This commit is contained in:
nlohmann committed 2026-10-21 10:31:00 +00:00
1 parent be4d0a6f4b
commit 90f0c9d411
714 files changed
+22067 -622

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
<!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=author content="Niels Lohmann"><link href="https://json.nlohmann.me/api/basic_json_view/operator%5B%5D/" rel="canonical"><link href=../operator_ltlt/ rel=prev><link href=../operator_eq/ rel=next><link rel=icon href=../../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>operator[] - 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="../../../assets/external/fonts.googleapis.com/css.61a430c9.css"><style>:root{--md-text-font:"Roboto";--md-code-font:"JetBrains Mono"}</style><link rel=stylesheet href=../../../css/custom.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=indigo data-md-color-accent=indigo> <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=#nlohmannbasic_json_viewoperator 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> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54"/></svg> </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> operator[] </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=indigo data-md-color-accent=indigo 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=indigo data-md-color-accent=indigo 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 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.52 6.52 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 Line truncated
<span class=n>basic_json_view</span><span class=w> </span><span class=k>operator</span><span class=p>[](</span><span class=n>string_view_t</span><span class=w> </span><span class=n>key</span><span class=p>)</span><span class=w> </span><span class=k>const</span><span class=p>;</span>
<span class=n>basic_json_view</span><span class=w> </span><span class=k>operator</span><span class=p>[](</span><span class=k>const</span><span class=w> </span><span class=kt>char</span><span class=o>*</span><span class=w> </span><span class=n>key</span><span class=p>)</span><span class=w> </span><span class=k>const</span><span class=p>;</span>
<span class=n>basic_json_view</span><span class=w> </span><span class=k>operator</span><span class=p>[](</span><span class=k>const</span><span class=w> </span><span class=n>string_t</span><span class=o>&amp;</span><span class=w> </span><span class=n>key</span><span class=p>)</span><span class=w> </span><span class=k>const</span><span class=p>;</span>
<span class=c1>// (2)</span>
<span class=n>basic_json_view</span><span class=w> </span><span class=k>operator</span><span class=p>[](</span><span class=n>size_type</span><span class=w> </span><span class=n>idx</span><span class=p>)</span><span class=w> </span><span class=k>const</span><span class=p>;</span>
<span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>IntegerType</span><span class=o>&gt;</span>
<span class=n>basic_json_view</span><span class=w> </span><span class=k>operator</span><span class=p>[](</span><span class=n>IntegerType</span><span class=w> </span><span class=n>idx</span><span class=p>)</span><span class=w> </span><span class=k>const</span><span class=p>;</span>
<span class=c1>// (3)</span>
<span class=n>basic_json_view</span><span class=w> </span><span class=k>operator</span><span class=p>[](</span><span class=k>const</span><span class=w> </span><span class=n>json_pointer</span><span class=o>&amp;</span><span class=w> </span><span class=n>ptr</span><span class=p>)</span><span class=w> </span><span class=k>const</span><span class=p>;</span>
</code></pre></div> <ol> <li>Returns the value of the object member with key <code>key</code> -- the first one, should the key occur more than once (see the <a href=#notes>Notes</a> below) -- or a <a href=../is_discarded/ >discarded</a> view if there is no such member.</li> <li>Returns the array element at index <code>idx</code>, or a <a href=../is_discarded/ >discarded</a> view if <code>idx</code> is out of range. The template accepts every integer type except <code class=highlight><span class=kt>bool</span></code> and <code class=highlight><span class=n>std</span><span class=o>::</span><span class=kt>size_t</span></code> (<code class=highlight><span class=kt>int</span></code>, <code class=highlight><span class=kt>unsigned</span></code>, <code class=highlight><span class=kt>long</span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=kt>int64_t</span></code>, ...) and forwards to the <code>size_type</code> overload, so that an integer argument is not ambiguous between that overload and 1; a negative <code>idx</code> is out of range.</li> <li>Returns the value a <abbr title="JavaScript Object Notation">JSON</abbr> pointer <code>ptr</code> refers to, starting at this value, or a <a href=../is_discarded/ >discarded</a> view wherever resolving it further is not possible without inserting into or extending the document (see <a href=#return-value>Return value</a> and <a href=#exceptions>Exceptions</a> below).</li> </ol> <h2 id=parameters>Parameters<a class=headerlink href=#parameters title="Permanent link">&para;</a></h2> <dl> <dt><code>key</code> (in)</dt> <dd>object key of the element to access</dd> <dt><code>idx</code> (in)</dt> <dd>index of the element to access</dd> <dt><code>ptr</code> (in)</dt> <dd><abbr title="JavaScript Object Notation">JSON</abbr> pointer to the element to access</dd> </dl> <h2 id=return-value>Return value<a class=headerlink href=#return-value title="Permanent link">&para;</a></h2> <ol> <li>the value of the first member with key <code>key</code>, or a discarded view if no member has this key (or if this view is <a href=../is_discarded/ >discarded</a>)</li> <li>the element at index <code>idx</code>, or a discarded view if <code class=highlight><span class=n>idx</span><span class=w> </span><span class=o>&gt;=</span><span class=w> </span><span class=n>size</span><span class=p>()</span></code> or <code>idx</code> is negative (or if this view is <a href=../is_discarded/ >discarded</a>)</li> <li>the value <code>ptr</code> resolves to, starting at this value, or a discarded view (also if this view is <a href=../is_discarded/ >discarded</a>) for exactly the reference tokens where the <strong>const</strong> overload of <a href=../../basic_json/operator%5B%5D/ ><code>BasicJsonType::operator[]</code></a> invokes undefined behavior for the same pointer and the same document: an object member that does not exist, or an array index that is out of range</li> </ol> <h2 id=exception-safety>Exception safety<a class=headerlink href=#exception-safety title="Permanent link">&para;</a></h2> <p>Strong guarantee: there are no changes to the view or the document it refers to.</p> <h2 id=exceptions>Exceptions<a class=headerlink href=#exceptions title="Permanent link">&para;</a></h2> <ol> <li>Throws <a href=../../../home/exceptions/#jsonexceptiontype_error305><code>type_error.305</code></a> if the value is not an object and not <a href=../is_discarded/ >discarded</a> -- the same exception, with the same message, that the <strong>const</strong> overload of <a href=../../basic_json/operator%5B%5D/ ><code>BasicJsonType::operator[]</code></a> throws for a string argument on a non-object value.</li> <li>Throws <a href=../../../home/exceptions/#jsonexceptiontype_error305><code>type_error.305</code></a> if the value is not an array and not <a href=../is_discarded/ >discarded</a> -- the same exception, with the same message, that the <strong>const</strong> overload of <a href=../../basic_json/operator%5B%5D/ ><code>BasicJsonType::operator[]</code></a> throws for a numeric argument on a non-array value.</li> <li>Throws the same exceptions, with the same messages, that the <strong>const</strong> overload of <a href=../../basic_json/operator%5B%5D/ ><code>BasicJsonType::operator[]</code></a> throws for the same pointer and the same document:<ul> <li><a href=../../../home/exceptions/#jsonexceptionout_of_range402><code>out_of_range.402</code></a> if a reference token is <code class=highlight><span class=s>"-"</span></code> at an array.</li> <li><a href=../../../home/exceptions/#jsonexceptionout_of_range404><code>out_of_range.404</code></a> if a reference token cannot be resolved because it is used on a primitive value.</li> <li><a href=../../../home/exceptions/#jsonexceptionparse_error106><code>parse_error.106</code></a> if an array index in <code>ptr</code> begins with <code class=highlight><span class=sc>'0'</span></code>.</li> <li><a href=../../../home/exceptions/#jsonexceptionparsLine 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>json_document</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json_document</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>// two user records from a large API response; only the fields that are</span>
<span class=w> </span><span class=c1>// actually read are ever touched, and no nlohmann::json tree is built</span>
<span class=w> </span><span class=c1>// for the batch</span>
<span class=w> </span><span class=n>json_document</span><span class=w> </span><span class=n>batch</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=sa>R</span><span class=s>"</span><span class=dl>(</span>
<span class=s> [</span>
<span class=s> {"name": "Alice", "email": "alice@example.com", "tags": ["admin", "ops"]},</span>
<span class=s> {"name": "Bob", "tags": []}</span>
<span class=s> ]</span>
<span class=s> </span><span class=dl>)</span><span class=s>"</span><span class=p>);</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>users</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>batch</span><span class=p>.</span><span class=n>root</span><span class=p>();</span>
<span class=w> </span><span class=k>for</span><span class=w> </span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=kt>size_t</span><span class=w> </span><span class=n>i</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>0</span><span class=p>;</span><span class=w> </span><span class=n>i</span><span class=w> </span><span class=o>&lt;</span><span class=w> </span><span class=n>users</span><span class=p>.</span><span class=n>size</span><span class=p>();</span><span class=w> </span><span class=o>++</span><span class=n>i</span><span class=p>)</span>
<span class=w> </span><span class=p>{</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>user</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>users</span><span class=p>[</span><span class=n>i</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>&lt;&lt;</span><span class=w> </span><span class=n>user</span><span class=p>[</span><span class=s>"name"</span><span class=p>].</span><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>();</span>
<span class=w> </span><span class=c1>// operator[] on a missing object key gives a discarded view -- test</span>
<span class=w> </span><span class=c1>// it with is_discarded(). The const overload of json::operator[]</span>
<span class=w> </span><span class=c1>// would instead be undefined behavior (guarded by an assertion) for</span>
<span class=w> </span><span class=c1>// a missing key</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>email</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>user</span><span class=p>[</span><span class=s>"email"</span><span class=p>];</span>
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=o>!</span><span class=n>email</span><span class=p>.</span><span class=n>is_discarded</span><span class=p>())</span>
<span class=w> </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>&lt;&lt;</span><span class=w> </span><span class=s>" &lt;"</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=n>email</span><span class=p>.</span><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>()</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=s>"&gt;"</span><span class=p>;</span>
<span class=w> </span><span class=p>}</span>
<span class=w> </span><span class=c1>// the same holds for an array index past the end: a discarded view,</span>
<span class=w> </span><span class=c1>// not undefined behavior</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>first_tag</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>user</span><span class=p>[</span><span class=s>"tags"</span><span class=p>][</span><span class=mi>0</span><span class=p>];</span>
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=o>!</span><span class=n>first_tag</span><span class=p>.</span><span class=n>is_discarded</span><span class=p>())</span>
<span class=w> </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>&lt;&lt;</span><span class=w> </span><span class=s>" #"</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=n>first_tag</span><span class=p>.</span><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>();</span>
<span class=w> </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>&lt;&lt;</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span>
<span class=w> </span><span class=p>}</span>
<span class=p>}</span>
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code><span class=s2>"Alice"</span><span class=w> </span><span class=err>&lt;</span><span class=s2>"alice@example.com"</span><span class=err>&gt;</span><span class=w> </span><span class=err>#</span><span class=s2>"admin"</span>
<span class=s2>"Bob"</span>
</code></pre></div> </details> <details class=example> <summary>Example: (3) access specified element via <abbr title="JavaScript Object Notation">JSON</abbr> pointer</summary> <p>The example below reaches straight into one deeply nested field of a large document with a single <abbr title="JavaScript Object Notation">JSON</abbr> pointer, without ever building a tree for the rest of it, and shows the discarded-view and throwing outcomes of a pointer that cannot be fully resolved.</p> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;iostream&gt;</span>
<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>json_document</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json_document</span><span class=p>;</span>
<span class=k>using</span><span class=w> </span><span class=n>json_pointer</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=o>::</span><span class=n>json_pointer</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 larger document; operator[] with a JSON pointer reaches straight to</span>
<span class=w> </span><span class=c1>// one deeply nested field, without ever building a tree for the rest</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=sa>R</span><span class=s>"</span><span class=dl>(</span>
<span class=s> {</span>
<span class=s> "region": {</span>
<span class=s> "servers": [</span>
<span class=s> {"name": "eu-1", "metrics": {"cpu": 0.42}},</span>
<span class=s> {"name": "eu-2", "metrics": {"cpu": 0.71}}</span>
<span class=s> ]</span>
<span class=s> }</span>
<span class=s> }</span>
<span class=s> </span><span class=dl>)</span><span class=s>"</span><span class=p>);</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>root</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=w> </span><span class=n>std</span><span class=o>::</span><span class=n>cout</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=n>root</span><span class=p>[</span><span class=n>json_pointer</span><span class=p>(</span><span class=s>"/region/servers/1/metrics/cpu"</span><span class=p>)].</span><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>()</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span>
<span class=w> </span><span class=c1>// a missing key or an out-of-range index along the path gives a</span>
<span class=w> </span><span class=c1>// discarded view, exactly where const json::operator[] would be</span>
<span class=w> </span><span class=c1>// undefined behavior for the same pointer</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>missing</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>root</span><span class=p>[</span><span class=n>json_pointer</span><span class=p>(</span><span class=s>"/region/servers/5/metrics/cpu"</span><span class=p>)];</span>
<span class=w> </span><span class=k>if</span><span class=w> </span><span class=p>(</span><span class=o>!</span><span class=n>missing</span><span class=p>.</span><span class=n>is_discarded</span><span class=p>())</span>
<span class=w> </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>&lt;&lt;</span><span class=w> </span><span class=n>missing</span><span class=p>.</span><span class=n>materialize</span><span class=p>().</span><span class=n>dump</span><span class=p>()</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span>
<span class=w> </span><span class=p>}</span>
<span class=w> </span><span class=k>else</span>
<span class=w> </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>&lt;&lt;</span><span class=w> </span><span class=s>"no such server</span><span class=se>\n</span><span class=s>"</span><span class=p>;</span>
<span class=w> </span><span class=p>}</span>
<span class=w> </span><span class=c1>// indexing into a primitive still throws, as basic_json::operator[]</span>
<span class=w> </span><span class=c1>// does for the same pointer</span>
<span class=w> </span><span class=k>try</span>
<span class=w> </span><span class=p>{</span>
<span class=w> </span><span class=k>static_cast</span><span class=o>&lt;</span><span class=kt>void</span><span class=o>&gt;</span><span class=p>(</span><span class=n>root</span><span class=p>[</span><span class=n>json_pointer</span><span class=p>(</span><span class=s>"/region/servers/0/name/x"</span><span class=p>)]);</span>
<span class=w> </span><span class=p>}</span>
<span class=w> </span><span class=k>catch</span><span class=w> </span><span class=p>(</span><span class=k>const</span><span class=w> </span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=o>::</span><span class=n>out_of_range</span><span class=o>&amp;</span><span class=w> </span><span class=n>e</span><span class=p>)</span>
<span class=w> </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>&lt;&lt;</span><span class=w> </span><span class=n>e</span><span class=p>.</span><span class=n>what</span><span class=p>()</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=sc>'\n'</span><span class=p>;</span>
<span class=w> </span><span class=p>}</span>
<span class=p>}</span>
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code><span class=mf>0.71</span>
<span class=kc>n</span><span class=err>o</span><span class=w> </span><span class=err>such</span><span class=w> </span><span class=err>server</span>
<span class=p>[</span><span class=err>jso</span><span class=kc>n</span><span class=err>.excep</span><span class=kc>t</span><span class=err>io</span><span class=kc>n</span><span class=err>.ou</span><span class=kc>t</span><span class=err>_o</span><span class=kc>f</span><span class=err>_ra</span><span class=kc>n</span><span class=err>ge.</span><span class=mi>404</span><span class=p>]</span><span class=w> </span><span class=err>u</span><span class=kc>nres</span><span class=err>olved</span><span class=w> </span><span class=err>re</span><span class=kc>feren</span><span class=err>ce</span><span class=w> </span><span class=kc>t</span><span class=err>oke</span><span class=kc>n</span><span class=w> </span><span class=err>'x'</span>
</code></pre></div> </details> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">&para;</a></h2> <ul> <li><a href=../at/ >at</a> - access specified element with bounds checking (throws instead of returning a discarded view)</li> <li><a href=../front/ >front</a>, <a href=../back/ >back</a> - access the first or last element</li> <li><a href=../find/ >find</a>, <a href=../contains/ >contains</a> - look up a member without throwing</li> <li><a href=../../basic_json/operator%5B%5D/ ><code>BasicJsonType::operator[]</code></a> - the corresponding function of <code>basic_json</code></li> <li><a href=../../json_pointer/ ><code>json_pointer</code></a> - <abbr title="JavaScript Object Notation">JSON</abbr> pointer type used by overload 3</li> </ul> <h2 id=version-history>Version history<a class=headerlink href=#version-history title="Permanent link">&para;</a></h2> <ul> <li>Added in version 3.13.0 <span class=unreleased-version title="Not part of a release yet; the latest release is 3.12.0.">unreleased</span>.</li> </ul> <!-- https://squidfunk.github.io/mkdocs-material/reference/tooltips/#adding-a-glossary --> <aside class=md-source-file> <span class=md-source-file__fact> <span class=md-icon title="Last update"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M21 13.1c-.1 0-.3.1-.4.2l-1 1 2.1 2.1 1-1c.2-.2.2-.6 0-.8l-1.3-1.3c-.1-.1-.2-.2-.4-.2m-1.9 1.8-6.1 6V23h2.1l6.1-6.1zM12.5 7v5.2l4 2.4-1 1L11 13V7zM11 21.9c-5.1-.5-9-4.8-9-9.9C2 6.5 6.5 2 12 2c5.3 0 9.6 4.1 10 9.3-.3-.1-.6-.2-1-.2s-.7.1-1 .2C19.6 7.2 16.2 4 12 4c-4.4 0-8 3.6-8 8 0 4.1 3.1 7.5 7.1 7.9l-.1.2z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date" title="October 21, 2026 08:21:28 UTC">October 21, 2026</span> </span> </aside> </article> </div> <script>var tabs=__md_get("__tabs");if(Array.isArray(tabs))e:for(var set of document.querySelectorAll(".tabbed-set")){var labels=set.querySelector(".tabbed-labels");for(var tab of tabs)for(var label of labels.getElementsByTagName("label"))if(label.innerText.trim()===tab){var input=document.getElementById(label.htmlFor);input.checked=!0;continue e}}</script> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type=button class="md-top md-icon" data-md-component=top hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class=md-footer> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-copyright> <div class=md-copyright__highlight> Copyright &copy; 2013-2026 Niels Lohmann </div> </div> <div class=md-social> <a href="https://github.com/nlohmann" target="_blank" rel="noopener" title="github.com" class="md-social__link"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 512 512"><!-- Font Awesome Free 7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2025 Fonticons, Inc.--><path d="M173.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6m-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3m44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9M252.8 8C114.1 8 8 113.3 8 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C436.2 457.8 504 362.9 504 252 504 113.3 391.5 8 252.8 8M105.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1m-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7m32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1m-11.4-14.7c-1.6 1-1.6 3.6 0 5.9s4.3 3.3 5.6 2.3c1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2"/></svg> </a> <a href="https://www.linkedin.com/in/nielslohmann/" target="_blank" rel="noopener" title="www.linkedin.com" class="md-social__link"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 448 512"><!-- Font Awesome Free 7.1.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2025 Fonticons, Inc.--><path d="M416 32H31.9C14.3 32 0 46.5 0 64.3v383.4C0 465.5 14.3Line truncated
+207
View File
@@ -0,0 +1,207 @@
# nlohmann::basic_json_view::operator[]
```
// (1)
basic_json_view operator[](string_view_t key) const;
basic_json_view operator[](const char* key) const;
basic_json_view operator[](const string_t& key) const;
// (2)
basic_json_view operator[](size_type idx) const;
template<typename IntegerType>
basic_json_view operator[](IntegerType idx) const;
// (3)
basic_json_view operator[](const json_pointer& ptr) const;
```
1. Returns the value of the object member with key `key` -- the first one, should the key occur more than once (see the [Notes](#notes) below) -- or a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view if there is no such member.
1. Returns the array element at index `idx`, or a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view if `idx` is out of range. The template accepts every integer type except `bool` and `std::size_t` (`int`, `unsigned`, `long`, `std::int64_t`, ...) and forwards to the `size_type` overload, so that an integer argument is not ambiguous between that overload and 1; a negative `idx` is out of range.
1. Returns the value a JSON pointer `ptr` refers to, starting at this value, or a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view wherever resolving it further is not possible without inserting into or extending the document (see [Return value](#return-value) and [Exceptions](#exceptions) below).
## Parameters
`key` (in) : object key of the element to access
`idx` (in) : index of the element to access
`ptr` (in) : JSON pointer to the element to access
## Return value
1. the value of the first member with key `key`, or a discarded view if no member has this key (or if this view is [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md))
1. the element at index `idx`, or a discarded view if `idx >= size()` or `idx` is negative (or if this view is [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md))
1. the value `ptr` resolves to, starting at this value, or a discarded view (also if this view is [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md)) for exactly the reference tokens where the **const** overload of [`BasicJsonType::operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) invokes undefined behavior for the same pointer and the same document: an object member that does not exist, or an array index that is out of range
## Exception safety
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
1. Throws [`type_error.305`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error305) if the value is not an object and not [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) -- the same exception, with the same message, that the **const** overload of [`BasicJsonType::operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) throws for a string argument on a non-object value.
1. Throws [`type_error.305`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error305) if the value is not an array and not [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) -- the same exception, with the same message, that the **const** overload of [`BasicJsonType::operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) throws for a numeric argument on a non-array value.
1. Throws the same exceptions, with the same messages, that the **const** overload of [`BasicJsonType::operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) throws for the same pointer and the same document:
- [`out_of_range.402`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range402) if a reference token is `"-"` at an array.
- [`out_of_range.404`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range404) if a reference token cannot be resolved because it is used on a primitive value.
- [`parse_error.106`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error106) if an array index in `ptr` begins with `'0'`.
- [`parse_error.109`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error109) if an array index in `ptr` is not a number.
None of these exceptions carry a [`JSON_DIAGNOSTICS`](https://json.nlohmann.me/api/macros/json_diagnostics/index.md) path: the view has no `BasicJsonType` value to point at, so the exception is created without one, even if `BasicJsonType` was built with `JSON_DIAGNOSTICS` enabled.
## Complexity
1. Linear in the number of members: as for [`ordered_json`](https://json.nlohmann.me/api/ordered_json/index.md), members are compared one after another, in document order, stopping at the first match. Each comparison first checks the key's length -- already known from the index, without reading the key bytes -- before comparing its content, so a key of a different length than `key` is rejected without touching the source text. Objects with 128 or more members get a hash index of their keys while parsing, so that a lookup in them takes constant time on average.
1. Linear in `idx`: elements are skipped one at a time from the first one, since they are not a fixed size in the index (unlike `BasicJsonType`'s array, which is random-access).
1. Linear in the number of reference tokens of `ptr` and, for each token, in the number of members of the object at that level (as 1.) or the index into the array (as 2.).
## Notes
Unlike `BasicJsonType::operator[]`, which is undefined behavior (guarded by a [runtime assertion](https://json.nlohmann.me/features/assertions/index.md)) for a missing key on a **const** value, this operator returns a safe, testable result for a missing key or an index out of range: a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view, which is tested with [`is_discarded`](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md). There is also no non-const overload that inserts a missing key or extends an array -- a view never modifies the document.
Chained access
`operator[]` on a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view returns a discarded view and does not throw, so a chain like `v["a"]["b"][0]` is safe even if `"a"` or `"b"` is missing: the first missing step makes the whole result discarded, which is tested once at the end. Type errors on values that are *not* discarded still throw: a key on an array or a primitive, or an index on an object or a primitive, is `type_error.305` as for `BasicJsonType`. [`at`](https://json.nlohmann.me/api/basic_json_view/at/index.md) still throws for a discarded view, as it does for a missing key.
Duplicate keys: the first member wins
If the source text has an object with a duplicate key, `operator[]` (and [`at`](https://json.nlohmann.me/api/basic_json_view/at/index.md), [`find`](https://json.nlohmann.me/api/basic_json_view/find/index.md), [`contains`](https://json.nlohmann.me/api/basic_json_view/contains/index.md), [`value`](https://json.nlohmann.me/api/basic_json_view/value/index.md), and JSON pointer resolution) all resolve to the *first* member with that key, because a lookup can stop as soon as it finds a match. This is different from [`materialize()`](https://json.nlohmann.me/api/basic_json_view/materialize/index.md) (and [`BasicJsonType::parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md)), which replay every member in order and so keep the *last* value for a repeated key, so `v["a"]` and `v.materialize()["a"]` can differ. To get the value `parse()` would give, use [`materialize()`](https://json.nlohmann.me/api/basic_json_view/materialize/index.md) or iterate the members with [`items()`](https://json.nlohmann.me/api/basic_json_view/items/index.md) and keep the last match. The key hash index of a larger object (128 members or more) leads to the first member of a key as well. [`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) iterate over *all* members, including duplicates, in document order. See [Duplicate keys](https://json.nlohmann.me/features/json_view/#duplicate-keys) and [`size()`](https://json.nlohmann.me/api/basic_json_view/size/#notes).
JSON pointer resolution
Overload 3 walks `ptr` one reference token at a time, starting at this value, the same way [`at`](https://json.nlohmann.me/api/basic_json_view/at/index.md) and [`contains`](https://json.nlohmann.me/api/basic_json_view/contains/index.md) do. It only ever returns a discarded view where the **const** overload of `BasicJsonType::operator[]` would be undefined behavior for the same pointer -- a missing object member or an out-of-range array index -- and still throws for every other way `ptr` can fail to resolve. See [`at`](https://json.nlohmann.me/api/basic_json_view/at/#exceptions) for the checked version, which throws in every case instead, and [`contains`](https://json.nlohmann.me/api/basic_json_view/contains/index.md) for a version that never throws.
## Examples
Example: (1)/(2) access specified element
The example below reads a couple of fields out of a batch of user records without ever materializing a full `BasicJsonType` value for the batch. `operator[]` is used both to look up an optional object member and to index into an array -- in both cases, a missing value comes back as a discarded view that can be tested with a plain `if`, instead of relying on undefined behavior.
```
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
int main()
{
// two user records from a large API response; only the fields that are
// actually read are ever touched, and no nlohmann::json tree is built
// for the batch
json_document batch = json_document::parse(R"(
[
{"name": "Alice", "email": "alice@example.com", "tags": ["admin", "ops"]},
{"name": "Bob", "tags": []}
]
)");
const auto users = batch.root();
for (std::size_t i = 0; i < users.size(); ++i)
{
const auto user = users[i];
std::cout << user["name"].materialize().dump();
// operator[] on a missing object key gives a discarded view -- test
// it with is_discarded(). The const overload of json::operator[]
// would instead be undefined behavior (guarded by an assertion) for
// a missing key
const auto email = user["email"];
if (!email.is_discarded())
{
std::cout << " <" << email.materialize().dump() << ">";
}
// the same holds for an array index past the end: a discarded view,
// not undefined behavior
const auto first_tag = user["tags"][0];
if (!first_tag.is_discarded())
{
std::cout << " #" << first_tag.materialize().dump();
}
std::cout << '\n';
}
}
```
Output:
```
"Alice" <"alice@example.com"> #"admin"
"Bob"
```
Example: (3) access specified element via JSON pointer
The example below reaches straight into one deeply nested field of a large document with a single JSON pointer, without ever building a tree for the rest of it, and shows the discarded-view and throwing outcomes of a pointer that cannot be fully resolved.
```
#include <iostream>
#include <nlohmann/json_view.hpp>
using json_document = nlohmann::json_document;
using json_pointer = nlohmann::json::json_pointer;
int main()
{
// a larger document; operator[] with a JSON pointer reaches straight to
// one deeply nested field, without ever building a tree for the rest
json_document doc = json_document::parse(R"(
{
"region": {
"servers": [
{"name": "eu-1", "metrics": {"cpu": 0.42}},
{"name": "eu-2", "metrics": {"cpu": 0.71}}
]
}
}
)");
const auto root = doc.root();
std::cout << root[json_pointer("/region/servers/1/metrics/cpu")].materialize().dump() << '\n';
// a missing key or an out-of-range index along the path gives a
// discarded view, exactly where const json::operator[] would be
// undefined behavior for the same pointer
const auto missing = root[json_pointer("/region/servers/5/metrics/cpu")];
if (!missing.is_discarded())
{
std::cout << missing.materialize().dump() << '\n';
}
else
{
std::cout << "no such server\n";
}
// indexing into a primitive still throws, as basic_json::operator[]
// does for the same pointer
try
{
static_cast<void>(root[json_pointer("/region/servers/0/name/x")]);
}
catch (const nlohmann::json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
0.71
no such server
[json.exception.out_of_range.404] unresolved reference token 'x'
```
## See also
- [at](https://json.nlohmann.me/api/basic_json_view/at/index.md) - access specified element with bounds checking (throws instead of returning a discarded view)
- [front](https://json.nlohmann.me/api/basic_json_view/front/index.md), [back](https://json.nlohmann.me/api/basic_json_view/back/index.md) - access the first or last element
- [find](https://json.nlohmann.me/api/basic_json_view/find/index.md), [contains](https://json.nlohmann.me/api/basic_json_view/contains/index.md) - look up a member without throwing
- [`BasicJsonType::operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) - the corresponding function of `basic_json`
- [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) - JSON pointer type used by overload 3
## Version history
- Added in version 3.13.0 unreleased.