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

+82
View File
@@ -0,0 +1,82 @@
<!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_document/set/" rel="canonical"><link href=../save/ rel=prev><link href=../shrink_to_fit/ rel=next><link rel=icon href=../../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>set - 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_documentset 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> set </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 12 14 9.5 12 5 9.5 5"/></svg>Line truncated
<span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>V</span><span class=o>&gt;</span>
<span class=n>view_type</span><span class=w> </span><span class=n>set</span><span class=p>(</span><span class=n>view_type</span><span class=w> </span><span class=n>target</span><span class=p>,</span><span class=w> </span><span class=n>V</span><span class=o>&amp;&amp;</span><span class=w> </span><span class=n>value</span><span class=p>);</span>
<span class=c1>// (2)</span>
<span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>V</span><span class=o>&gt;</span>
<span class=n>view_type</span><span class=w> </span><span class=n>set</span><span class=p>(</span><span class=n>view_type</span><span class=w> </span><span class=n>object</span><span class=p>,</span><span class=w> </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=n>V</span><span class=o>&amp;&amp;</span><span class=w> </span><span class=n>value</span><span class=p>);</span>
<span class=c1>// (3)</span>
<span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>I</span><span class=p>,</span><span class=w> </span><span class=k>typename</span><span class=w> </span><span class=nc>V</span><span class=o>&gt;</span>
<span class=n>view_type</span><span class=w> </span><span class=n>set</span><span class=p>(</span><span class=n>view_type</span><span class=w> </span><span class=n>array</span><span class=p>,</span><span class=w> </span><span class=n>I</span><span class=w> </span><span class=n>idx</span><span class=p>,</span><span class=w> </span><span class=n>V</span><span class=o>&amp;&amp;</span><span class=w> </span><span class=n>value</span><span class=p>);</span>
<span class=c1>// (4)</span>
<span class=k>template</span><span class=o>&lt;</span><span class=k>typename</span><span class=w> </span><span class=nc>V</span><span class=o>&gt;</span>
<span class=n>view_type</span><span class=w> </span><span class=n>set</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=n>V</span><span class=o>&amp;&amp;</span><span class=w> </span><span class=n>value</span><span class=p>);</span>
</code></pre></div> <p>Only an <strong>editable</strong> document (<code class=highlight><span class=n>Editable</span><span class=w> </span><span class=o>==</span><span class=w> </span><span class=nb>true</span></code>, e.g. <a href=../../json_editable_document/ ><code>json_editable_document</code></a>) has <code>set</code>; calling it on a read-only <code>basic_json_document</code> fails to compile (<code class=highlight><span class=k>static_assert</span></code>).</p> <ol> <li>Replaces the value <code>target</code> refers to with <code>value</code>.</li> <li>Sets the member <code>key</code> of the object <code>object</code> to <code>value</code>: assigns it if <code>object</code> already has a member with this key -- the first one, should the key occur more than once, and the later duplicates are then dropped (see the <a href=#notes>Notes</a> below) -- or appends a new member at the end otherwise. A <a href=../../basic_json_view/is_null/ >null</a> <code>object</code> first becomes an empty object.</li> <li>Assigns <code>value</code> to the element at index <code>idx</code> of the array <code>array</code>, which must already exist (<code class=highlight><span class=n>idx</span><span class=w> </span><span class=o>&lt;</span><span class=w> </span><span class=n>array</span><span class=p>.</span><span class=n>size</span><span class=p>()</span></code>).</li> <li>Sets the value the <abbr title="JavaScript Object Notation">JSON</abbr> pointer <code>ptr</code> refers to, relative to <a href=../root/ ><code>root()</code></a>, to <code>value</code>. The <em>parent</em> of the target must already exist: an object member is set as in 2. (added if it does not exist yet), an array element is assigned as in 3., and a last reference token of <code class=highlight><span class=s>"-"</span></code>, or equal to the size of the array, appends <code>value</code> instead, exactly as <a href=../push_back/ ><code>push_back</code></a> would. A <a href=../../basic_json_view/is_null/ >null</a> parent becomes what <a href=../../basic_json/operator%5B%5D/ ><code>basic_json::operator[]</code></a> with a <abbr title="JavaScript Object Notation">JSON</abbr> pointer makes of it: an array if the last reference token is <code class=highlight><span class=s>"-"</span></code> or consists of digits only (for an index beyond 0, the array is first filled with null values up to that index), an object otherwise. An empty <code>ptr</code> sets <a href=../root/ ><code>root()</code></a> itself, as in 1.</li> </ol> <p>In every overload, <code>value</code> is accepted three ways: a <a href=../../basic_json_view/ ><code>basic_json_view</code></a> of <em>any</em> document -- read-only or editable, and it does not have to be <code>target</code>'s/<code>object</code>'s/<code>array</code>'s own document -- which is copied so that nothing is shared with the source document afterward; a <code>BasicJsonType</code> value; or anything <code>BasicJsonType</code> can be constructed from (numbers, strings, <code class=highlight><span class=kt>bool</span></code>, <code class=highlight><span class=nb>nullptr</span></code>, containers, ...).</p> <h2 id=template-parameters>Template parameters<a class=headerlink href=#template-parameters title="Permanent link">&para;</a></h2> <dl> <dt><code>V</code></dt> <dd>the type of <code>value</code>, deduced; see above for what is accepted.</dd> <dt><code>I</code></dt> <dd>an integral type other than <code class=highlight><span class=kt>bool</span></code>, deduced (overloads taking a <code class=highlight><span class=kt>bool</span></code> or a non-integral type for <code>idx</code> do not participate in overload resolution).</dd> </dl> <h2 id=parameters>Parameters<a class=headerlink href=#parameters title="Permanent link">&para;</a></h2> <dl> <dt><code>target</code> (in)</dt> <dd>the value to replace</dd> <dt><code>object</code> (in)</dt> <dd>the object (or null value) whose member to set</dd> <dt><code>array</code> (in)</dt> <dd>the array whose element to assign</dd> <dt><code>key</code> (in)</dt> <dd>the key of the member to set</dd> <dt><code>idx</code> (in)</dt> <dd>the index of the element to assign; a negative value throws (see <a href=#exceptions>Exceptions</a>)</dd> <dt><code>ptr</code> (in)</dt> <dd>a <abbr title="JavaScript Object Notation">JSON</abbr> pointer to the value to set, relative to <code>root()</code></dd> <dt><code>value</code> (in)</dt> <dd>the new value</dd> </dl> <h2 id=return-value>Return value<a class=headerlink href=#return-value title="Permanent link">&para;</a></h2> <ol> <li>a view of <code>target</code>, now holding <code>value</code></li> <li>a view of the member <code>key</code> of <code>object</code>, now holding <code>value</code></li> <li>a view of the element <code>idx</code> of <code>array</code>, now holding <code>value</code></li> <li>a view of the value <code>ptr</code> refers to, now holding <code>value</code></li> </ol> <h2 id=exception-safety>Exception safety<a class=headerlink href=#excepLine 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</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=p>;</span>
<span class=k>using</span><span class=w> </span><span class=n>json_editable_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_editable_document</span><span class=p>;</span>
<span class=k>using</span><span class=w> </span><span class=n>json_editable_view</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_editable_view</span><span class=p>;</span>
<span class=kt>int</span><span class=w> </span><span class=nf>main</span><span class=p>()</span>
<span class=p>{</span>
<span class=w> </span><span class=c1>// a configuration file, as it might be read from disk -- "price" is</span>
<span class=w> </span><span class=c1>// written with a trailing zero that has no effect on its value</span>
<span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=w> </span><span class=n>text</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=sa>R</span><span class=s>"</span><span class=dl>(</span><span class=s>{</span>
<span class=s> "name": "cache",</span>
<span class=s> "host": "db1",</span>
<span class=s> "port": 6379,</span>
<span class=s> "price": 19.90,</span>
<span class=s> "replicas": ["db2", "db3"],</span>
<span class=s> "timeout": 30</span>
<span class=s>}</span><span class=dl>)</span><span class=s>"</span><span class=p>;</span>
<span class=w> </span><span class=n>json_editable_document</span><span class=w> </span><span class=n>doc</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>json_editable_document</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>text</span><span class=p>);</span>
<span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>set</span><span class=p>(</span><span class=n>doc</span><span class=p>.</span><span class=n>root</span><span class=p>()[</span><span class=s>"port"</span><span class=p>],</span><span class=w> </span><span class=mi>6380</span><span class=p>);</span><span class=w> </span><span class=c1>// (1) replace a value</span>
<span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>set</span><span class=p>(</span><span class=n>doc</span><span class=p>.</span><span class=n>root</span><span class=p>(),</span><span class=w> </span><span class=s>"region"</span><span class=p>,</span><span class=w> </span><span class=s>"us-east"</span><span class=p>);</span><span class=w> </span><span class=c1>// (2) add a member</span>
<span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>set</span><span class=p>(</span><span class=n>doc</span><span class=p>.</span><span class=n>root</span><span class=p>()[</span><span class=s>"replicas"</span><span class=p>],</span><span class=w> </span><span class=mi>0</span><span class=p>,</span><span class=w> </span><span class=s>"db4"</span><span class=p>);</span><span class=w> </span><span class=c1>// (3) assign an element</span>
<span class=w> </span><span class=n>doc</span><span class=p>.</span><span class=n>set</span><span class=p>(</span><span class=n>json</span><span class=o>::</span><span class=n>json_pointer</span><span class=p>(</span><span class=s>"/timeout"</span><span class=p>),</span><span class=w> </span><span class=mi>45</span><span class=p>);</span><span class=w> </span><span class=c1>// (4) via a JSON pointer</span>
<span class=w> </span><span class=c1>// members stay in document order (the new one at the end), and a number</span>
<span class=w> </span><span class=c1>// that was not itself edited keeps its exact spelling</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>doc</span><span class=p>.</span><span class=n>root</span><span class=p>().</span><span class=n>dump</span><span class=p>(</span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=sc>' '</span><span class=p>,</span><span class=w> </span><span class=nb>false</span><span class=p>,</span><span class=w> </span><span class=n>json_editable_view</span><span class=o>::</span><span class=n>number_format</span><span class=o>::</span><span class=n>source</span><span class=p>)</span><span class=w> </span><span class=o>&lt;&lt;</span><span class=w> </span><span class=s>"</span><span class=se>\n\n</span><span class=s>"</span><span class=p>;</span>
<span class=w> </span><span class=c1>// the same edits on a plain json value: object_t is a std::map, so</span>
<span class=w> </span><span class=c1>// parsing already sorted the keys, and dump() rewrites every number to</span>
<span class=w> </span><span class=c1>// its shortest form, even "price", which was never touched</span>
<span class=w> </span><span class=n>json</span><span class=w> </span><span class=n>plain</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>text</span><span class=p>);</span>
<span class=w> </span><span class=n>plain</span><span class=p>[</span><span class=s>"port"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>6380</span><span class=p>;</span>
<span class=w> </span><span class=n>plain</span><span class=p>[</span><span class=s>"region"</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"us-east"</span><span class=p>;</span>
<span class=w> </span><span class=n>plain</span><span class=p>[</span><span class=s>"replicas"</span><span class=p>][</span><span class=mi>0</span><span class=p>]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>"db4"</span><span class=p>;</span>
<span class=w> </span><span class=n>plain</span><span class=p>[</span><span class=n>json</span><span class=o>::</span><span class=n>json_pointer</span><span class=p>(</span><span class=s>"/timeout"</span><span class=p>)]</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>45</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>plain</span><span class=p>.</span><span class=n>dump</span><span class=p>(</span><span class=mi>2</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=p>}</span>
</code></pre></div> <p>Output:</p> <div class=highlight><pre><span></span><code><span class=p>{</span>
<span class=w> </span><span class=nt>"name"</span><span class=p>:</span><span class=w> </span><span class=s2>"cache"</span><span class=p>,</span>
<span class=w> </span><span class=nt>"host"</span><span class=p>:</span><span class=w> </span><span class=s2>"db1"</span><span class=p>,</span>
<span class=w> </span><span class=nt>"port"</span><span class=p>:</span><span class=w> </span><span class=mi>6380</span><span class=p>,</span>
<span class=w> </span><span class=nt>"price"</span><span class=p>:</span><span class=w> </span><span class=mf>19.90</span><span class=p>,</span>
<span class=w> </span><span class=nt>"replicas"</span><span class=p>:</span><span class=w> </span><span class=p>[</span>
<span class=w> </span><span class=s2>"db4"</span><span class=p>,</span>
<span class=w> </span><span class=s2>"db3"</span>
<span class=w> </span><span class=p>],</span>
<span class=w> </span><span class=nt>"timeout"</span><span class=p>:</span><span class=w> </span><span class=mi>45</span><span class=p>,</span>
<span class=w> </span><span class=nt>"region"</span><span class=p>:</span><span class=w> </span><span class=s2>"us-east"</span>
<span class=p>}</span>
<span class=p>{</span>
<span class=w> </span><span class=nt>"host"</span><span class=p>:</span><span class=w> </span><span class=s2>"db1"</span><span class=p>,</span>
<span class=w> </span><span class=nt>"name"</span><span class=p>:</span><span class=w> </span><span class=s2>"cache"</span><span class=p>,</span>
<span class=w> </span><span class=nt>"port"</span><span class=p>:</span><span class=w> </span><span class=mi>6380</span><span class=p>,</span>
<span class=w> </span><span class=nt>"price"</span><span class=p>:</span><span class=w> </span><span class=mf>19.9</span><span class=p>,</span>
<span class=w> </span><span class=nt>"region"</span><span class=p>:</span><span class=w> </span><span class=s2>"us-east"</span><span class=p>,</span>
<span class=w> </span><span class=nt>"replicas"</span><span class=p>:</span><span class=w> </span><span class=p>[</span>
<span class=w> </span><span class=s2>"db4"</span><span class=p>,</span>
<span class=w> </span><span class=s2>"db3"</span>
<span class=w> </span><span class=p>],</span>
<span class=w> </span><span class=nt>"timeout"</span><span class=p>:</span><span class=w> </span><span class=mi>45</span>
<span class=p>}</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=../push_back/ >push_back</a> - append to an array</li> <li><a href=../insert/ >insert</a> - insert an element into an array</li> <li><a href=../erase/ >erase</a> - remove an object member, an array element, or the value a <abbr title="JavaScript Object Notation">JSON</abbr> pointer refers to</li> <li><a href=../root/ >root</a> - the view of the root value, the starting point of overload 4</li> <li><a href=../../basic_json_view/dump/ ><code>basic_json_view::dump</code></a> - serialize the document, keeping an untouched number's spelling with <code class=highlight><span class=n>number_format</span><span class=o>::</span><span class=n>source</span></code></li> <li><a href=../#edits>Edits</a> - what an edit guarantees, for every overload</li> <li><a href=../../../features/json_view/#editing-a-document>Editing a document</a> - why editable documents keep the source text's order and number spelling</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:29 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 Line truncated
+181
View File
@@ -0,0 +1,181 @@
# nlohmann::basic_json_document::set
```
// (1)
template<typename V>
view_type set(view_type target, V&& value);
// (2)
template<typename V>
view_type set(view_type object, string_view_t key, V&& value);
// (3)
template<typename I, typename V>
view_type set(view_type array, I idx, V&& value);
// (4)
template<typename V>
view_type set(const json_pointer& ptr, V&& value);
```
Only an **editable** document (`Editable == true`, e.g. [`json_editable_document`](https://json.nlohmann.me/api/json_editable_document/index.md)) has `set`; calling it on a read-only `basic_json_document` fails to compile (`static_assert`).
1. Replaces the value `target` refers to with `value`.
1. Sets the member `key` of the object `object` to `value`: assigns it if `object` already has a member with this key -- the first one, should the key occur more than once, and the later duplicates are then dropped (see the [Notes](#notes) below) -- or appends a new member at the end otherwise. A [null](https://json.nlohmann.me/api/basic_json_view/is_null/index.md) `object` first becomes an empty object.
1. Assigns `value` to the element at index `idx` of the array `array`, which must already exist (`idx < array.size()`).
1. Sets the value the JSON pointer `ptr` refers to, relative to [`root()`](https://json.nlohmann.me/api/basic_json_document/root/index.md), to `value`. The *parent* of the target must already exist: an object member is set as in 2. (added if it does not exist yet), an array element is assigned as in 3., and a last reference token of `"-"`, or equal to the size of the array, appends `value` instead, exactly as [`push_back`](https://json.nlohmann.me/api/basic_json_document/push_back/index.md) would. A [null](https://json.nlohmann.me/api/basic_json_view/is_null/index.md) parent becomes what [`basic_json::operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) with a JSON pointer makes of it: an array if the last reference token is `"-"` or consists of digits only (for an index beyond 0, the array is first filled with null values up to that index), an object otherwise. An empty `ptr` sets [`root()`](https://json.nlohmann.me/api/basic_json_document/root/index.md) itself, as in 1.
In every overload, `value` is accepted three ways: a [`basic_json_view`](https://json.nlohmann.me/api/basic_json_view/index.md) of *any* document -- read-only or editable, and it does not have to be `target`'s/`object`'s/`array`'s own document -- which is copied so that nothing is shared with the source document afterward; a `BasicJsonType` value; or anything `BasicJsonType` can be constructed from (numbers, strings, `bool`, `nullptr`, containers, ...).
## Template parameters
`V` : the type of `value`, deduced; see above for what is accepted.
`I` : an integral type other than `bool`, deduced (overloads taking a `bool` or a non-integral type for `idx` do not participate in overload resolution).
## Parameters
`target` (in) : the value to replace
`object` (in) : the object (or null value) whose member to set
`array` (in) : the array whose element to assign
`key` (in) : the key of the member to set
`idx` (in) : the index of the element to assign; a negative value throws (see [Exceptions](#exceptions))
`ptr` (in) : a JSON pointer to the value to set, relative to `root()`
`value` (in) : the new value
## Return value
1. a view of `target`, now holding `value`
1. a view of the member `key` of `object`, now holding `value`
1. a view of the element `idx` of `array`, now holding `value`
1. a view of the value `ptr` refers to, now holding `value`
## Exception safety
Basic exception safety: `value` is fully encoded -- including the checks below -- into storage owned by the document before anything already reachable from [`root()`](https://json.nlohmann.me/api/basic_json_document/root/index.md) is touched, so a failure while encoding `value` (an invalid argument, or `std::bad_alloc`) leaves the document completely unchanged, other than memory allocated for the encoding that is not reclaimed. A failure of a later allocation -- while an edited array or object switches from its parsed layout to a growable block, see [Notes](#notes) -- can still leave a partial effect, such as a [null](https://json.nlohmann.me/api/basic_json_view/is_null/index.md) `object`/`array` argument already turned into an empty object/array even though `value` itself was not linked in. Likewise, a failure of `value` in 4. leaves a null parent that is set with an index beyond 0 already filled with the null values before the index.
## Exceptions
1. Throws [`type_error.302`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error302) if `value` is a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view, or a [discarded](https://json.nlohmann.me/api/basic_json/is_discarded/index.md) `BasicJsonType` value (e.g. `BasicJsonType(value_t::discarded)`) -- an object or array `value`, of either kind, is fine and is encoded as a whole subtree.
1. Throws [`type_error.305`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error305) if `object` is neither an object nor null -- the same message [`operator[]`](https://json.nlohmann.me/api/basic_json_view/operator%5B%5D/index.md) throws for a string argument on such a value. Throws [`type_error.316`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error316) if `key` is not valid UTF-8, with the same message [`BasicJsonType::dump()`](https://json.nlohmann.me/api/basic_json/dump/index.md) gives for that string. Also throws what 1. throws for `value`.
1. Throws `type_error.305` if `array` is not an array -- the same message `operator[]` throws for a numeric argument on such a value. Throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) if `idx` is negative, or if `idx >= array.size()`. Also throws what 1. throws for `value`.
1. Throws what [`at`](https://json.nlohmann.me/api/basic_json_view/at/index.md) throws (overload 3) for resolving `ptr`'s parent, except that a missing object member or an array index equal to the array's size at the very last reference token is not an error there (it becomes a new member or an appended element) instead of [`out_of_range.403`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range403)/[`out_of_range.402`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range402). For the last reference token itself: if the parent is an object (or a primitive value, where it throws `type_error.305`), throws what 2. throws; if the parent is an array, throws what 3. throws for an index that is out of range, or, for a token that is not a valid array index, [`parse_error.106`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error106) (a leading `'0'`), [`parse_error.109`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error109) (not a number), [`out_of_range.410`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range410) (too large for `size_type`), or [`out_of_range.404`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range404) (an empty token); the same errors are thrown for a null parent and a token of digits (the parent is not changed then), and [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) if the index is 4294967295 or more. Also throws what 1. throws for `value`.
Every overload also throws [`type_error.319`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error319) if `value` is (or contains) a binary value -- `BasicJsonType` can hold one, but a `json_document` cannot -- and [`invalid_iterator.202`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator202) ("view does not belong to this document") if `target`/`object`/`array` is a [discarded](https://json.nlohmann.me/api/basic_json_view/is_discarded/index.md) view or a view of a *different* document (overloads 1-3 only; overload 4 always starts from this document's own [`root()`](https://json.nlohmann.me/api/basic_json_document/root/index.md)).
## Complexity
1. Linear in the size of `value` (encoding it into the document's storage): constant for a scalar, linear in the number of nested values for an array or object. If `target` is itself an array or object that spans more than one node in its parent's original, unedited layout, and `value` is a scalar, replacing it additionally costs time linear in the size of the document, the *first* time (the parent of `target` is looked up from [`root()`](https://json.nlohmann.me/api/basic_json_document/root/index.md), and then switches to links) -- see [Notes](#notes). Once the parent has links, `target` is replaced in constant time: setting every element of a large array one after the other is linear overall. To avoid the lookup altogether, use 3. (or 2. for an object), which know the parent.
1. Linear in the number of members of `object`, to find an existing member with `key`, plus the complexity of 1. for `value`.
1. Constant, plus the complexity of 1. for `value`.
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 or the index into the array (as [`at`](https://json.nlohmann.me/api/basic_json_view/at/index.md)), plus the complexity of 2. or 3. for the last token; for a null parent and an index, linear in the index.
## Notes
Duplicate keys
If `object` already has more than one member with `key` (2.), the *first* one is assigned `value` and every later member with the same key is removed -- so that a lookup, an iteration, and [`materialize()`](https://json.nlohmann.me/api/basic_json_view/materialize/index.md) of `object` afterward all agree on a single value for `key`, the same way [`operator[]`](https://json.nlohmann.me/api/basic_json_view/operator%5B%5D/index.md) already picks the first occurrence of a duplicate key for reading. See the [Notes on duplicate keys](https://json.nlohmann.me/api/basic_json_view/operator%5B%5D/#notes) of `operator[]`.
Setting a member (2.) or an element (3., through 4.) of an array or object whose elements have not been edited before switches it from its parsed layout to a growable block holding links to its elements; a later [`push_back`](https://json.nlohmann.me/api/basic_json_document/push_back/index.md) or `set` on the same container reuses that block, growing it (amortized constant time) only once it runs out of room. This never moves an element itself -- only where the container's *links* to its elements live -- so a view of an element stays valid, but any iterator already taken over the container is invalidated, since it was walking the old layout. See [Edits](https://json.nlohmann.me/api/basic_json_document/#edits) for what stays valid across an edit in general.
The same switch happens, for the same reason, when overload 1. replaces a multi-node array/object value with a scalar: the *parent's* element sequence is what has to switch to links, not `target` itself, because the parent originally stepped over `target`'s whole subtree by its node count, which no longer applies once `target` is a one-node scalar.
## Examples
Example: (1)/(2)/(3)/(4) replace a value, set a member, assign an element, set via a JSON pointer
The example below edits a small configuration document -- replacing a value, adding an object member, assigning an array element, and reaching a field through a JSON pointer -- and shows what [`dump()`](https://json.nlohmann.me/api/basic_json_view/dump/index.md) preserves that is lost once the same edits are made on a `BasicJsonType` value instead: the order object members were written in, and the exact spelling of a number that was never touched.
```
#include <iostream>
#include <nlohmann/json_view.hpp>
using json = nlohmann::json;
using json_editable_document = nlohmann::json_editable_document;
using json_editable_view = nlohmann::json_editable_view;
int main()
{
// a configuration file, as it might be read from disk -- "price" is
// written with a trailing zero that has no effect on its value
const std::string text = R"({
"name": "cache",
"host": "db1",
"port": 6379,
"price": 19.90,
"replicas": ["db2", "db3"],
"timeout": 30
})";
json_editable_document doc = json_editable_document::parse(text);
doc.set(doc.root()["port"], 6380); // (1) replace a value
doc.set(doc.root(), "region", "us-east"); // (2) add a member
doc.set(doc.root()["replicas"], 0, "db4"); // (3) assign an element
doc.set(json::json_pointer("/timeout"), 45); // (4) via a JSON pointer
// members stay in document order (the new one at the end), and a number
// that was not itself edited keeps its exact spelling
std::cout << doc.root().dump(2, ' ', false, json_editable_view::number_format::source) << "\n\n";
// the same edits on a plain json value: object_t is a std::map, so
// parsing already sorted the keys, and dump() rewrites every number to
// its shortest form, even "price", which was never touched
json plain = json::parse(text);
plain["port"] = 6380;
plain["region"] = "us-east";
plain["replicas"][0] = "db4";
plain[json::json_pointer("/timeout")] = 45;
std::cout << plain.dump(2) << '\n';
}
```
Output:
```
{
"name": "cache",
"host": "db1",
"port": 6380,
"price": 19.90,
"replicas": [
"db4",
"db3"
],
"timeout": 45,
"region": "us-east"
}
{
"host": "db1",
"name": "cache",
"port": 6380,
"price": 19.9,
"region": "us-east",
"replicas": [
"db4",
"db3"
],
"timeout": 45
}
```
## See also
- [push_back](https://json.nlohmann.me/api/basic_json_document/push_back/index.md) - append to an array
- [insert](https://json.nlohmann.me/api/basic_json_document/insert/index.md) - insert an element into an array
- [erase](https://json.nlohmann.me/api/basic_json_document/erase/index.md) - remove an object member, an array element, or the value a JSON pointer refers to
- [root](https://json.nlohmann.me/api/basic_json_document/root/index.md) - the view of the root value, the starting point of overload 4
- [`basic_json_view::dump`](https://json.nlohmann.me/api/basic_json_view/dump/index.md) - serialize the document, keeping an untouched number's spelling with `number_format::source`
- [Edits](https://json.nlohmann.me/api/basic_json_document/#edits) - what an edit guarantees, for every overload
- [Editing a document](https://json.nlohmann.me/features/json_view/#editing-a-document) - why editable documents keep the source text's order and number spelling
## Version history
- Added in version 3.13.0 unreleased.