deploy: 6f01030c4e
This commit is contained in:
1 parent
cf8df97ba7
commit
eeea067a72
566 files changed
+15370
-2688
No files matched your search
@@ -0,0 +1,47 @@
|
||||
<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=description content="JSON for Modern C++ is a header-only C++11 library that makes JSON a first-class data type."><meta name=author content="Niels Lohmann"><link href="https://json.nlohmann.me/features/json_view/editing/" rel="canonical"><link href=../generic_code/ rel=prev><link href=../images/ rel=next><link rel=icon href=../../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.8.0"><title>Editing a document - JSON for Modern C++</title><link rel=stylesheet href=../../../assets/stylesheets/main.57a0d79d.min.css><link rel=stylesheet href=../../../assets/stylesheets/palette.fb2fffe2.min.css><link rel=stylesheet href=../../../css/custom.css><link rel=stylesheet href=../../../css/brand.css><link rel=stylesheet href=../../../css/fig-sax.css><link rel=stylesheet href=../../../css/fig-jsonview.css><link rel=stylesheet href=../../../css/fig-exceptions.css><link rel=stylesheet href=../../../css/fig-pointer.css><link rel=stylesheet href=../../../css/fig-charts.css><link rel=stylesheet href=../../../css/fig-integration.css><link rel=stylesheet href=../../../css/fig-macros.css><script>__md_scope=new URL("../../..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script></head> <body dir=ltr data-md-color-scheme=default data-md-color-primary=custom data-md-color-accent=custom> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#editing-a-document class=md-skip> Skip to content </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header__inner md-grid" aria-label=Header> <a href=../../.. title="JSON for Modern C++" class="md-header__button md-logo" aria-label="JSON for Modern C++" data-md-component=logo> <img src=../../../images/wordmark-header.svg alt=logo> </a> <label class="md-header__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg> </label> <div class=md-header__title data-md-component=header-title> <div class=md-header__ellipsis> <div class=md-header__topic> <span class=md-ellipsis> JSON for Modern C++ </span> </div> <div class=md-header__topic data-md-component=header-topic> <span class=md-ellipsis> Editing a document </span> </div> </div> </div> <form class=md-header__option data-md-component=palette> <input class=md-option data-md-color-media="(prefers-color-scheme: light)" data-md-color-scheme=default data-md-color-primary=custom data-md-color-accent=custom aria-label="Switch to dark mode" type=radio name=__palette id=__palette_0> <label class="md-header__button md-icon" title="Switch to dark mode" for=__palette_1 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> <input class=md-option data-md-color-media="(prefers-color-scheme: dark)" data-md-color-scheme=slate data-md-color-primary=custom data-md-color-accent=custom aria-label="Switch to light mode" type=radio name=__palette id=__palette_1> <label class="md-header__button md-icon" title="Switch to light mode" for=__palette_0 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> </form> <script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefers-color-scheme: light)"),input=document.querySelector(media.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']");palette.color.media=input.getAttribute("data-md-color-media"),palette.color.scheme=input.getAttribute("data-md-color-scheme"),palette.color.primary=input.getAttribute("data-md-color-primary"),palette.color.accent=input.getAttribute("data-md-color-accent")}for(var[key,value]of Object.entries(palette.color))document.body.setAttribute("data-md-color-"+key,value)}</script> <label class="md-header__button md-icon" for=__search> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d=Line truncated
|
||||
"name":"cache",
|
||||
"port":6379,
|
||||
"price":<span class=nj-jsonview-bad>19.9</span>,
|
||||
"retries":3}</pre></div> <div><p class=nj-jsonview-cmp-h><code>ordered_json</code></p><p class=nj-jsonview-cmp-v>key order kept, numbers rewritten</p><pre>{"name":"cache",
|
||||
"host":"db2",
|
||||
"port":6379,
|
||||
"price":<span class=nj-jsonview-bad>19.9</span>,
|
||||
"retries":3}</pre></div> <div class=nj-jsonview-cmp--best><p class=nj-jsonview-cmp-h><code>json_editable_document</code></p><p class=nj-jsonview-cmp-v>order and spelling kept</p><pre>{"name":"cache",
|
||||
"host":"db2",
|
||||
"port":6379,
|
||||
"price":<span class=nj-jsonview-ok>19.90</span>,
|
||||
"retries":3}</pre></div> </div> <p>An editable document keeps both. <a href=../../../api/basic_json_view/dump/ ><code>dump()</code></a> of an edited document writes members in document order — a member <a href=../../../api/basic_json_document/set/ ><code>set</code></a> added goes at the end, exactly where it was inserted, and an <a href=../../../api/basic_json_document/erase/ ><code>erase</code></a>d member simply leaves a gap: everything around it keeps its place — and <a href=../../../api/basic_json_view/number_format/ ><code>number_format::source</code></a> keeps the exact spelling of every number an edit did not itself touch; a number an edit <em>did</em> touch is written the way <a href=../../../api/basic_json/dump/ ><code>BasicJsonType::dump()</code></a> would write it, since there is no source spelling for a brand new value. See <a href=../reading/#writing-a-view-back>Writing a view back</a>.</p> <details class=example> <summary>Example: patch a configuration, keeping member order and number spellings</summary> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf><iostream></span>
|
||||
<span class=cp>#include</span><span class=w> </span><span class=cpf><nlohmann/json_view.hpp></span>
|
||||
|
||||
<span class=k>using</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=p>;</span>
|
||||
<span class=k>using</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json_editable_document</span><span class=p>;</span>
|
||||
<span class=k>using</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json_editable_view</span><span class=p>;</span>
|
||||
|
||||
<span class=kt>int</span><span class=w> </span><span class=nf>main</span><span class=p>()</span>
|
||||
<span class=p>{</span>
|
||||
<span class=w> </span><span class=c1>// a configuration file, as it might be read from disk</span>
|
||||
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=w> </span><span class=n>text</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=sa>R</span><span class=s>"</span><span class=dl>(</span><span class=s>{"name": "cache", "host": "db1", "port": 6379, "price": 19.90}</span><span class=dl>)</span><span class=s>"</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>text</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=s>"</span><span class=se>\n\n</span><span class=s>"</span><span class=p>;</span>
|
||||
|
||||
<span class=w> </span><span class=c1>// patch two fields -- "price" is never touched</span>
|
||||
<span class=w> </span><span class=n>json_editable_document</span><span class=w> </span><span class=n>doc</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>json_editable_document</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>text</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>set</span><span class=p>(</span><span class=n>doc</span><span class=p>.</span><span class=n>root</span><span class=p>(),</span><span class=w> </span><span class=s>"host"</span><span class=p>,</span><span class=w> </span><span class=s>"db2"</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>set</span><span class=p>(</span><span class=n>doc</span><span class=p>.</span><span class=n>root</span><span class=p>(),</span><span class=w> </span><span class=s>"retries"</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=p>);</span>
|
||||
|
||||
<span class=w> </span><span class=c1>// member order (the new member at the end) and the untouched number's</span>
|
||||
<span class=w> </span><span class=c1>// exact spelling survive</span>
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>root</span><span class=p>().</span><span class=n>dump</span><span class=p>(</span><span class=mi>-1</span><span class=p>,</span><span class=w> </span><span class=sc>' '</span><span class=p>,</span><span class=w> </span><span class=nb>false</span><span class=p>,</span><span class=w> </span><span class=n>json_editable_view</span><span class=o>::</span><span class=n>number_format</span><span class=o>::</span><span class=n>source</span><span class=p>)</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span>
|
||||
|
||||
<span class=w> </span><span class=c1>// the same patch on a plain json value: keys are sorted (object_t is a</span>
|
||||
<span class=w> </span><span class=c1>// std::map), and "price" is rewritten even though the patch never</span>
|
||||
<span class=w> </span><span class=c1>// touched it</span>
|
||||
<span class=w> </span><span class=n>json</span><span class=w> </span><span class=n>plain</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>text</span><span class=p>);</span>
|
||||
<span class=w> </span><span class=n>plain</span><span class=p>[</span><span class=s>"host"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"db2"</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>plain</span><span class=p>[</span><span class=s>"retries"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>3</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=n>plain</span><span class=p>.</span><span class=n>dump</span><span class=p>()</span><span class=w> </span><span class=o><<</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span>
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code><span class=p>{</span><span class=nt>"name"</span><span class=p>:</span><span class=w> </span><span class=s2>"cache"</span><span class=p>,</span><span class=w> </span><span class=nt>"host"</span><span class=p>:</span><span class=w> </span><span class=s2>"db1"</span><span class=p>,</span><span class=w> </span><span class=nt>"port"</span><span class=p>:</span><span class=w> </span><span class=mi>6379</span><span class=p>,</span><span class=w> </span><span class=nt>"price"</span><span class=p>:</span><span class=w> </span><span class=mf>19.90</span><span class=p>}</span>
|
||||
|
||||
<span class=p>{</span><span class=nt>"name"</span><span class=p>:</span><span class=s2>"cache"</span><span class=p>,</span><span class=nt>"host"</span><span class=p>:</span><span class=s2>"db2"</span><span class=p>,</span><span class=nt>"port"</span><span class=p>:</span><span class=mi>6379</span><span class=p>,</span><span class=nt>"price"</span><span class=p>:</span><span class=mf>19.90</span><span class=p>,</span><span class=nt>"retries"</span><span class=p>:</span><span class=mi>3</span><span class=p>}</span>
|
||||
<span class=p>{</span><span class=nt>"host"</span><span class=p>:</span><span class=s2>"db2"</span><span class=p>,</span><span class=nt>"name"</span><span class=p>:</span><span class=s2>"cache"</span><span class=p>,</span><span class=nt>"port"</span><span class=p>:</span><span class=mi>6379</span><span class=p>,</span><span class=nt>"price"</span><span class=p>:</span><span class=mf>19.9</span><span class=p>,</span><span class=nt>"retries"</span><span class=p>:</span><span class=mi>3</span><span class=p>}</span>
|
||||
</code></pre></div> </details> <h2 id=what-stays-valid-and-what-an-edit-costs>What stays valid, and what an edit costs<a class=headerlink href=#what-stays-valid-and-what-an-edit-costs title="Permanent link">¶</a></h2> <p>The source text itself is <strong>never written</strong>, and the parsed index never moves — a value keeps the node it was parsed into for as long as it is not itself replaced. So every <a href=../../../api/basic_json_view/ >view</a> taken before an edit, including a previously obtained <a href=../../../api/basic_json_document/root/ ><code>root()</code></a>, stays valid and, if it still refers to the edited value, sees the edit; a view of a value a later edit drops or replaces just keeps showing what it last held. New values go to storage the document allocates and owns on demand. The one thing an edit does invalidate is the <strong>iterators</strong> taken over an edited array or object: the first time an element is added to it, inserted into it, erased from it, or replaced by a value that spans a different number of nodes, its elements move from the parsed, fixed layout to a growable block of links so that <a href=../../../api/basic_json_document/push_back/ ><code>push_back</code></a> can later grow it in amortized constant time — existing elements are not touched, but an iterator that was walking the old layout no longer matches. A string obtained with <a href=../../../api/basic_json_view/get_string/ ><code>get_string()</code></a> is unaffected either way and stays valid across further edits. See <a href=../../../api/basic_json_document/#edits><code>basic_json_document</code>'s Edits</a> for the details, and <a href=../../../api/basic_json_document/set/#exception-safety><code>set</code>'s Exception safety</a> for what an edit guarantees if it throws (the <em>basic</em> guarantee, not the strong one <code>dump()</code> and the read-only functions provide). How edits are kept in the index is described in the <a href=../../../home/architecture/#node-index-of-json-views>architecture overview</a>.</p> <p>Step through the edits of a small document (the node fields follow the <a href=../../../home/architecture/#node-index-of-json-views>architecture overview</a>):</p> <div class=nj-jsonview-steps data-nj-jsonview-steps> <figure class=nj-jsonview-step data-label="After parsing"> <div class=nj-jsonview-scroll> <svg class="nj-fig nj-jsonview nj-jsonview-editfig" viewbox="0 0 840 372" role=img aria-labelledby="fig-jve0-title fig-jve0-title-d" xmlns=http://www.w3.org/2000/svg> <title id=fig-jve0-title>Step 1 of 5: parsed</title> <desc id=fig-jve0-title-d>After parse: nine nodes, nothing owned yet. The dump with number_format::source is {"port":6379,"price":19.90,"tags":["eu","a\"b"]}.</desc> <defs> <marker id=jve0-line viewbox="0 0 10 10" refx=9 refy=5 markerwidth=6.5 markerheight=6.5 orient=auto-start-reverse><path class="nj-jsonview-c-line nj-jsonview-head" d="M0 1 L10 5 L0 9 z"/></marker> <marker id=jve0-own viewbox="0 0 10 10" refx=9 refy=5 markerwidth=6.5 markerheight=6.5 orient=auto-start-reverse><path class="nj-jsonview-c-own nj-jsonview-head" d="M0 1 L10 5 L0 9 z"/></marker> <marker id=jve0-struct viewbox="0 0 10 10" refx=9 refy=5 markerwidth=6.5 markerheight=6.5 orient=auto-start-reverse><path class="nj-jsonview-c-struct nj-jsonview-head" d="M0 1 L10 5 L0 9 z"/></marker> <marker id=jve0-bad viewbox="0 0 10 10" refx=9 refy=5 markerwidth=6.5 markerheight=6.5 orient=auto-start-reverse><path class="nj-jsonview-c-bad nj-jsonview-head" d="M0 1 L10 5 L0 9 z"/></marker> </defs> <text class="nj-jsonview-note nj-jsonview-strong" x=16 y=22 xml:space=preserve>parsed index: fixed, never moves</text> <text class=nj-jsonview-note x=824 y=22 text-anchor=end xml:space=preserve>the source text is never written</text> <rect x=36 y=34 width=84 height=50 rx=5 class="nj-jsonview-node nj-jsonview-c-struct"/> <text class=nj-jsonview-tiny x=42 y=47 xml:space=preserve>0</text> <text class="nj-jsonview-kind nj-jsonview-xs nj-jsonview-c-struct" x=78 y=61 text-anchor=middle xml:space=preserve>object</text> <text class="nj-jsonview-mono nj-jsonview-sm" x=78 y=77 text-anchor=middle xml:space=preserve>{ } 3</text> <rect x=124 y=34 width=84 height=50 rx=5 class="nj-jsonview-node nj-jsonview-c-key"/> <text class=nj-jsonview-tiny x=130 y=47 xml:space=preserve>1</text> <text class="nj-jsonview-kind nj-jsonview-xs nj-jsonview-c-key" x=166 y=61 text-anchor=middle xml:space=preserve>key</text> <text class="nj-jsonview-mono nj-jsonview-sm" x=166 y=77 text-anchor=middle xml:space=preserve>port</text> <rect x=212 y=34 width=84 height=50 rx=5 class="nj-jsonview-node nj-jsonview-c-num"/> <text class=nj-jsonview-tiny x=218 y=47 xml:space=preserve>2</text> <text class="nj-jsonview-kind nj-jsonview-xs nj-jsonview-c-num" x=254 y=61 text-anchor=middle xml:space=preserve>uint</text> <text class="nj-jsonview-mono nj-jsonview-sm" x=254 y=77 text-anchor=middle xml:space=preserve>Line truncated
|
||||
@@ -0,0 +1,125 @@
|
||||
# Editing a document
|
||||
|
||||
A [`json_document`](https://json.nlohmann.me/api/json_document/index.md)/[`json_view`](https://json.nlohmann.me/api/json_view/index.md) lets you look at a parsed text without copying it, but not change it. [`basic_json_document<BasicJsonType, view_mode::editable>`](https://json.nlohmann.me/api/basic_json_document/index.md) — more conveniently spelled [`json_editable_document`](https://json.nlohmann.me/api/json_editable_document/index.md) or [`ordered_json_editable_document`](https://json.nlohmann.me/api/ordered_json_editable_document/index.md) — also lets you [`set`](https://json.nlohmann.me/api/basic_json_document/set/index.md) a value, [`push_back`](https://json.nlohmann.me/api/basic_json_document/push_back/index.md) onto or [`insert`](https://json.nlohmann.me/api/basic_json_document/insert/index.md) into an array, and [`erase`](https://json.nlohmann.me/api/basic_json_document/erase/index.md) an object member or an array element, still without ever building a `basic_json` tree for parts you do not touch.
|
||||
|
||||
The [mode](https://json.nlohmann.me/api/view_mode/index.md) defaults to `view_mode::read_only`, so `json_document`/`ordered_json_document` are unaffected — they carry none of the bookkeeping edits need, and calling `set`/`push_back`/`insert`/`erase` on one is a compile error, not a runtime one.
|
||||
|
||||
## Why: editing without reformatting
|
||||
|
||||
A price like `19.90` is exactly the kind of value that makes editing a `json` or `ordered_json` value in place lossy. Say you parse a configuration file, patch one field, and write it back:
|
||||
|
||||
- **`json`** re-sorts every key on the way in (`object_t` is a `std::map`) and rewrites every number to its shortest round-trip form on the way out — a one-field patch turns into a diff that reorders the whole file and rewrites `19.90` to `19.9`.
|
||||
- **`ordered_json`** keeps the key order, but still rewrites every number the same way: parsing has already reduced it to a `double`/`int64_t`, and there is no way back to how it was spelled in the source text.
|
||||
|
||||
The patch of the example below (set `"host"`, add `"retries"`) written back by each of them:
|
||||
|
||||
`json`
|
||||
|
||||
keys sorted, numbers rewritten
|
||||
|
||||
```
|
||||
{"host":"db2",
|
||||
"name":"cache",
|
||||
"port":6379,
|
||||
"price":19.9,
|
||||
"retries":3}
|
||||
```
|
||||
|
||||
`ordered_json`
|
||||
|
||||
key order kept, numbers rewritten
|
||||
|
||||
```
|
||||
{"name":"cache",
|
||||
"host":"db2",
|
||||
"port":6379,
|
||||
"price":19.9,
|
||||
"retries":3}
|
||||
```
|
||||
|
||||
`json_editable_document`
|
||||
|
||||
order and spelling kept
|
||||
|
||||
```
|
||||
{"name":"cache",
|
||||
"host":"db2",
|
||||
"port":6379,
|
||||
"price":19.90,
|
||||
"retries":3}
|
||||
```
|
||||
|
||||
An editable document keeps both. [`dump()`](https://json.nlohmann.me/api/basic_json_view/dump/index.md) of an edited document writes members in document order — a member [`set`](https://json.nlohmann.me/api/basic_json_document/set/index.md) added goes at the end, exactly where it was inserted, and an [`erase`](https://json.nlohmann.me/api/basic_json_document/erase/index.md)d member simply leaves a gap: everything around it keeps its place — and [`number_format::source`](https://json.nlohmann.me/api/basic_json_view/number_format/index.md) keeps the exact spelling of every number an edit did not itself touch; a number an edit *did* touch is written the way [`BasicJsonType::dump()`](https://json.nlohmann.me/api/basic_json/dump/index.md) would write it, since there is no source spelling for a brand new value. See [Writing a view back](https://json.nlohmann.me/features/json_view/reading/#writing-a-view-back).
|
||||
|
||||
Example: patch a configuration, keeping member order and number spellings
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json_view.hpp>
|
||||
|
||||
using nlohmann::json;
|
||||
using nlohmann::json_editable_document;
|
||||
using nlohmann::json_editable_view;
|
||||
|
||||
int main()
|
||||
{
|
||||
// a configuration file, as it might be read from disk
|
||||
const std::string text = R"({"name": "cache", "host": "db1", "port": 6379, "price": 19.90})";
|
||||
std::cout << text << "\n\n";
|
||||
|
||||
// patch two fields -- "price" is never touched
|
||||
json_editable_document doc = json_editable_document::parse(text);
|
||||
doc.set(doc.root(), "host", "db2");
|
||||
doc.set(doc.root(), "retries", 3);
|
||||
|
||||
// member order (the new member at the end) and the untouched number's
|
||||
// exact spelling survive
|
||||
std::cout << doc.root().dump(-1, ' ', false, json_editable_view::number_format::source) << '\n';
|
||||
|
||||
// the same patch on a plain json value: keys are sorted (object_t is a
|
||||
// std::map), and "price" is rewritten even though the patch never
|
||||
// touched it
|
||||
json plain = json::parse(text);
|
||||
plain["host"] = "db2";
|
||||
plain["retries"] = 3;
|
||||
std::cout << plain.dump() << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
{"name": "cache", "host": "db1", "port": 6379, "price": 19.90}
|
||||
|
||||
{"name":"cache","host":"db2","port":6379,"price":19.90,"retries":3}
|
||||
{"host":"db2","name":"cache","port":6379,"price":19.9,"retries":3}
|
||||
```
|
||||
|
||||
## What stays valid, and what an edit costs
|
||||
|
||||
The source text itself is **never written**, and the parsed index never moves — a value keeps the node it was parsed into for as long as it is not itself replaced. So every [view](https://json.nlohmann.me/api/basic_json_view/index.md) taken before an edit, including a previously obtained [`root()`](https://json.nlohmann.me/api/basic_json_document/root/index.md), stays valid and, if it still refers to the edited value, sees the edit; a view of a value a later edit drops or replaces just keeps showing what it last held. New values go to storage the document allocates and owns on demand. The one thing an edit does invalidate is the **iterators** taken over an edited array or object: the first time an element is added to it, inserted into it, erased from it, or replaced by a value that spans a different number of nodes, its elements move from the parsed, fixed layout to a growable block of links so that [`push_back`](https://json.nlohmann.me/api/basic_json_document/push_back/index.md) can later grow it in amortized constant time — existing elements are not touched, but an iterator that was walking the old layout no longer matches. A string obtained with [`get_string()`](https://json.nlohmann.me/api/basic_json_view/get_string/index.md) is unaffected either way and stays valid across further edits. See [`basic_json_document`'s Edits](https://json.nlohmann.me/api/basic_json_document/#edits) for the details, and [`set`'s Exception safety](https://json.nlohmann.me/api/basic_json_document/set/#exception-safety) for what an edit guarantees if it throws (the *basic* guarantee, not the strong one `dump()` and the read-only functions provide). How edits are kept in the index is described in the [architecture overview](https://json.nlohmann.me/home/architecture/#node-index-of-json-views).
|
||||
|
||||
Step through the edits of a small document (the node fields follow the [architecture overview](https://json.nlohmann.me/home/architecture/#node-index-of-json-views)):
|
||||
|
||||
Step 1 of 5. After parsing: nine nodes in the parsed index, no owned storage yet.
|
||||
|
||||
Step 2 of 5. `doc.set(doc.root(), "port", 6380)` overwrites the node of the integer in place; no member is added or removed, so the object keeps its parsed layout.
|
||||
|
||||
Step 3 of 5. `doc.erase(doc.root()["tags"], 0)`: the array is edited for the first time, so its elements move to a block of links in owned storage. The node of `"eu"` stays in the index, but nothing refers to it any more; iterators over the array taken before are invalid.
|
||||
|
||||
Step 4 of 5. `doc.push_back(doc.root()["tags"], "new")`: the new string gets its own node, its text goes to the buffer of edited text, and a link to it is appended to the block of the array.
|
||||
|
||||
Step 5 of 5. `doc.set(doc.root(), "retries", 3)`: a new member, so the object moves to a block too: copies of its keys, links to the values it already had, then the new key and a link to the new integer.
|
||||
|
||||
The node index and the owned storage of the document after each of five edits. Use *Back*, *Next*, or the numbered buttons to switch between the steps; without JavaScript all steps are shown one below the other.
|
||||
|
||||
## See also
|
||||
|
||||
- [Zero-copy JSON views](https://json.nlohmann.me/features/json_view/index.md) - overview
|
||||
- [`json_editable_document`](https://json.nlohmann.me/api/json_editable_document/index.md) - and [`ordered_json_editable_document`](https://json.nlohmann.me/api/ordered_json_editable_document/index.md) - the documents that can be edited in place
|
||||
- [`basic_json_document`'s Edits](https://json.nlohmann.me/api/basic_json_document/#edits) - the rules of edits in detail
|
||||
- [Differences from `basic_json`](https://json.nlohmann.me/features/json_view/differences/#exception-context) - source positions after edits
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0 unreleased.
|
||||
Reference in new issue
Block a user