This commit is contained in:
nlohmann committed 2026-11-01 16:56:42 +00:00
1 parent cf84df303b
commit 264aee6773
39 files changed
+586 -498

No files matched your search

+15 -5
View File
@@ -1,4 +1,4 @@
<!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/" rel="canonical"><link href=../types/template_parameters/ rel=prev><link href=../../integration/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>Zero-copy JSON views - JSON for Modern C++</title><link rel=stylesheet href=../../assets/stylesheets/main.ec1eaa64.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.ab4e12ef.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=#zero-copy-json-views 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> Zero-copy JSON views </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="M9.5 3A6.5 6.5 0 0 1 16 9Line truncated
<!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/" rel="canonical"><link href=../types/template_parameters/ rel=prev><link href=../../integration/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>Zero-copy JSON views - JSON for Modern C++</title><link rel=stylesheet href=../../assets/stylesheets/main.ec1eaa64.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.ab4e12ef.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=#zero-copy-json-views 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> Zero-copy JSON views </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="M9.5 3A6.5 6.5 0 0 1 16 9Line truncated
<span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;nlohmann/json_view.hpp&gt;</span>
<span class=k>using</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json_document</span><span class=p>;</span>
@@ -53,7 +53,7 @@
<span class=kc>true</span>
<span class=kc>true</span>
<span class=kc>true</span>
</code></pre></div> </details> <h2 id=what-is-the-same-as-parse>What is the same as <code>parse()</code><a class=headerlink href=#what-is-the-same-as-parse title="Permanent link">&para;</a></h2> <ul> <li><strong>Accept/reject.</strong> <a href=../../api/basic_json_document/accept/ ><code>accept()</code></a> and <a href=../../api/basic_json_document/parse/ ><code>parse()</code></a> accept and reject exactly the same inputs as <a href=../../api/basic_json/accept/ ><code>basic_json::accept()</code></a>/<a href=../../api/basic_json/parse/ ><code>basic_json::parse()</code></a>, with the same <code>ignore_comments</code> and <code>ignore_trailing_commas</code> options.</li> <li><strong>Errors.</strong> A failing parse throws the same exception — the same id, message, and position — because on failure the library's own parser is run on the same bytes to produce the diagnostic. Valid input never pays for this, and the replay builds no values: it costs about a lexing pass up to the error. <code class=highlight><span class=n>allow_exceptions</span><span class=w> </span><span class=o>==</span><span class=w> </span><span class=nb>false</span></code> skips the replay and gives a <a href=../../api/basic_json_document/is_discarded/ >discarded</a> document instead of throwing, just as it gives a discarded value for <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code>.</li> <li><strong>Number classification.</strong> An integer literal that does not fit into the 64-bit integer type becomes a floating-point value, exactly as it does for <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code>.</li> <li><strong>Macros.</strong> <a href=../../api/macros/json_strict_nul_handling/ ><code>JSON_STRICT_NUL_HANDLING</code></a> and <a href=../../api/macros/json_noexception/ ><code>JSON_NOEXCEPTION</code></a>/<a href=../../api/macros/json_throw_user/ ><code>JSON_THROW_USER</code></a> behave the same way they do for <code>&lt;nlohmann/json.hpp&gt;</code>. These are the macros that change what the parser accepts or how it reports errors. The others either do not apply (<a href=../../api/macros/json_diagnostics/ ><code>JSON_DIAGNOSTICS</code></a> needs parent pointers in <code>basic_json</code> values) or only affect the values <code>materialize()</code> produces, through <code>BasicJsonType</code>.</li> </ul> <h2 id=what-is-different>What is different<a class=headerlink href=#what-is-different title="Permanent link">&para;</a></h2> <ul> <li><strong>Only 64-bit integers.</strong> <code>basic_json_document&lt;BasicJsonType&gt;</code> requires <code>BasicJsonType::number_integer_t</code> and <code>number_unsigned_t</code> to both be 64 bits wide; this is a compile-time <code class=highlight><span class=k>static_assert</span></code>.</li> <li><strong>A 4 <abbr title="Gibibyte (2^30 bytes)">GiB</abbr> input limit.</strong> An input of 4294967280 bytes (4 <abbr title="Gibibyte (2^30 bytes)">GiB</abbr> minus 16 bytes) or more throws <a href=../../home/exceptions/#jsonexceptionout_of_range416><code>out_of_range.416</code></a>, a limit <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code> does not have. It keeps an index entry at 16 bytes: offsets and counts are 32 bits wide. The limit is 16 bytes below 2^32, because the parser reads in 16-byte steps, and a position one step past the end must still fit.</li> <li><strong>A stream is always read to its end.</strong> There is no partial/streaming read of an <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>istream</span></code>: the stream is read to its end into a buffer the document owns, and parsing starts after that.</li> <li><strong>Fewer source positions after edits.</strong> With <a href=../../api/macros/json_diagnostic_positions/ ><code>JSON_DIAGNOSTIC_POSITIONS</code></a> enabled, <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a> sets the same positions as <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code>. In an <a href=../../api/json_editable_document/ >editable document</a>, a value written by an edit has none, and neither has an array or object whose elements changed or whose last element has none; a <code>basic_json</code> value keeps its positions when it is changed. See <a href=../../api/basic_json_view/materialize/#notes><code>materialize()</code></a>.</li> <li><strong>Objects iterate in document order.</strong> <a href=../../api/basic_json_view/begin/ ><code>begin()</code></a>/ <a href=../../api/basic_json_view/end/ ><code>end()</code></a> and <a href=../../api/basic_json_view/items/ ><code>items()</code></a> visit an object's members in the order they appear in the source text. <code>basic_json</code>'sLine truncated
</code></pre></div> </details> <h2 id=what-is-the-same-as-parse>What is the same as <code>parse()</code><a class=headerlink href=#what-is-the-same-as-parse title="Permanent link">&para;</a></h2> <ul> <li><strong>Accept/reject.</strong> <a href=../../api/basic_json_document/accept/ ><code>accept()</code></a> and <a href=../../api/basic_json_document/parse/ ><code>parse()</code></a> accept and reject exactly the same inputs as <a href=../../api/basic_json/accept/ ><code>basic_json::accept()</code></a>/<a href=../../api/basic_json/parse/ ><code>basic_json::parse()</code></a>, with the same <code>ignore_comments</code> and <code>ignore_trailing_commas</code> options.</li> <li><strong>Errors.</strong> A failing parse throws the same exception — the same id, message, and position — because on failure the library's own parser is run on the same bytes to produce the diagnostic. Valid input never pays for this, and the replay builds no values: it costs about a lexing pass up to the error. <code class=highlight><span class=n>allow_exceptions</span><span class=w> </span><span class=o>==</span><span class=w> </span><span class=nb>false</span></code> skips the replay and gives a <a href=../../api/basic_json_document/is_discarded/ >discarded</a> document instead of throwing, just as it gives a discarded value for <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code>.</li> <li><strong>Number classification.</strong> An integer literal that does not fit into the 64-bit integer type becomes a floating-point value, exactly as it does for <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code>.</li> <li> <p><strong>Macros.</strong> <a href=../../api/macros/json_strict_nul_handling/ ><code>JSON_STRICT_NUL_HANDLING</code></a> and <a href=../../api/macros/json_noexception/ ><code>JSON_NOEXCEPTION</code></a>/<a href=../../api/macros/json_throw_user/ ><code>JSON_THROW_USER</code></a> behave the same way they do for <code>&lt;nlohmann/json.hpp&gt;</code>. These are the macros that change what the parser accepts or how it reports errors. Two more macros add context to the exceptions of views, as they do for those of <code class=highlight><span class=n>basic_json</span></code>:</p> <ul> <li>With <a href=../../api/macros/json_diagnostics/ ><code>JSON_DIAGNOSTICS</code></a>, an exception names the <abbr title="JavaScript Object Notation">JSON</abbr> Pointer path of the value within the document.</li> <li>With <a href=../../api/macros/json_diagnostic_positions/ ><code>JSON_DIAGNOSTIC_POSITIONS</code></a>, an exception names the bytes of the value in the source text.</li> </ul> <p>A view has neither parent pointers nor stored positions, so both are found from the document's index when the exception is thrown. This takes time linear in the size of the document. One exception has neither: <code>key()</code> of an iterator over an array or a primitive value (<a href=../../home/exceptions/#jsonexceptioninvalid_iterator207><code>invalid_iterator.207</code></a>), because a view's iterator does not know the value it iterates over.</p> <p>The other macros only affect the values <code>materialize()</code> produces, through <code>BasicJsonType</code>.</p> </li> </ul> <h2 id=what-is-different>What is different<a class=headerlink href=#what-is-different title="Permanent link">&para;</a></h2> <ul> <li><strong>Only 64-bit integers.</strong> <code>basic_json_document&lt;BasicJsonType&gt;</code> requires <code>BasicJsonType::number_integer_t</code> and <code>number_unsigned_t</code> to both be 64 bits wide; this is a compile-time <code class=highlight><span class=k>static_assert</span></code>.</li> <li><strong>A 4 <abbr title="Gibibyte (2^30 bytes)">GiB</abbr> input limit.</strong> An input of 4294967280 bytes (4 <abbr title="Gibibyte (2^30 bytes)">GiB</abbr> minus 16 bytes) or more throws <a href=../../home/exceptions/#jsonexceptionout_of_range416><code>out_of_range.416</code></a>, a limit <code class=highlight><span class=n>basic_json</span><span class=o>::</span><span class=n>parse</span><span class=p>()</span></code> does not have. It keeps an index entry at 16 bytes: offsets and counts are 32 bits wide. The limit is 16 bytes below 2^32, because the parser reads in 16-byte steps, and a position one step past the end must still fit.</li> <li><strong>A stream is always read to its end.</strong> There is no partial/streaming read of an <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>istream</span></code>: the stream is read to its end into a buffer the document owns, and parsing starts after that.</li> <li><strong>Fewer source positions after edits.</strong> With <a href=../../api/macros/json_diagnostic_positions/ ><code>JSON_DIAGNOSTIC_POSITIONS</code></a> enabled, <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a> sets the same poLine truncated
<span class=n>json_view</span><span class=w> </span><span class=n>last</span><span class=p>;</span>
<span class=k>for</span><span class=w> </span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>item</span><span class=w> </span><span class=o>:</span><span class=w> </span><span class=n>view</span><span class=p>.</span><span class=n>items</span><span class=p>())</span>
<span class=p>{</span>
@@ -62,7 +62,17 @@
<span class=w> </span><span class=n>last</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>item</span><span class=p>.</span><span class=n>value</span><span class=p>();</span>
<span class=w> </span><span class=p>}</span>
<span class=p>}</span>
</code></pre></div> <p>If you cannot trust the source text to have unique keys, check <a href=../../api/basic_json_view/size/ ><code>size()</code></a> against the number of distinct keys, or reject duplicates when iterating.</p> <h2 id=getting-values-out-without-copying>Getting values out without copying<a class=headerlink href=#getting-values-out-without-copying title="Permanent link">&para;</a></h2> <p><a href=../../api/basic_json_view/get/ ><code>get&lt;T&gt;()</code></a> converts most <code>T</code> directly from the flat index, without ever building a <code>basic_json</code> value for the conversion: <code class=highlight><span class=kt>bool</span></code>, arithmetic types, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>nullptr_t</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string</span></code>/other <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>basic_string</span></code>s (copied once), <code>basic_json_view</code> itself, the standard containers and other types the library converts (<code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>vector</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>map</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>list</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>array</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>pair</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>tuple</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>optional</span></code>, ...), and the types of the <code>NLOHMANN_DEFINE_TYPE_*</code> and <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> macros. Types whose <code>from_json()</code> is written for <code>basic_json</code> only go through <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a><code>.get&lt;T&gt;()</code> instead: the subtree is built into a real <code>basic_json</code> value first, exactly as <a href=../../api/basic_json/parse/ ><code>parse()</code></a> would, and converted from there. See <a href=#writing-generic-code>Writing generic code</a> for how to write a <code>from_json()</code> that reads views.</p> <p>Two conversions never copy at all:</p> <ul> <li><a href=../../api/basic_json_view/get_string/ ><code>get_string()</code></a> (equivalently, <code class=highlight><span class=n>get</span><span class=o>&lt;</span><span class=n>string_view_t</span><span class=o>&gt;</span><span class=p>()</span></code>) returns a string as a <code>string_view_t</code> pointing into the document's <a href=../../api/basic_json_document/source/ ><code>source()</code></a> text — or, for a string that contains escape sequences, into the document's own buffer of decoded strings — instead of allocating a new <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string</span></code>.</li> <li><a href=../../api/basic_json_view/number_token/ ><code>number_token()</code></a> returns a number exactly as it was written in the source, e.g. <code class=highlight><span class=s>"1.50"</span></code>, <code class=highlight><span class=s>"1E2"</span></code>, or an integer with more digits than any number type holds, instead of rounding it into a <code class=highlight><span class=kt>double</span></code>/<code class=highlight><span class=kt>int64_t</span></code> the way <code class=highlight><span class=n>get</span><span class=o>&lt;</span><span class=n>T</span><span class=o>&gt;</span><span class=p>()</span></code> (and <a href=../../api/basic_json/parse/ ><code>basic_json::parse()</code></a>) would.</li> </ul> <p>Both results are only valid as long as the view — and, for a string with no escapes, the borrowed source text — is.</p> <h2 id=writing-generic-code>Writing generic code<a class=headerlink href=#writing-generic-code title="Permanent link">&para;</a></h2> <p>A view's type names its <code>BasicJsonType</code> and its <a href=../../api/view_mode/ ><code>view_mode</code></a>: <a href=../../api/json_view/ ><code>json_view</code></a> is <code class=highlight><span class=n>basic_json_view</span><span class=o>&lt;</span><span class=n>json</span><span class=p>,</span><span class=w> </span><span class=n>view_mode</span><span class=o>::</span><span class=n>read_only</span><span class=o>&gt;</span></code>, and <a href=../../api/json_editable_view/ ><code>json_editable_view</code></a> is <code class=highlight><span class=n>basic_json_view</span><span class=o>&lt;</span><span class=n>json</span><span class=p>,</span><span class=w> </span><span class=n>view_mode</span><span class=o>::</span><span class=n>editable</span><span class=o>&gt;</span></code>. These are different typeLine truncated
</code></pre></div> <p>If you cannot trust the source text to have unique keys, check <a href=../../api/basic_json_view/size/ ><code>size()</code></a> against the number of distinct keys, or reject duplicates when iterating.</p> <h2 id=getting-values-out-without-copying>Getting values out without copying<a class=headerlink href=#getting-values-out-without-copying title="Permanent link">&para;</a></h2> <p><a href=../../api/basic_json_view/get/ ><code>get&lt;T&gt;()</code></a> converts most <code>T</code> directly from the flat index, without ever building a <code>basic_json</code> value for the conversion: <code class=highlight><span class=kt>bool</span></code>, arithmetic types, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>nullptr_t</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string</span></code>/other <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>basic_string</span></code>s (copied once), <code>basic_json_view</code> itself, the standard containers and other types the library converts (<code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>vector</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>map</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>list</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>array</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>pair</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>tuple</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>optional</span></code>, ...), and the types of the <code>NLOHMANN_DEFINE_TYPE_*</code> and <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> macros. Types whose <code>from_json()</code> is written for <code>basic_json</code> only go through <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a><code>.get&lt;T&gt;()</code> instead: the subtree is built into a real <code>basic_json</code> value first, exactly as <a href=../../api/basic_json/parse/ ><code>parse()</code></a> would, and converted from there. See <a href=#writing-generic-code>Writing generic code</a> for how to write a <code>from_json()</code> that reads views.</p> <p>Two conversions never copy at all:</p> <ul> <li><a href=../../api/basic_json_view/get_string/ ><code>get_string()</code></a> (equivalently, <code class=highlight><span class=n>get</span><span class=o>&lt;</span><span class=n>string_view_t</span><span class=o>&gt;</span><span class=p>()</span></code>) returns a string as a <code>string_view_t</code> pointing into the document's <a href=../../api/basic_json_document/source/ ><code>source()</code></a> text — or, for a string that contains escape sequences, into the document's own buffer of decoded strings — instead of allocating a new <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string</span></code>.</li> <li><a href=../../api/basic_json_view/number_token/ ><code>number_token()</code></a> returns a number exactly as it was written in the source, e.g. <code class=highlight><span class=s>"1.50"</span></code>, <code class=highlight><span class=s>"1E2"</span></code>, or an integer with more digits than any number type holds, instead of rounding it into a <code class=highlight><span class=kt>double</span></code>/<code class=highlight><span class=kt>int64_t</span></code> the way <code class=highlight><span class=n>get</span><span class=o>&lt;</span><span class=n>T</span><span class=o>&gt;</span><span class=p>()</span></code> (and <a href=../../api/basic_json/parse/ ><code>basic_json::parse()</code></a>) would.</li> </ul> <p>Both results are only valid as long as the view — and, for a string with no escapes, the borrowed source text — is.</p> <h3 id=string_view-members><code>string_view</code> members<a class=headerlink href=#string_view-members title="Permanent link">&para;</a></h3> <p>A struct whose member is a <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string_view</span></code> (C++17) can be decoded from a view with the <code>NLOHMANN_DEFINE_TYPE_*</code> macros, and the member is not copied either: for a string without escape sequences it points into the document's source text, and for a string with escape sequences into the document's buffer of decoded strings. The member is valid as long as the document is alive and, for a document that <a href=#ownership-and-lifetime>borrows its source text</a> (as <a href=../../api/basic_json_document/parse/ ><code>parse()</code></a> does for an lvalue <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>string</span></code>, a <code class=highlight><span class=n>std</spLine truncated
<span class=p>{</span>
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string_view</span><span class=w> </span><span class=n>name</span><span class=p>;</span>
<span class=w> </span><span class=kt>int</span><span class=w> </span><span class=n>count</span><span class=p>;</span>
<span class=w> </span><span class=n>NLOHMANN_DEFINE_TYPE_INTRUSIVE</span><span class=p>(</span><span class=n>record</span><span class=p>,</span><span class=w> </span><span class=n>name</span><span class=p>,</span><span class=w> </span><span class=n>count</span><span class=p>)</span>
<span class=p>};</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": "widget", "count": 3}</span><span class=dl>)</span><span class=s>"</span><span class=p>;</span>
<span class=k>const</span><span class=w> </span><span class=n>json_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_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=c1>// borrows text</span>
<span class=k>const</span><span class=w> </span><span class=n>record</span><span class=w> </span><span class=n>r</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>get</span><span class=o>&lt;</span><span class=n>record</span><span class=o>&gt;</span><span class=p>();</span><span class=w> </span><span class=c1>// r.name points into text, valid while text and doc are</span>
</code></pre></div> <div class="admonition warning"> <p class=admonition-title>Decoding into a <code>string_view</code> from a <code>json</code> value dangles at once</p> <p>The same struct also compiles with <code class=highlight><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=n>get</span><span class=o>&lt;</span><span class=n>record</span><span class=o>&gt;</span><span class=p>()</span></code>, but there <code>name</code> points into the temporary <code>json</code> value, which is destroyed at the end of the statement. Use a named <a href=../../api/json_document/ ><code>json_document</code></a>, as above, to decode such a struct.</p> </div> <h2 id=writing-generic-code>Writing generic code<a class=headerlink href=#writing-generic-code title="Permanent link">&para;</a></h2> <p>A view's type names its <code>BasicJsonType</code> and its <a href=../../api/view_mode/ ><code>view_mode</code></a>: <a href=../../api/json_view/ ><code>json_view</code></a> is <code class=highlight><span class=n>basic_json_view</span><span class=o>&lt;</span><span class=n>json</span><span class=p>,</span><span class=w> </span><span class=n>view_mode</span><span class=o>::</span><span class=n>read_only</span><span class=o>&gt;</span></code>, and <a href=../../api/json_editable_view/ ><code>json_editable_view</code></a> is <code class=highlight><span class=n>basic_json_view</span><span class=o>&lt;</span><span class=n>json</span><span class=p>,</span><span class=w> </span><span class=n>view_mode</span><span class=o>::</span><span class=n>editable</span><span class=o>&gt;</span></code>. These are different types. The only conversion between them turns a view of a read-only document into a view of an editable document of the same <code>BasicJsonType</code>, so a function written for one shortcut accepts few other views:</p> <div class=highlight><pre><span></span><code><span class=kt>void</span><span class=w> </span><span class=nf>print_names</span><span class=p>(</span><span class=n>json_view</span><span class=w> </span><span class=n>v</span><span class=p>);</span><span class=w> </span><span class=c1>// accepts neither an ordered_json_view nor a json_editable_view</span>
<span class=kt>void</span><span class=w> </span><span class=nf>print_names</span><span class=p>(</span><span class=n>json_editable_view</span><span class=w> </span><span class=n>v</span><span class=p>);</span><span class=w> </span><span class=c1>// also accepts a json_view, but no ordered_json_view</span>
</code></pre></div> <p>This is the same pitfall as a <code>to_json</code>/<code>from_json</code> written for <code>json</code> instead of any <code>BasicJsonType</code>, which then does not work for <code>ordered_json</code>. The shortcuts are for declaring documents and views; a function that takes a view names the views it accepts with a template:</p> <div class=highlight><pre><span></span><code><span class=c1>// views of editable documents only</span>
<span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>BasicJsonType</span><span class=o>&gt;</span>
@@ -82,7 +92,7 @@
<span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>name</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"name"</span><span class=p>).</span><span class=k>template</span><span class=w> </span><span class=n>get</span><span class=o>&lt;</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>&gt;</span><span class=p>();</span>
<span class=w> </span><span class=n>p</span><span class=p>.</span><span class=n>age</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>j</span><span class=p>.</span><span class=n>at</span><span class=p>(</span><span class=s>"age"</span><span class=p>).</span><span class=k>template</span><span class=w> </span><span class=n>get</span><span class=o>&lt;</span><span class=kt>int</span><span class=o>&gt;</span><span class=p>();</span>
<span class=p>}</span>
</code></pre></div> <p>Its body may only use what views and <code>basic_json</code> have in common: the type checks, <code>at()</code>, <code>operator[]</code>, <code>contains()</code>, <code>value()</code>, <code>size()</code>, iteration and <code>items()</code>, and <code>get&lt;T&gt;()</code>/<code>get_to()</code>. An unconstrained <code class=highlight><span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>BasicJsonType</span><span class=o>&gt;</span><span class=w> </span><span class=kt>void</span><span class=w> </span><span class=n>from_json</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>BasicJsonType</span><span class=o>&amp;</span><span class=w> </span><span class=n>j</span><span class=p>,</span><span class=w> </span><span class=n>person</span><span class=o>&amp;</span><span class=w> </span><span class=n>p</span><span class=p>)</span></code>, as in <a href=../arbitrary_types/ >arbitrary type conversions</a>, is never called with a view, as it might use <code>basic_json</code> functions a view does not have; such a type is converted through <code>materialize()</code>. A <code>from_json()</code> for <code>json</code> only is converted through <code>materialize()</code> as well.</p> <p>Two things differ when a <code>from_json()</code> reads the view:</p> <ul> <li><strong>Duplicate keys.</strong> Members looked up by name (<code>at()</code>, <code>value()</code>, ... and thus the macros) find the <strong>first</strong> member with a repeated key, see <a href=#duplicate-keys>Duplicate keys</a>; <code class=highlight><span class=n>materialize</span><span class=p>().</span><span class=n>get</span><span class=o>&lt;</span><span class=n>T</span><span class=o>&gt;</span><span class=p>()</span></code> would see the last one. Containers built from an object, such as <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>map</span></code>, keep the <strong>last</strong> value either way, as <a href=../../api/basic_json/parse/ ><code>parse()</code></a> does.</li> <li><strong><a href=../../api/macros/json_diagnostics/ ><code>JSON_DIAGNOSTICS</code></a>.</strong> Exceptions thrown by the view carry no path to the value.</li> </ul> <p><code>to_json()</code> is unaffected: it writes <code>basic_json</code> values, never views.</p> <h2 id=writing-a-view-back>Writing a view back<a class=headerlink href=#writing-a-view-back title="Permanent link">&para;</a></h2> <p><a href=../../api/basic_json_view/dump/ ><code>dump()</code></a> serializes a view directly from the flat index, without ever building a <code>basic_json</code> value. An object's members are written in document order, not sorted by key, and <em>every</em> occurrence of a repeated key is written, not only the last one — the same two ways <a href=#what-is-different>iteration</a> already differs from a <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a>d value, see <a href=#duplicate-keys>Duplicate keys</a>. <code class=highlight><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>()</span></code> gives a different result in both respects for a <code>json_view</code>.</p> <p>By default, numbers are written the way <a href=../../api/basic_json/dump/ ><code>basic_json::dump()</code></a> would. <a href=../../api/basic_json_view/number_format/ ><code>number_format::source</code></a> instead copies every number exactly as it was written in the source text — a price like <code class=highlight><span class=mf>19.90</span></code>, a long order or account ID with more digits than any number type holds, or a high-precision coordinate — something <code>basic_json</code> cannot do at all, since parsing already reduces a number to its parsed <code class=highlight><span class=kt>double</span></code>/<code class=highlight><span class=kt>int64_t</span></code> value.</p> <p><a href=../../api/basic_json_view/operator_ltlt/ ><code>operator&lt;&lt;</code></a> writes a view to a stream the way <code>basic_json</code>'s does, using the stream's <code>width</code>/<code>fill</code> for indentation.</p> <h2 id=editing-a-document>Editing a document<a class=headerlink href=#editing-a-document title="Permanent link">&para;</a></h2> <p>Everything above is read-only: a <code>json_document</code>/<code>json_view</code> lets you look at a parsed text without copying it, but not change it. <a href=../../api/basic_json_document/ ><code>basic_json_document&lt;BasicJsonType, view_mode::editable&gt;</code></a> — more conveniently spelled <a href=../../api/json_editable_document/ ><code>json_editable_document</code></a> or <a href=../../api/ordered_json_editable_document/ ><code>ordered_json_editable_document</code></a> — also lets you <a href=../../api/basic_json_document/set/ ><code>set</code></a> a value, <a href=../../api/basic_json_document/push_back/ ><code>push_back</code></a> onLine truncated
</code></pre></div> <p>Its body may only use what views and <code>basic_json</code> have in common: the type checks, <code>at()</code>, <code>operator[]</code>, <code>contains()</code>, <code>value()</code>, <code>size()</code>, iteration and <code>items()</code>, and <code>get&lt;T&gt;()</code>/<code>get_to()</code>. An unconstrained <code class=highlight><span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>BasicJsonType</span><span class=o>&gt;</span><span class=w> </span><span class=kt>void</span><span class=w> </span><span class=n>from_json</span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>BasicJsonType</span><span class=o>&amp;</span><span class=w> </span><span class=n>j</span><span class=p>,</span><span class=w> </span><span class=n>person</span><span class=o>&amp;</span><span class=w> </span><span class=n>p</span><span class=p>)</span></code>, as in <a href=../arbitrary_types/ >arbitrary type conversions</a>, is never called with a view, as it might use <code>basic_json</code> functions a view does not have; such a type is converted through <code>materialize()</code>. A <code>from_json()</code> for <code>json</code> only is converted through <code>materialize()</code> as well.</p> <p>One thing differs when a <code>from_json()</code> reads the view: members looked up by name (<code>at()</code>, <code>value()</code>, ... and thus the macros) find the <strong>first</strong> member with a repeated key, see <a href=#duplicate-keys>Duplicate keys</a>; <code class=highlight><span class=n>materialize</span><span class=p>().</span><span class=n>get</span><span class=o>&lt;</span><span class=n>T</span><span class=o>&gt;</span><span class=p>()</span></code> would see the last one. Containers built from an object, such as <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>map</span></code>, keep the <strong>last</strong> value either way, as <a href=../../api/basic_json/parse/ ><code>parse()</code></a> does.</p> <p><code>to_json()</code> is unaffected: it writes <code>basic_json</code> values, never views.</p> <h2 id=writing-a-view-back>Writing a view back<a class=headerlink href=#writing-a-view-back title="Permanent link">&para;</a></h2> <p><a href=../../api/basic_json_view/dump/ ><code>dump()</code></a> serializes a view directly from the flat index, without ever building a <code>basic_json</code> value. An object's members are written in document order, not sorted by key, and <em>every</em> occurrence of a repeated key is written, not only the last one — the same two ways <a href=#what-is-different>iteration</a> already differs from a <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a>d value, see <a href=#duplicate-keys>Duplicate keys</a>. <code class=highlight><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>()</span></code> gives a different result in both respects for a <code>json_view</code>.</p> <p>By default, numbers are written the way <a href=../../api/basic_json/dump/ ><code>basic_json::dump()</code></a> would. <a href=../../api/basic_json_view/number_format/ ><code>number_format::source</code></a> instead copies every number exactly as it was written in the source text — a price like <code class=highlight><span class=mf>19.90</span></code>, a long order or account ID with more digits than any number type holds, or a high-precision coordinate — something <code>basic_json</code> cannot do at all, since parsing already reduces a number to its parsed <code class=highlight><span class=kt>double</span></code>/<code class=highlight><span class=kt>int64_t</span></code> value.</p> <p><a href=../../api/basic_json_view/operator_ltlt/ ><code>operator&lt;&lt;</code></a> writes a view to a stream the way <code>basic_json</code>'s does, using the stream's <code>width</code>/<code>fill</code> for indentation.</p> <h2 id=editing-a-document>Editing a document<a class=headerlink href=#editing-a-document title="Permanent link">&para;</a></h2> <p>Everything above is read-only: a <code>json_document</code>/<code>json_view</code> lets you look at a parsed text without copying it, but not change it. <a href=../../api/basic_json_document/ ><code>basic_json_document&lt;BasicJsonType, view_mode::editable&gt;</code></a> — more conveniently spelled <a href=../../api/json_editable_document/ ><code>json_editable_document</code></a> or <a href=../../api/ordered_json_editable_document/ ><code>ordered_json_editable_document</code></a> — also lets you <a href=../../api/basic_json_document/set/ ><code>set</code></a> a value, <a href=../../api/basic_json_document/push_back/ ><code>push_back</code></a> onto or <a href=../../api/basic_json_document/insert/ ><code>insert</code></a> into an array, and <a href=../../api/basic_json_document/erase/ ><code>erase</code></a> an object member or an array element, still withoutLine truncated
"name":"cache",
"port":6379,
"price":<span class=nj-jsonview-bad>19.9</span>,
@@ -161,4 +171,4 @@
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code><span class=mi>316</span>
<span class=kc>true</span>
<span class=kc>true</span>
</code></pre></div> </details> <div class="admonition warning"> <p class=admonition-title>Experimental</p> <p>The image format is versioned but not yet stable, and may change in an incompatible way before it is declared stable. It is little-endian only (on big-endian targets, <code>save()</code> and <code>load()</code> do not exist), and tied to the library build that wrote it — use it to cache a document or to hand one to another process running the <em>same</em> build, not as a long-term storage format; keep the original <abbr title="JavaScript Object Notation">JSON</abbr> text if a saved document needs to be readable by a future library version.</p> </div> <p>The idea of a document you can read without parsing comes from zero-copy formats such as <a href="https://github.com/google/flatbuffers">FlatBuffers</a> and <a href="https://github.com/yandex/yaff">YaFF</a>; the check <a href=../../api/basic_json_document/load/ ><code>load()</code></a> runs follows the idea of FlatBuffers' Verifier. No code is taken from either.</p> <h2 id=choosing-between-json-ordered_json-the-sax-interface-and-json_view>Choosing between <code>json</code>, <code>ordered_json</code>, the <abbr title="Simple API for XML">SAX</abbr> interface, and <code>json_view</code><a class=headerlink href=#choosing-between-json-ordered_json-the-sax-interface-and-json_view title="Permanent link">&para;</a></h2> <table> <thead> <tr> <th></th> <th><a href=../../api/json/ ><code>json</code></a> / <a href=../../api/ordered_json/ ><code>ordered_json</code></a></th> <th><a href=../parsing/sax_interface/ ><abbr title="Simple API for XML">SAX</abbr> interface</a></th> <th><a href=../../api/json_document/ ><code>json_document</code></a> / <a href=../../api/json_view/ ><code>json_view</code></a></th> <th><a href=../../api/json_editable_document/ ><code>json_editable_document</code></a> / <a href=../../api/json_editable_view/ ><code>json_editable_view</code></a></th> </tr> </thead> <tbody> <tr> <td><strong>Ownership</strong></td> <td>owns every value</td> <td>owns nothing; you decide what to keep, in your handler</td> <td>borrows or owns the <em>text</em>; the index is always owned by the document</td> <td>same as <code>json_document</code>; edits go to storage the document owns</td> </tr> <tr> <td><strong>Mutability</strong></td> <td>freely mutable</td> <td>not applicable (a one-shot event stream)</td> <td>read-only</td> <td><a href=../../api/basic_json_document/set/ ><code>set</code></a>/<a href=../../api/basic_json_document/push_back/ ><code>push_back</code></a>/<a href=../../api/basic_json_document/insert/ ><code>insert</code></a>/<a href=../../api/basic_json_document/erase/ ><code>erase</code></a> edit in place; the source text is never rewritten</td> </tr> <tr> <td><strong>What you get</strong></td> <td>a full tree you can read, write, and keep as long as you like</td> <td>a sequence of callbacks; whatever your handler builds from them</td> <td>a flat index plus, on demand, <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a>d <code>json</code>/<code>ordered_json</code> values for the parts you actually use</td> <td>the same, plus <a href=../../api/basic_json_view/dump/ ><code>dump()</code></a> of an edited document that keeps the member order and, with <a href=../../api/basic_json_view/number_format/ ><code>number_format::source</code></a>, the spelling of every untouched number</td> </tr> <tr> <td><strong>Typical use</strong></td> <td>general-purpose <abbr title="JavaScript Object Notation">JSON</abbr> handling: config, request/response bodies you build or modify, anything you hold onto</td> <td>validating or projecting a text into your own data structure without ever holding the whole thing as <abbr title="JavaScript Object Notation">JSON</abbr></td> <td>large or high-volume input where you only need part of it, or need it repeatedly, and can keep the source text (or a copy) alive for as long as the document lives</td> <td>a document you read, patch a few fields of, and write back — a configuration file, for instance — where the rest of it should come back exactly as it was</td> </tr> <tr> <td><strong>Caching/reload</strong></td> <td>not applicable — re-parse, or roll your own serialization</td> <td>not applicable</td> <td><a href=../../api/basic_json_document/save/ ><code>save()</code></a>/<a href=../../api/basic_json_document/load/ ><code>load()</code></a>: cache the parsed index as an image and reload it without parsing</td> <td>same, saving the document's current — possibly edited — state</td> </tr> </tbody> </table> <p class=nj-table-caption>Each column is one way to work with <abbr title="JavaScript Object Notation">JSON</abbr> in this library, and each row compares one property of them.</p> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">&para;</a></h2> <ul> <li><a href=../../api/basic_json_document/ ><code>basic_json_document</code></a> - the document that owns the parsLine truncated
</code></pre></div> </details> <div class="admonition warning"> <p class=admonition-title>Experimental</p> <p>The image format is versioned but not yet stable, and may change in an incompatible way before it is declared stable. It is little-endian only (on big-endian targets, <code>save()</code> and <code>load()</code> do not exist), and tied to the library build that wrote it — use it to cache a document or to hand one to another process running the <em>same</em> build, not as a long-term storage format; keep the original <abbr title="JavaScript Object Notation">JSON</abbr> text if a saved document needs to be readable by a future library version.</p> </div> <p>The idea of a document you can read without parsing comes from zero-copy formats such as <a href="https://github.com/google/flatbuffers">FlatBuffers</a> and <a href="https://github.com/yandex/yaff">YaFF</a>; the check <a href=../../api/basic_json_document/load/ ><code>load()</code></a> runs follows the idea of FlatBuffers' Verifier. No code is taken from either.</p> <h2 id=choosing-between-json-ordered_json-the-sax-interface-and-json_view>Choosing between <code>json</code>, <code>ordered_json</code>, the <abbr title="Simple API for XML">SAX</abbr> interface, and <code>json_view</code><a class=headerlink href=#choosing-between-json-ordered_json-the-sax-interface-and-json_view title="Permanent link">&para;</a></h2> <table> <thead> <tr> <th></th> <th><a href=../../api/json/ ><code>json</code></a> / <a href=../../api/ordered_json/ ><code>ordered_json</code></a></th> <th><a href=../parsing/sax_interface/ ><abbr title="Simple API for XML">SAX</abbr> interface</a></th> <th><a href=../../api/json_document/ ><code>json_document</code></a> / <a href=../../api/json_view/ ><code>json_view</code></a></th> <th><a href=../../api/json_editable_document/ ><code>json_editable_document</code></a> / <a href=../../api/json_editable_view/ ><code>json_editable_view</code></a></th> </tr> </thead> <tbody> <tr> <td><strong>Ownership</strong></td> <td>owns every value</td> <td>owns nothing; you decide what to keep, in your handler</td> <td>borrows or owns the <em>text</em>; the index is always owned by the document</td> <td>same as <code>json_document</code>; edits go to storage the document owns</td> </tr> <tr> <td><strong>Mutability</strong></td> <td>freely mutable</td> <td>not applicable (a one-shot event stream)</td> <td>read-only</td> <td><a href=../../api/basic_json_document/set/ ><code>set</code></a>/<a href=../../api/basic_json_document/push_back/ ><code>push_back</code></a>/<a href=../../api/basic_json_document/insert/ ><code>insert</code></a>/<a href=../../api/basic_json_document/erase/ ><code>erase</code></a> edit in place; the source text is never rewritten</td> </tr> <tr> <td><strong>What you get</strong></td> <td>a full tree you can read, write, and keep as long as you like</td> <td>a sequence of callbacks; whatever your handler builds from them</td> <td>a flat index plus, on demand, <a href=../../api/basic_json_view/materialize/ ><code>materialize()</code></a>d <code>json</code>/<code>ordered_json</code> values for the parts you actually use</td> <td>the same, plus <a href=../../api/basic_json_view/dump/ ><code>dump()</code></a> of an edited document that keeps the member order and, with <a href=../../api/basic_json_view/number_format/ ><code>number_format::source</code></a>, the spelling of every untouched number</td> </tr> <tr> <td><strong>Typical use</strong></td> <td>general-purpose <abbr title="JavaScript Object Notation">JSON</abbr> handling: config, request/response bodies you build or modify, anything you hold onto</td> <td>validating or projecting a text into your own data structure without ever holding the whole thing as <abbr title="JavaScript Object Notation">JSON</abbr></td> <td>large or high-volume input where you only need part of it, or need it repeatedly, and can keep the source text (or a copy) alive for as long as the document lives</td> <td>a document you read, patch a few fields of, and write back — a configuration file, for instance — where the rest of it should come back exactly as it was</td> </tr> <tr> <td><strong>Caching/reload</strong></td> <td>not applicable — re-parse, or roll your own serialization</td> <td>not applicable</td> <td><a href=../../api/basic_json_document/save/ ><code>save()</code></a>/<a href=../../api/basic_json_document/load/ ><code>load()</code></a>: cache the parsed index as an image and reload it without parsing</td> <td>same, saving the document's current — possibly edited — state</td> </tr> </tbody> </table> <p class=nj-table-caption>Each column is one way to work with <abbr title="JavaScript Object Notation">JSON</abbr> in this library, and each row compares one property of them.</p> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">&para;</a></h2> <ul> <li><a href=../../api/basic_json_document/ ><code>basic_json_document</code></a> - the document that owns the parsLine truncated
+33 -6
View File
@@ -121,9 +121,19 @@ true
## What is the same as `parse()`
- **Accept/reject.** [`accept()`](https://json.nlohmann.me/api/basic_json_document/accept/index.md) and [`parse()`](https://json.nlohmann.me/api/basic_json_document/parse/index.md) accept and reject exactly the same inputs as [`basic_json::accept()`](https://json.nlohmann.me/api/basic_json/accept/index.md)/[`basic_json::parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md), with the same `ignore_comments` and `ignore_trailing_commas` options.
- **Errors.** A failing parse throws the same exception — the same id, message, and position — because on failure the library's own parser is run on the same bytes to produce the diagnostic. Valid input never pays for this, and the replay builds no values: it costs about a lexing pass up to the error. `allow_exceptions == false` skips the replay and gives a [discarded](https://json.nlohmann.me/api/basic_json_document/is_discarded/index.md) document instead of throwing, just as it gives a discarded value for `basic_json::parse()`.
- **Number classification.** An integer literal that does not fit into the 64-bit integer type becomes a floating-point value, exactly as it does for `basic_json::parse()`.
- **Macros.** [`JSON_STRICT_NUL_HANDLING`](https://json.nlohmann.me/api/macros/json_strict_nul_handling/index.md) and [`JSON_NOEXCEPTION`](https://json.nlohmann.me/api/macros/json_noexception/index.md)/[`JSON_THROW_USER`](https://json.nlohmann.me/api/macros/json_throw_user/index.md) behave the same way they do for `<nlohmann/json.hpp>`. These are the macros that change what the parser accepts or how it reports errors. The others either do not apply ([`JSON_DIAGNOSTICS`](https://json.nlohmann.me/api/macros/json_diagnostics/index.md) needs parent pointers in `basic_json` values) or only affect the values `materialize()` produces, through `BasicJsonType`.
- **Macros.** [`JSON_STRICT_NUL_HANDLING`](https://json.nlohmann.me/api/macros/json_strict_nul_handling/index.md) and [`JSON_NOEXCEPTION`](https://json.nlohmann.me/api/macros/json_noexception/index.md)/[`JSON_THROW_USER`](https://json.nlohmann.me/api/macros/json_throw_user/index.md) behave the same way they do for `<nlohmann/json.hpp>`. These are the macros that change what the parser accepts or how it reports errors. Two more macros add context to the exceptions of views, as they do for those of `basic_json`:
- With [`JSON_DIAGNOSTICS`](https://json.nlohmann.me/api/macros/json_diagnostics/index.md), an exception names the JSON Pointer path of the value within the document.
- With [`JSON_DIAGNOSTIC_POSITIONS`](https://json.nlohmann.me/api/macros/json_diagnostic_positions/index.md), an exception names the bytes of the value in the source text.
A view has neither parent pointers nor stored positions, so both are found from the document's index when the exception is thrown. This takes time linear in the size of the document. One exception has neither: `key()` of an iterator over an array or a primitive value ([`invalid_iterator.207`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator207)), because a view's iterator does not know the value it iterates over.
The other macros only affect the values `materialize()` produces, through `BasicJsonType`.
## What is different
@@ -134,7 +144,6 @@ true
- **Objects iterate in document order.** [`begin()`](https://json.nlohmann.me/api/basic_json_view/begin/index.md)/ [`end()`](https://json.nlohmann.me/api/basic_json_view/end/index.md) and [`items()`](https://json.nlohmann.me/api/basic_json_view/items/index.md) visit an object's members in the order they appear in the source text. `basic_json`'s default `object_t` is a `std::map`, which sorts by key, so iterating a [`materialize()`](https://json.nlohmann.me/api/basic_json_view/materialize/index.md)d value can print members in a different order than iterating the view they came from.
- **Chained access is safe.** [`operator[]`](https://json.nlohmann.me/api/basic_json_view/operator%5B%5D/index.md) with a missing key, an index out of range, or an unresolvable JSON pointer returns a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view, and `operator[]` on a discarded view returns a discarded view without throwing: `v["a"]["b"][0]` can be tested once at the end. Type errors on values that exist (a key on an array, an index on an object) still throw, and [`at`](https://json.nlohmann.me/api/basic_json_view/at/index.md) throws for every missing value.
- **Duplicate keys: lookups find the first member, `parse()` keeps the last.** See [Duplicate keys](#duplicate-keys) below.
- **No [`JSON_DIAGNOSTICS`](https://json.nlohmann.me/api/macros/json_diagnostics/index.md) path.** Exceptions thrown by `basic_json_view`'s own element access and lookup functions never carry the JSON Pointer path `JSON_DIAGNOSTICS` would otherwise add: the view has no `basic_json` value to point at, so the exception is created without one, regardless of how `BasicJsonType` was built.
- **Ordering comparisons are not provided** by `basic_json_view` — there is no `operator<`. [`operator==`](https://json.nlohmann.me/api/basic_json_view/operator_eq/index.md) and [`operator!=`](https://json.nlohmann.me/api/basic_json_view/operator_ne/index.md) are provided, though: two views, or a view and a `BasicJsonType` value, compare equal exactly when [`materialize()`](https://json.nlohmann.me/api/basic_json_view/materialize/index.md) or [`parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md) would produce equal values for them, without ever building a tree to do it. For ordering, too, [`materialize()`](https://json.nlohmann.me/api/basic_json_view/materialize/index.md) is the way to get a value you can compare.
## Duplicate keys
@@ -178,6 +187,27 @@ Two conversions never copy at all:
Both results are only valid as long as the view — and, for a string with no escapes, the borrowed source text — is.
### `string_view` members
A struct whose member is a `std::string_view` (C++17) can be decoded from a view with the `NLOHMANN_DEFINE_TYPE_*` macros, and the member is not copied either: for a string without escape sequences it points into the document's source text, and for a string with escape sequences into the document's buffer of decoded strings. The member is valid as long as the document is alive and, for a document that [borrows its source text](#ownership-and-lifetime) (as [`parse()`](https://json.nlohmann.me/api/basic_json_document/parse/index.md) does for an lvalue `std::string`, a `std::string_view`, or a C string), as long as that text is.
```
struct record
{
std::string_view name;
int count;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(record, name, count)
};
const std::string text = R"({"name": "widget", "count": 3})";
const json_document doc = json_document::parse(text); // borrows text
const record r = doc.root().get<record>(); // r.name points into text, valid while text and doc are
```
Decoding into a `string_view` from a `json` value dangles at once
The same struct also compiles with `json::parse(text).get<record>()`, but there `name` points into the temporary `json` value, which is destroyed at the end of the statement. Use a named [`json_document`](https://json.nlohmann.me/api/json_document/index.md), as above, to decode such a struct.
## Writing generic code
A view's type names its `BasicJsonType` and its [`view_mode`](https://json.nlohmann.me/api/view_mode/index.md): [`json_view`](https://json.nlohmann.me/api/json_view/index.md) is `basic_json_view<json, view_mode::read_only>`, and [`json_editable_view`](https://json.nlohmann.me/api/json_editable_view/index.md) is `basic_json_view<json, view_mode::editable>`. These are different types. The only conversion between them turns a view of a read-only document into a view of an editable document of the same `BasicJsonType`, so a function written for one shortcut accepts few other views:
@@ -227,10 +257,7 @@ void from_json(const J& j, person& p)
Its body may only use what views and `basic_json` have in common: the type checks, `at()`, `operator[]`, `contains()`, `value()`, `size()`, iteration and `items()`, and `get<T>()`/`get_to()`. An unconstrained `template<typename BasicJsonType> void from_json(const BasicJsonType& j, person& p)`, as in [arbitrary type conversions](https://json.nlohmann.me/features/arbitrary_types/index.md), is never called with a view, as it might use `basic_json` functions a view does not have; such a type is converted through `materialize()`. A `from_json()` for `json` only is converted through `materialize()` as well.
Two things differ when a `from_json()` reads the view:
- **Duplicate keys.** Members looked up by name (`at()`, `value()`, ... and thus the macros) find the **first** member with a repeated key, see [Duplicate keys](#duplicate-keys); `materialize().get<T>()` would see the last one. Containers built from an object, such as `std::map`, keep the **last** value either way, as [`parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md) does.
- **[`JSON_DIAGNOSTICS`](https://json.nlohmann.me/api/macros/json_diagnostics/index.md).** Exceptions thrown by the view carry no path to the value.
One thing differs when a `from_json()` reads the view: members looked up by name (`at()`, `value()`, ... and thus the macros) find the **first** member with a repeated key, see [Duplicate keys](#duplicate-keys); `materialize().get<T>()` would see the last one. Containers built from an object, such as `std::map`, keep the **last** value either way, as [`parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md) does.
`to_json()` is unaffected: it writes `basic_json` values, never views.