mirror of
https://github.com/nlohmann/json.git
synced 2026-10-29 00:55:44 +00:00
deploy: a47170346a
This commit is contained in:
1 parent
b36f8a9821
commit
11a863958e
1180 files changed
+14211
-6025
No files matched your search
@@ -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=author content="Niels Lohmann"><link href="https://json.nlohmann.me/features/conversions/" rel="canonical"><link href=../comments/ rel=prev><link href=../creating_values/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>Converting values - 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=#converting-values 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> Converting values </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> </labeLine 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/conversions/" rel="canonical"><link href=../comments/ rel=prev><link href=../creating_values/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>Converting values - 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=#converting-values 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> Converting values </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 9.5c0 1.61-.59 3.09-1.56Line truncated
|
||||
|
||||
<span class=k>auto</span><span class=w> </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=s>"name"</span><span class=p>].</span><span class=n>get</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>></span><span class=p>();</span><span class=w> </span><span class=c1>// "Mary"</span>
|
||||
<span class=k>auto</span><span class=w> </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=s>"age"</span><span class=p>].</span><span class=n>get</span><span class=o><</span><span class=kt>int</span><span class=o>></span><span class=p>();</span><span class=w> </span><span class=c1>// 42</span>
|
||||
@@ -97,14 +97,14 @@
|
||||
<span class=n>std</span><span class=o>::</span><span class=n>optional</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>></span><span class=w> </span><span class=n>opt</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>j_null</span><span class=p>;</span><span class=w> </span><span class=c1>// ❌ throws type_error 302</span>
|
||||
</code></pre></div> <p>This is due to C++ language rules: <code>std::optional<T></code> has its own converting constructor that is chosen over <code>basic_json::operator T()</code> when both are viable. Use <code>get<std::optional<T>>()</code> or <code>get_to()</code> instead:</p> <div class=highlight><pre><span></span><code><span class=k>auto</span><span class=w> </span><span class=n>opt</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>j_null</span><span class=p>.</span><span class=n>get</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>optional</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=o>>></span><span class=p>();</span><span class=w> </span><span class=c1>// ✅ std::nullopt</span>
|
||||
<span class=n>j_null</span><span class=p>.</span><span class=n>get_to</span><span class=p>(</span><span class=n>opt</span><span class=p>);</span><span class=w> </span><span class=c1>// ✅ std::nullopt</span>
|
||||
</code></pre></div> </div> <div class="admonition warning"> <p class=admonition-title><code>static_cast</code> and <code>get<std::optional<T>>()</code> are not guaranteed equivalent</p> <p><code>operator ValueType()</code> (used by <code>static_cast</code> and implicit conversions) intentionally excludes <code>std::optional<T></code> from delegating to <code>get<T>()</code>, to avoid a constructor ambiguity with <code>std::optional<T></code>'s own converting constructor from <code>basic_json</code>. As a result, <code>static_cast<std::optional<T>>(json_value)</code> goes through <code>std::optional<T></code>'s own converting constructor rather than through <code>get<std::optional<T>>()</code>, which can behave differently -- for example, with a custom <code>adl_serializer<std::optional<T>></code> specialization. Prefer <code>get<std::optional<T>>()</code>/<code>get_to()</code> over <code>static_cast</code> for optional types.</p> </div> <div class="admonition warning"> <p class=admonition-title>Converting to a fixed-size destination does not check the array size</p> <p>Some destination types have a size that is fixed by their C++ type rather than by the <abbr title="JavaScript Object Notation">JSON</abbr> value: <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>pair</span><span class=o><</span><span class=n>A</span><span class=p>,</span><span class=w> </span><span class=n>B</span><span class=o>></span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>tuple</span><span class=o><</span><span class=n>Ts</span><span class=p>...</span><span class=o>></span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=n>T</span><span class=p>,</span><span class=w> </span><span class=n>N</span><span class=o>></span></code>, C arrays <code class=highlight><span class=n>T</span><span class=p>[</span><span class=n>N</span><span class=p>]</span></code>, and <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>unordered_map</span></code> with a non-string key type (which is read from an array of two-element arrays). All of them read exactly as many elements as they need via <a href=../../api/basic_json/at/ ><code>at</code></a> and <strong>never compare the <abbr title="JavaScript Object Notation">JSON</abbr> array's size to that number</strong>. The two mismatch directions therefore behave differently:</p> <ul> <li>The <abbr title="JavaScript Object Notation">JSON</abbr> array has <strong>too many</strong> elements: the surplus is <strong>silently discarded</strong>, and no exception is thrown.</li> <li>The <abbr title="JavaScript Object Notation">JSON</abbr> array has <strong>too few</strong> elements: <code>at</code> throws <a href=../../home/exceptions/#jsonexceptionout_of_range401><code>out_of_range.401</code></a> for the first missing index -- an out-of-range error, not a <a href=../../home/exceptions/#type-errors><code>type_error</code></a>, even though the cause is a shape mismatch.</li> </ul> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=p>,</span><span class=w> </span><span class=mi>4</span><span class=p>,</span><span class=w> </span><span class=mi>5</span><span class=p>};</span>
|
||||
</code></pre></div> </div> <div class="admonition warning"> <p class=admonition-title><code>static_cast</code> and <code>get<std::optional<T>>()</code> are not guaranteed equivalent</p> <p><code>operator ValueType()</code> (used by <code>static_cast</code> and implicit conversions) intentionally excludes <code>std::optional<T></code> from delegating to <code>get<T>()</code>, to avoid a constructor ambiguity with <code>std::optional<T></code>'s own converting constructor from <code>basic_json</code>. As a result, <code>static_cast<std::optional<T>>(json_value)</code> goes through <code>std::optional<T></code>'s own converting constructor rather than through <code>get<std::optional<T>>()</code>, which can behave differently — for example, with a custom <code>adl_serializer<std::optional<T>></code> specialization. Prefer <code>get<std::optional<T>>()</code>/<code>get_to()</code> over <code>static_cast</code> for optional types.</p> </div> <div class="admonition warning"> <p class=admonition-title>Converting to a fixed-size destination does not check the array size</p> <p>Some destination types have a size that is fixed by their C++ type rather than by the <abbr title="JavaScript Object Notation">JSON</abbr> value: <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>pair</span><span class=o><</span><span class=n>A</span><span class=p>,</span><span class=w> </span><span class=n>B</span><span class=o>></span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>tuple</span><span class=o><</span><span class=n>Ts</span><span class=p>...</span><span class=o>></span></code>, <code class=highlight><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=n>T</span><span class=p>,</span><span class=w> </span><span class=n>N</span><span class=o>></span></code>, C arrays <code class=highlight><span class=n>T</span><span class=p>[</span><span class=n>N</span><span class=p>]</span></code>, and <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>unordered_map</span></code> with a non-string key type (which is read from an array of two-element arrays). All of them read exactly as many elements as they need via <a href=../../api/basic_json/at/ ><code>at</code></a> and <strong>never compare the <abbr title="JavaScript Object Notation">JSON</abbr> array's size to that number</strong>. The two mismatch directions therefore behave differently:</p> <ul> <li>The <abbr title="JavaScript Object Notation">JSON</abbr> array has <strong>too many</strong> elements: the surplus is <strong>silently discarded</strong>, and no exception is thrown.</li> <li>The <abbr title="JavaScript Object Notation">JSON</abbr> array has <strong>too few</strong> elements: <code>at</code> throws <a href=../../home/exceptions/#jsonexceptionout_of_range401><code>out_of_range.401</code></a> for the first missing index — an out-of-range error, not a <a href=../../home/exceptions/#type-errors><code>type_error</code></a>, even though the cause is a shape mismatch.</li> </ul> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=p>,</span><span class=w> </span><span class=mi>4</span><span class=p>,</span><span class=w> </span><span class=mi>5</span><span class=p>};</span>
|
||||
|
||||
<span class=k>auto</span><span class=w> </span><span class=n>a</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>get</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>array</span><span class=o><</span><span class=kt>int</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=o>>></span><span class=p>();</span><span class=w> </span><span class=c1>// {1, 2, 3} -- elements 4 and 5 silently dropped</span>
|
||||
<span class=k>auto</span><span class=w> </span><span class=n>p</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>get</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>pair</span><span class=o><</span><span class=kt>int</span><span class=p>,</span><span class=w> </span><span class=kt>int</span><span class=o>>></span><span class=p>();</span><span class=w> </span><span class=c1>// (1, 2) -- elements 3, 4, and 5 silently dropped</span>
|
||||
|
||||
<span class=n>json</span><span class=w> </span><span class=n>k</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{</span><span class=mi>1</span><span class=p>};</span>
|
||||
<span class=k>auto</span><span class=w> </span><span class=n>q</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>k</span><span class=p>.</span><span class=n>get</span><span class=o><</span><span class=n>std</span><span class=o>::</span><span class=n>pair</span><span class=o><</span><span class=kt>int</span><span class=p>,</span><span class=w> </span><span class=kt>int</span><span class=o>>></span><span class=p>();</span><span class=w> </span><span class=c1>// ❌ throws out_of_range.401</span>
|
||||
</code></pre></div> <p>If a size mismatch is an error in your application, check the size yourself before converting.</p> </div> <h2 id=omitting-a-field-when-serializing-stdoptional>Omitting a field when serializing <code>std::optional</code><a class=headerlink href=#omitting-a-field-when-serializing-stdoptional title="Permanent link">¶</a></h2> <p>By default, <code>to_json</code> for <code>std::optional<T></code> writes either the value or <code class=highlight><span class=kc>null</span></code> -- there is no built-in way to make a field disappear from the serialized object entirely when the <code>std::optional</code> is <code>std::nullopt</code>. Because a specialization of <code>adl_serializer<std::optional<T>></code> only controls how the <em>value</em> is converted (it cannot prevent the containing object's <code>to_json</code> from inserting the key in the first place), omission has to be implemented in the <em>containing</em> type's <code>to_json</code>:</p> <div class=highlight><pre><span></span><code><span class=k>struct</span><span class=w> </span><span class=nc>person</span><span class=w> </span><span class=p>{</span>
|
||||
</code></pre></div> <p>If a size mismatch is an error in your application, check the size yourself before converting.</p> </div> <h2 id=omitting-a-field-when-serializing-stdoptional>Omitting a field when serializing <code>std::optional</code><a class=headerlink href=#omitting-a-field-when-serializing-stdoptional title="Permanent link">¶</a></h2> <p>By default, <code>to_json</code> for <code>std::optional<T></code> writes either the value or <code class=highlight><span class=kc>null</span></code> — there is no built-in way to make a field disappear from the serialized object entirely when the <code>std::optional</code> is <code>std::nullopt</code>. Because a specialization of <code>adl_serializer<std::optional<T>></code> only controls how the <em>value</em> is converted (it cannot prevent the containing object's <code>to_json</code> from inserting the key in the first place), omission has to be implemented in the <em>containing</em> type's <code>to_json</code>:</p> <div class=highlight><pre><span></span><code><span class=k>struct</span><span class=w> </span><span class=nc>person</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>string</span><span class=w> </span><span class=n>name</span><span class=p>;</span>
|
||||
<span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>optional</span><span class=o><</span><span class=kt>int</span><span class=o>></span><span class=w> </span><span class=n>age</span><span class=p>;</span>
|
||||
<span class=p>};</span>
|
||||
@@ -117,7 +117,7 @@
|
||||
<span class=p>}</span>
|
||||
</code></pre></div> <h2 id=putting-values-in>Putting values in<a class=headerlink href=#putting-values-in title="Permanent link">¶</a></h2> <p>The reverse direction works the same way: assigning or constructing a <code>json</code> from a C++ value converts it to <abbr title="JavaScript Object Notation">JSON</abbr>.</p> <div class=highlight><pre><span></span><code><span class=n>std</span><span class=o>::</span><span class=n>vector</span><span class=o><</span><span class=kt>int</span><span class=o>></span><span class=w> </span><span class=n>numbers</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=p>};</span>
|
||||
<span class=n>json</span><span class=w> </span><span class=n>j</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>numbers</span><span class=p>;</span><span class=w> </span><span class=c1>// [1,2,3]</span>
|
||||
</code></pre></div> <div class="admonition info"> <p class=admonition-title>Constructing from a C++20 range view</p> <p>A <code>json</code> array can also be constructed directly from a C++20 range view (<code>std::ranges::view</code>), such as the result of <code>std::views::filter</code> or <code>std::views::transform</code> -- no intermediate container is needed:</p> <div class=highlight><pre><span></span><code><span class=n>std</span><span class=o>::</span><span class=n>vector</span><span class=o><</span><span class=kt>int</span><span class=o>></span><span class=w> </span><span class=n>nums</span><span class=p>{</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>37</span><span class=p>,</span><span class=w> </span><span class=mi>42</span><span class=p>,</span><span class=w> </span><span class=mi>21</span><span class=p>};</span>
|
||||
</code></pre></div> <div class="admonition info"> <p class=admonition-title>Constructing from a C++20 range view</p> <p>A <code>json</code> array can also be constructed directly from a C++20 range view (<code>std::ranges::view</code>), such as the result of <code>std::views::filter</code> or <code>std::views::transform</code> — no intermediate container is needed:</p> <div class=highlight><pre><span></span><code><span class=n>std</span><span class=o>::</span><span class=n>vector</span><span class=o><</span><span class=kt>int</span><span class=o>></span><span class=w> </span><span class=n>nums</span><span class=p>{</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>37</span><span class=p>,</span><span class=w> </span><span class=mi>42</span><span class=p>,</span><span class=w> </span><span class=mi>21</span><span class=p>};</span>
|
||||
<span class=k>auto</span><span class=w> </span><span class=n>filtered</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>nums</span><span class=w> </span><span class=o>|</span><span class=w> </span><span class=n>std</span><span class=o>::</span><span class=n>views</span><span class=o>::</span><span class=n>filter</span><span class=p>([](</span><span class=kt>int</span><span class=w> </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>return</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>10</span><span class=p>;</span><span class=w> </span><span class=p>});</span>
|
||||
<span class=n>json</span><span class=w> </span><span class=nf>j</span><span class=p>(</span><span class=n>filtered</span><span class=p>);</span><span class=w> </span><span class=c1>// [37,42,21]</span>
|
||||
</code></pre></div> <p>This requires <a href=../../api/macros/json_has_ranges/ ><code>JSON_HAS_RANGES</code></a> to be enabled and is unavailable on <abbr title="Minimalist GNU for Windows">MinGW</abbr> due to incomplete C++20 ranges support there; see <a href=../../api/macros/json_has_range_view_conversion/ ><code>JSON_HAS_RANGE_VIEW_CONVERSION</code></a>.</p> </div> <h2 id=your-own-types>Your own types<a class=headerlink href=#your-own-types title="Permanent link">¶</a></h2> <p>The conversions above are built in for standard types. To make the same syntax work for <strong>your own</strong> types, provide <code>to_json</code>/<code>from_json</code> functions (or use one of the convenience macros). This is described in detail on the <a href=../arbitrary_types/ >arbitrary types conversions</a> page. Enums can be mapped to strings as described in <a href=../enum_conversion/ >specializing enum conversion</a>.</p> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">¶</a></h2> <ul> <li><a href=../../api/basic_json/get/ ><code>get</code></a> - get a copy converted to a given type</li> <li><a href=../../api/basic_json/get_to/ ><code>get_to</code></a> - convert into an existing variable</li> <li><a href=../../api/basic_json/get_ref/ ><code>get_ref</code></a> / <a href=../../api/basic_json/get_ptr/ ><code>get_ptr</code></a> - access the stored value without copying</li> <li><a href=../arbitrary_types/ >Arbitrary types conversions</a> - support your own types</li> <li><a href=../../api/macros/json_use_implicit_conversions/ ><code>JSON_USE_IMPLICIT_CONVERSIONS</code></a> - toggle implicit conversions</li> <li><a href=../json_view/ >Zero-copy <abbr title="JavaScript Object Notation">JSON</abbr> views</a> - get values out of a document or a view</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 25, 2026 11:07:13 UTC">October 25, 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 © 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-1Line truncated
|
||||
</code></pre></div> <p>This requires <a href=../../api/macros/json_has_ranges/ ><code>JSON_HAS_RANGES</code></a> to be enabled and is unavailable on <abbr title="Minimalist GNU for Windows">MinGW</abbr> due to incomplete C++20 ranges support there; see <a href=../../api/macros/json_has_range_view_conversion/ ><code>JSON_HAS_RANGE_VIEW_CONVERSION</code></a>.</p> </div> <h2 id=your-own-types>Your own types<a class=headerlink href=#your-own-types title="Permanent link">¶</a></h2> <p>The conversions above are built in for standard types. To make the same syntax work for <strong>your own</strong> types, provide <code>to_json</code>/<code>from_json</code> functions (or use one of the convenience macros). This is described in detail on the <a href=../arbitrary_types/ >arbitrary types conversions</a> page. Enums can be mapped to strings as described in <a href=../enum_conversion/ >specializing enum conversion</a>.</p> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">¶</a></h2> <ul> <li><a href=../../api/basic_json/get/ ><code>get</code></a> - get a copy converted to a given type</li> <li><a href=../../api/basic_json/get_to/ ><code>get_to</code></a> - convert into an existing variable</li> <li><a href=../../api/basic_json/get_ref/ ><code>get_ref</code></a> - / <a href=../../api/basic_json/get_ptr/ ><code>get_ptr</code></a> - access the stored value without copying</li> <li><a href=../arbitrary_types/ >Arbitrary types conversions</a> - support your own types</li> <li><a href=../../api/macros/json_use_implicit_conversions/ ><code>JSON_USE_IMPLICIT_CONVERSIONS</code></a> - toggle implicit conversions</li> <li><a href=../json_view/ >Zero-copy <abbr title="JavaScript Object Notation">JSON</abbr> views</a> - get values out of a document or a view</li> <li><a href=../../api/adl_serializer/ ><code>adl_serializer</code></a> - the default serializer behind the conversions</li> <li><a href=../../api/basic_json/type/ ><code>type</code></a> - query the type of a value</li> <li><a href=../../api/macros/json_disable_tuple_reference_conversion/ ><code>JSON_DISABLE_TUPLE_REFERENCE_CONVERSION</code></a> - toggle conversion to tuples of references</li> <li><a href=../../api/macros/json_has_range_view_conversion/ ><code>JSON_HAS_RANGE_VIEW_CONVERSION</code></a> - toggle conversion from ranges</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 27, 2026 06:41:42 UTC">October 27, 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> <nav class="md-footer__inner md-grid" aria-label=Footer> <a href=../comments/ class="md-footer__link md-footer__link--prev" aria-label="Previous: Comments"> <div class="md-footer__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11z"/></svg> </div> <div class=md-footer__title> <span class=md-footer__direction> Previous </span> <div class=md-ellipsis> Comments </div> </div> </a> <a href=../creating_values/ class="md-footer__link md-footer__link--next" aria-label="Next: Creating JSON values"> <div class=md-footer__title> <span class=md-footer__direction> Next </span> <div class=md-ellipsis> Creating JSON values </div> </div> <div class="md-footer__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11z"/></svg> </div> </a> </nav> <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 &Line truncated
|
||||
@@ -197,14 +197,14 @@ j_null.get_to(opt); // ✅ std::nullopt
|
||||
|
||||
`static_cast` and `get<std::optional<T>>()` are not guaranteed equivalent
|
||||
|
||||
`operator ValueType()` (used by `static_cast` and implicit conversions) intentionally excludes `std::optional<T>` from delegating to `get<T>()`, to avoid a constructor ambiguity with `std::optional<T>`'s own converting constructor from `basic_json`. As a result, `static_cast<std::optional<T>>(json_value)` goes through `std::optional<T>`'s own converting constructor rather than through `get<std::optional<T>>()`, which can behave differently -- for example, with a custom `adl_serializer<std::optional<T>>` specialization. Prefer `get<std::optional<T>>()`/`get_to()` over `static_cast` for optional types.
|
||||
`operator ValueType()` (used by `static_cast` and implicit conversions) intentionally excludes `std::optional<T>` from delegating to `get<T>()`, to avoid a constructor ambiguity with `std::optional<T>`'s own converting constructor from `basic_json`. As a result, `static_cast<std::optional<T>>(json_value)` goes through `std::optional<T>`'s own converting constructor rather than through `get<std::optional<T>>()`, which can behave differently — for example, with a custom `adl_serializer<std::optional<T>>` specialization. Prefer `get<std::optional<T>>()`/`get_to()` over `static_cast` for optional types.
|
||||
|
||||
Converting to a fixed-size destination does not check the array size
|
||||
|
||||
Some destination types have a size that is fixed by their C++ type rather than by the JSON value: `std::pair<A, B>`, `std::tuple<Ts...>`, `std::array<T, N>`, C arrays `T[N]`, and `std::map`/`std::unordered_map` with a non-string key type (which is read from an array of two-element arrays). All of them read exactly as many elements as they need via [`at`](https://json.nlohmann.me/api/basic_json/at/index.md) and **never compare the JSON array's size to that number**. The two mismatch directions therefore behave differently:
|
||||
|
||||
- The JSON array has **too many** elements: the surplus is **silently discarded**, and no exception is thrown.
|
||||
- The JSON array has **too few** elements: `at` throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) for the first missing index -- an out-of-range error, not a [`type_error`](https://json.nlohmann.me/home/exceptions/#type-errors), even though the cause is a shape mismatch.
|
||||
- The JSON array has **too few** elements: `at` throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) for the first missing index — an out-of-range error, not a [`type_error`](https://json.nlohmann.me/home/exceptions/#type-errors), even though the cause is a shape mismatch.
|
||||
|
||||
```
|
||||
json j = {1, 2, 3, 4, 5};
|
||||
@@ -220,7 +220,7 @@ If a size mismatch is an error in your application, check the size yourself befo
|
||||
|
||||
## Omitting a field when serializing `std::optional`
|
||||
|
||||
By default, `to_json` for `std::optional<T>` writes either the value or `null` -- there is no built-in way to make a field disappear from the serialized object entirely when the `std::optional` is `std::nullopt`. Because a specialization of `adl_serializer<std::optional<T>>` only controls how the *value* is converted (it cannot prevent the containing object's `to_json` from inserting the key in the first place), omission has to be implemented in the *containing* type's `to_json`:
|
||||
By default, `to_json` for `std::optional<T>` writes either the value or `null` — there is no built-in way to make a field disappear from the serialized object entirely when the `std::optional` is `std::nullopt`. Because a specialization of `adl_serializer<std::optional<T>>` only controls how the *value* is converted (it cannot prevent the containing object's `to_json` from inserting the key in the first place), omission has to be implemented in the *containing* type's `to_json`:
|
||||
|
||||
```
|
||||
struct person {
|
||||
@@ -247,7 +247,7 @@ json j = numbers; // [1,2,3]
|
||||
|
||||
Constructing from a C++20 range view
|
||||
|
||||
A `json` array can also be constructed directly from a C++20 range view (`std::ranges::view`), such as the result of `std::views::filter` or `std::views::transform` -- no intermediate container is needed:
|
||||
A `json` array can also be constructed directly from a C++20 range view (`std::ranges::view`), such as the result of `std::views::filter` or `std::views::transform` — no intermediate container is needed:
|
||||
|
||||
```
|
||||
std::vector<int> nums{1, 2, 37, 42, 21};
|
||||
@@ -265,7 +265,11 @@ The conversions above are built in for standard types. To make the same syntax w
|
||||
|
||||
- [`get`](https://json.nlohmann.me/api/basic_json/get/index.md) - get a copy converted to a given type
|
||||
- [`get_to`](https://json.nlohmann.me/api/basic_json/get_to/index.md) - convert into an existing variable
|
||||
- [`get_ref`](https://json.nlohmann.me/api/basic_json/get_ref/index.md) / [`get_ptr`](https://json.nlohmann.me/api/basic_json/get_ptr/index.md) - access the stored value without copying
|
||||
- [`get_ref`](https://json.nlohmann.me/api/basic_json/get_ref/index.md) - / [`get_ptr`](https://json.nlohmann.me/api/basic_json/get_ptr/index.md) - access the stored value without copying
|
||||
- [Arbitrary types conversions](https://json.nlohmann.me/features/arbitrary_types/index.md) - support your own types
|
||||
- [`JSON_USE_IMPLICIT_CONVERSIONS`](https://json.nlohmann.me/api/macros/json_use_implicit_conversions/index.md) - toggle implicit conversions
|
||||
- [Zero-copy JSON views](https://json.nlohmann.me/features/json_view/index.md) - get values out of a document or a view
|
||||
- [`adl_serializer`](https://json.nlohmann.me/api/adl_serializer/index.md) - the default serializer behind the conversions
|
||||
- [`type`](https://json.nlohmann.me/api/basic_json/type/index.md) - query the type of a value
|
||||
- [`JSON_DISABLE_TUPLE_REFERENCE_CONVERSION`](https://json.nlohmann.me/api/macros/json_disable_tuple_reference_conversion/index.md) - toggle conversion to tuples of references
|
||||
- [`JSON_HAS_RANGE_VIEW_CONVERSION`](https://json.nlohmann.me/api/macros/json_has_range_view_conversion/index.md) - toggle conversion from ranges
|
||||
Reference in new issue
Block a user