This commit is contained in:
nlohmann committed 2026-10-26 21:24:35 +00:00
1 parent 41c601a7d1
commit d2e264bd84
1400 files changed
+11859 -5440

No files matched your search

+6 -6
View File
@@ -1,4 +1,4 @@
<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=author content="Niels Lohmann"><link href="https://json.nlohmann.me/home/faq/" rel="canonical"><link href=../license/ rel=prev><link href=../exceptions/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>FAQ - 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=#frequently-asked-questions-faq 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> FAQ </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> </label> <div class=md-search data-md-cLine 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=author content="Niels Lohmann"><link href="https://json.nlohmann.me/home/faq/" rel="canonical"><link href=../license/ rel=prev><link href=../exceptions/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.7.7"><title>FAQ - 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=#frequently-asked-questions-faq 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> FAQ </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> </label> <div class=md-search data-md-cLine truncated
</code></pre></div> <p>and</p> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=w> </span><span class=nf>j</span><span class=p>(</span><span class=nb>true</span><span class=p>);</span>
</code></pre></div> <p>yield different results (<code class=highlight><span class=p>[</span><span class=kc>true</span><span class=p>]</span></code> vs. <code class=highlight><span class=kc>true</span></code>)?</p> </div> <p>This is a known issue, and -- even worse -- the behavior differs between <abbr title="GNU Compiler Collection">GCC</abbr> and Clang. The "culprit" for this is the library's constructor overloads for initializer lists to allow syntax like</p> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=w> </span><span class=n>array</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>
</code></pre></div> <p>for arrays and</p> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=w> </span><span class=n>object</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{{</span><span class=s>"one"</span><span class=p>,</span><span class=w> </span><span class=mi>1</span><span class=p>},</span><span class=w> </span><span class=p>{</span><span class=s>"two"</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>}};</span><span class=w> </span>
@@ -8,16 +8,16 @@
<span class=n>json</span><span class=w> </span><span class=n>obj</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>{{</span><span class=s>"key"</span><span class=p>,</span><span class=w> </span><span class=s>"value"</span><span class=p>}};</span>
<span class=n>json</span><span class=w> </span><span class=n>j</span><span class=p>{</span><span class=n>obj</span><span class=p>};</span><span class=w> </span><span class=c1>// -&gt; {"key":"value"} (copy, not array)</span>
</code></pre></div> <p>Without the macro (default behavior), <code>json j{obj}</code> creates <code>[{"key":"value"}]</code>. This opt-in macro fixes issue #5074 while preserving backwards compatibility for existing code.</p> <h2 id=limitations>Limitations<a class=headerlink href=#limitations title="Permanent link">&para;</a></h2> <h3 id=relaxed-parsing>Relaxed parsing<a class=headerlink href=#relaxed-parsing title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Can you add an option to ignore trailing commas?</p> </div> <p>Yes, trailing commas in arrays and objects can be allowed by setting parameter <code>ignore_trailing_commas</code> of <a href=../../api/basic_json/parse/ ><code>parse</code></a> to <code class=highlight><span class=nb>true</span></code>; see <a href=../../features/trailing_commas/ >trailing commas</a>. They are rejected by default, and the library never adds them when serializing.</p> <h3 id=parse-errors-reading-non-ascii-characters>Parse errors reading non-<abbr title="American Standard Code for Information Interchange">ASCII</abbr> characters<a class=headerlink href=#parse-errors-reading-non-ascii-characters title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Questions</p> <ul> <li>Why is the parser complaining about a Chinese character?</li> <li>Does the library support Unicode?</li> <li>I get an exception <code>[json.exception.parse_error.101] parse error at line 1, column 53: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '"Testé$')"</code></li> </ul> </div> <p>The library supports <strong>Unicode input</strong> as follows:</p> <ul> <li><strong><abbr title="Unicode Transformation Format">UTF</abbr>-8</strong> encoded input is supported, which is the default encoding for <abbr title="JavaScript Object Notation">JSON</abbr>, according to <a href="https://tools.ietf.org/html/rfc8259.html#section-8.1"><abbr title="Request for Comments">RFC</abbr> 8259</a>.</li> <li><code>std::u16string</code> and <code>std::u32string</code> can be parsed, assuming <abbr title="Unicode Transformation Format">UTF</abbr>-16 and <abbr title="Unicode Transformation Format">UTF</abbr>-32 encoding, respectively; <code>std::wstring</code> works as well and is interpreted as <abbr title="Unicode Transformation Format">UTF</abbr>-16 or <abbr title="Unicode Transformation Format">UTF</abbr>-32, depending on the width of the platform's <code>wchar_t</code>. These encodings cannot be read from a <code>FILE*</code> or a <code>std::istream</code>, which carry bytes only.</li> <li>Ill-formed <abbr title="Unicode Transformation Format">UTF</abbr>-16 or <abbr title="Unicode Transformation Format">UTF</abbr>-32 input is rejected: a lone surrogate, a high surrogate that is not followed by its low surrogate, and a code point above <code>U+10FFFF</code> all yield a parse error. The same holds for iterators over 2- or 4-byte characters.</li> <li>Other encodings such as Latin-1 or <abbr title="International Organization for Standardization">ISO</abbr> 8859-1 are <strong>not</strong> supported and will yield parse or serialization errors.</li> <li>The library will not replace <a href="http://www.unicode.org/faq/private_use.html#nonchar1">Unicode noncharacters</a>.</li> <li>Invalid surrogates (e.g., incomplete pairs such as <code>\uDEAD</code>) will yield parse errors.</li> <li>The strings stored in the library are <abbr title="Unicode Transformation Format">UTF</abbr>-8 encoded. When using the default string type (<code>std::string</code>), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.</li> <li>When you store strings with different encodings in the library, calling <a href=../../api/basic_json/dump/ ><code>dump()</code></a> may throw an exception unless <code>json::error_handler_t::replace</code>, <code>json::error_handler_t::ignore</code>, or <code>json::error_handler_t::keep</code> are used as error handlers.</li> </ul> <p>In most cases, the parser is right to complain, because the input is not <abbr title="Unicode Transformation Format">UTF</abbr>-8 encoded. This is especially true for Microsoft Windows, where Latin-1 or <abbr title="International Organization for Standardization">ISO</abbr> 8859-1 is often the standard encoding.</p> <h3 id=nul-bytes-in-the-input>NUL bytes in the input<a class=headerlink href=#nul-bytes-in-the-input title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Questions</p> <ul> <li>Why does <a href=../../api/basic_json/parse/ ><code>json::parse()</code></a> silently ignore part of my input?</li> <li>Why does a <code>std::string</code>/buffer with extra data after the <abbr title="JavaScript Object Notation">JSON</abbr> text parse without error, while a similar-looking string with extra text does not?</li> </ul> </div> <p>A <code>'\0'</codLine truncated
</code></pre></div> <p>Without the macro (default behavior), <code>json j{obj}</code> creates <code>[{"key":"value"}]</code>. This opt-in macro fixes issue #5074 while preserving backwards compatibility for existing code.</p> <h2 id=getting-started>Getting started<a class=headerlink href=#getting-started title="Permanent link">&para;</a></h2> <h3 id=which-file-do-i-need>Which file do I need?<a class=headerlink href=#which-file-do-i-need title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Do I have to clone the repository or build the library?</p> </div> <p>No. The library is header-only: the single file <a href="https://github.com/nlohmann/json/releases"><code>json.hpp</code></a> from the releases page is all you need, including the <code>_json</code> literals. Put it in a directory <code>nlohmann</code> on your include path. Companion headers (<code>json_fwd.hpp</code>, <code>json_view.hpp</code>, <code>json_literals.hpp</code>) are only needed if you use them. See <a href=../../integration/#header-only>Integration</a>.</p> <h3 id=using-cmake-or-a-package-manager>Using CMake or a package manager<a class=headerlink href=#using-cmake-or-a-package-manager title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>How do I add the library with CMake, Conan, vcpkg, Homebrew, or another tool?</p> </div> <p>See <a href=../../integration/cmake/ >CMake</a> for <code>find_package</code>, <code>add_subdirectory</code>, and <code>FetchContent</code>, and <a href=../../integration/package_managers/ >Package managers</a> for the list of supported package managers.</p> <h3 id=the-ide-cannot-open-the-header>The <abbr title="Integrated Development Environment">IDE</abbr> cannot open the header<a class=headerlink href=#the-ide-cannot-open-the-header title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>The compiler finds <code>nlohmann/json.hpp</code>, but my <abbr title="Integrated Development Environment">IDE</abbr> reports "cannot open source file". Why?</p> </div> <p>The compiler's include path is set correctly, but the <abbr title="Integrated Development Environment">IDE</abbr>'s is not. Add the same directory to the include paths of the <abbr title="Integrated Development Environment">IDE</abbr> (or of its language server); the build itself is not affected.</p> <h3 id=compile-times>Compile times<a class=headerlink href=#compile-times title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Including the library slows down my build. What can I do?</p> </div> <p>Include <a href=../../integration/compile_times/#include-json_fwdhpp-in-headers><code>json_fwd.hpp</code></a> in headers and <code>json.hpp</code> only in the source files that need it, instantiate <code>basic_json</code> once, and consider precompiled headers or <a href=../../features/modules/ >C++20 modules</a>. See <a href=../../integration/compile_times/ >Compile times</a>.</p> <h2 id=parsing>Parsing<a class=headerlink href=#parsing title="Permanent link">&para;</a></h2> <h3 id=parsing-a-file-fails-with-unexpected-end-of-input>Parsing a file fails with "unexpected end of input"<a class=headerlink href=#parsing-a-file-fails-with-unexpected-end-of-input title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p><code>json::parse(file)</code> throws <code>parse_error.101</code> at line 1, column 1 for a file that is valid <abbr title="JavaScript Object Notation">JSON</abbr>. Why?</p> </div> <p>The parser did not see any character: the file was most likely not opened. A relative path is resolved against the working directory of the running program, which is often the build directory of your <abbr title="Integrated Development Environment">IDE</abbr>, not the source directory. Check <code>is_open()</code> and try an absolute path. Other causes are an empty file and a stream that was already read. See <a href=../exceptions/#jsonexceptionparse_error101><code>parse_error.101</code></a>.</p> <h3 id=input-that-arrives-in-chunks>Input that arrives in chunks<a class=headerlink href=#input-that-arrives-in-chunks title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>My data comes from a socket in pieces. How do I parse it?</p> </div> <p>The parser cannot be resumed. Frame the messages (one value per line, a length prefix) and parse each complete frame, or buffer the chunks until the value is complete; a <code>parse_error</code> at the end of the buffer means the input ended prematurely. See <a href=../../features/parsing/large_and_partial_input/#input-arriving-in-chunks>Large, streamed, and partial input</a>.</p> <h3 id=several-values-in-one-stream>Several values in one stream<a class=headerlink href=#several-values-in-oneLine truncated
<span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=p>(</span><span class=s>"123"</span><span class=p>)</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=sc>'\0'</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=s>"true"</span><span class=p>);</span><span class=w> </span><span class=c1>// == 123, the "true" is silently ignored too</span>
</code></pre></div> <p>This is different from any other unexpected trailing byte, which <em>does</em> raise <a href=../exceptions/#jsonexceptionparse_error101><code>parse_error.101</code></a>:</p> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=s>"123x"</span><span class=p>);</span><span class=w> </span><span class=c1>// throws parse_error.101: unexpected additional data</span>
</code></pre></div> <p>This falls out of the same convention used when no explicit input length is given at all: <code>json::parse(const char*)</code> already stops at the first NUL byte via <code>strlen()</code>, since a bare pointer has no length of its own. The library applies that same NUL-terminated-C-string convention uniformly, rather than only when a length is genuinely unavailable — so a <code>std::string</code>, iterator range, or container whose content happens to include a NUL byte is affected the same way a raw <code>const char*</code> would be.</p> <p>If your input may contain a trailing or embedded NUL that is <strong>not</strong> meant to signal the end of the <abbr title="JavaScript Object Notation">JSON</abbr> text — for instance, a fixed-size, zero-padded buffer — trim it yourself before calling <code>parse()</code>, since the library will otherwise silently stop there instead of raising an error:</p> <div class=highlight><pre><span></span><code><span class=n>s</span><span class=p>.</span><span class=n>resize</span><span class=p>(</span><span class=n>s</span><span class=p>.</span><span class=n>find</span><span class=p>(</span><span class=sc>'\0'</span><span class=p>));</span><span class=w> </span><span class=c1>// drop everything from the first NUL onward, if any</span>
</code></pre></div> <p>This falls out of the same convention used when no explicit input length is given at all: <code>json::parse(const char*)</code> already stops at the first <abbr title="Null character (U+0000, byte value 0)">NUL</abbr> byte via <code>strlen()</code>, since a bare pointer has no length of its own. The library applies that same <abbr title="Null character (U+0000, byte value 0)">NUL</abbr>-terminated-C-string convention uniformly, rather than only when a length is genuinely unavailable — so a <code>std::string</code>, iterator range, or container whose content happens to include a <abbr title="Null character (U+0000, byte value 0)">NUL</abbr> byte is affected the same way a raw <code>const char*</code> would be.</p> <p>If your input may contain a trailing or embedded <abbr title="Null character (U+0000, byte value 0)">NUL</abbr> that is <strong>not</strong> meant to signal the end of the <abbr title="JavaScript Object Notation">JSON</abbr> text — for instance, a fixed-size, zero-padded buffer — trim it yourself before calling <code>parse()</code>, since the library will otherwise silently stop there instead of raising an error:</p> <div class=highlight><pre><span></span><code><span class=n>s</span><span class=p>.</span><span class=n>resize</span><span class=p>(</span><span class=n>s</span><span class=p>.</span><span class=n>find</span><span class=p>(</span><span class=sc>'\0'</span><span class=p>));</span><span class=w> </span><span class=c1>// drop everything from the first NUL onward, if any</span>
<span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>s</span><span class=p>);</span>
</code></pre></div> <p><strong>Opt-in strict handling (since version 3.13.0 <span class=unreleased-version title="Not part of a release yet; the latest release is 3.12.0.">unreleased</span>)</strong></p> <p>Manually trimming every input is easy to forget. If you define <a href=../../api/macros/json_strict_nul_handling/ ><code>JSON_STRICT_NUL_HANDLING</code></a> to <code>1</code> before including the library, a <code>'\0'</code> byte is instead rejected like any other unexpected byte and raises <code>parse_error.101</code>, instead of being treated as end of input:</p> <div class=highlight><pre><span></span><code><span class=cp>#define JSON_STRICT_NUL_HANDLING 1</span>
<span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;nlohmann/json.hpp&gt;</span>
<span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=p>(</span><span class=s>"123"</span><span class=p>)</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=sc>'\0'</span><span class=p>);</span><span class=w> </span><span class=c1>// throws parse_error.101 instead of silently returning 123</span>
</code></pre></div> <p>This macro defaults to <code>0</code> (disabled, preserving the behavior described above) to avoid breaking existing code that may depend on it, even unknowingly; it is planned to become the default in version 4.0.0. See <a href=../../api/macros/json_strict_nul_handling/ >its documentation</a> for details, including how it also affects <code>char</code> arrays such as string literals.</p> <p>Note that this is unrelated to an <em>unescaped</em> NUL byte occurring <strong>inside</strong> a quoted <abbr title="JavaScript Object Notation">JSON</abbr> string, which is a different, already-invalid case and is correctly rejected either way:</p> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=p>(</span><span class=s>"</span><span class=se>\"</span><span class=s>"</span><span class=p>)</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=sc>'\0'</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=s>"</span><span class=se>\"</span><span class=s>"</span><span class=p>);</span><span class=w> </span><span class=c1>// throws parse_error.101: control character U+0000 (NUL) must be escaped to \u0000</span>
</code></pre></div> <p>This macro defaults to <code>0</code> (disabled, preserving the behavior described above) to avoid breaking existing code that may depend on it, even unknowingly; it is planned to become the default in version 4.0.0. See <a href=../../api/macros/json_strict_nul_handling/ >its documentation</a> for details, including how it also affects <code>char</code> arrays such as string literals.</p> <p>Note that this is unrelated to an <em>unescaped</em> <abbr title="Null character (U+0000, byte value 0)">NUL</abbr> byte occurring <strong>inside</strong> a quoted <abbr title="JavaScript Object Notation">JSON</abbr> string, which is a different, already-invalid case and is correctly rejected either way:</p> <div class=highlight><pre><span></span><code><span class=n>json</span><span class=o>::</span><span class=n>parse</span><span class=p>(</span><span class=n>std</span><span class=o>::</span><span class=n>string</span><span class=p>(</span><span class=s>"</span><span class=se>\"</span><span class=s>"</span><span class=p>)</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=sc>'\0'</span><span class=w> </span><span class=o>+</span><span class=w> </span><span class=s>"</span><span class=se>\"</span><span class=s>"</span><span class=p>);</span><span class=w> </span><span class=c1>// throws parse_error.101: control character U+0000 (NUL) must be escaped to \u0000</span>
</code></pre></div> <h3 id=wide-string-handling>Wide string handling<a class=headerlink href=#wide-string-handling title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Why are wide strings (e.g., <code>std::wstring</code>) dumped as arrays of numbers?</p> </div> <p>As described <a href=#parse-errors-reading-non-ascii-characters>above</a>, the library stores its strings as <abbr title="Unicode Transformation Format">UTF</abbr>-8. To store a wide string as a string, convert it to a <abbr title="Unicode Transformation Format">UTF</abbr>-8 encoded <code>std::string</code> first, as in the example below.</p> <div class="admonition example"> <p class=admonition-title>Example</p> <div class=highlight><pre><span></span><code><span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;codecvt&gt;</span><span class=w> </span><span class=c1>// codecvt_utf8</span>
<span class=cp>#include</span><span class=w> </span><span class=cpf>&lt;locale&gt;</span><span class=w> </span><span class=c1>// wstring_convert</span>
@@ -39,7 +39,7 @@
<span class=w> </span><span class=nt>"encoded"</span><span class=p>:</span><span class=w> </span><span class=s2>"車B1234 こんにちは"</span><span class=p>,</span>
<span class=w> </span><span class=nt>"original"</span><span class=p>:</span><span class=w> </span><span class=p>[</span><span class=mi>36554</span><span class=p>,</span><span class=w> </span><span class=mi>66</span><span class=p>,</span><span class=w> </span><span class=mi>49</span><span class=p>,</span><span class=w> </span><span class=mi>50</span><span class=p>,</span><span class=w> </span><span class=mi>51</span><span class=p>,</span><span class=w> </span><span class=mi>52</span><span class=p>,</span><span class=w> </span><span class=mi>32</span><span class=p>,</span><span class=w> </span><span class=mi>12371</span><span class=p>,</span><span class=w> </span><span class=mi>12435</span><span class=p>,</span><span class=w> </span><span class=mi>12395</span><span class=p>,</span><span class=w> </span><span class=mi>12385</span><span class=p>,</span><span class=w> </span><span class=mi>12399</span><span class=p>]</span>
<span class=p>}</span>
</code></pre></div> </div> <h2 id=usage>Usage<a class=headerlink href=#usage title="Permanent link">&para;</a></h2> <h3 id=thread-safety>Thread safety<a class=headerlink href=#thread-safety title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Is <code>basic_json</code> thread-safe?</p> </div> <p>No. <code>basic_json</code> provides no built-in synchronization, the same as <code>std::map</code> or <code>std::vector</code>. Concurrent reads of the same value from multiple threads are safe, as are concurrent (non-overlapping) accesses to independent <code>json</code> objects. However, any concurrent write to a <code>json</code> object -- or a concurrent read while another thread writes to the same object -- is a data race and requires external synchronization (e.g., a <code>std::mutex</code>) by the caller.</p> <h3 id=schema-validation>Schema validation<a class=headerlink href=#schema-validation title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Does this library support <abbr title="JavaScript Object Notation">JSON</abbr> Schema validation?</p> </div> <p>Not directly, but the companion project <a href="https://github.com/pboettch/json-schema-validator">json-schema-validator</a> builds <abbr title="JavaScript Object Notation">JSON</abbr> Schema (draft 7; draft 4 in its older, now-superseded 1.x releases) validation on top of this library and is a common recommendation for this use case.</p> <h2 id=exceptions>Exceptions<a class=headerlink href=#exceptions title="Permanent link">&para;</a></h2> <h3 id=parsing-without-exceptions>Parsing without exceptions<a class=headerlink href=#parsing-without-exceptions title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Is it possible to indicate a parse error without throwing an exception?</p> </div> <p>Yes, see <a href=../../features/parsing/parse_exceptions/ >Parsing and exceptions</a>.</p> <h3 id=key-name-in-exceptions>Key name in exceptions<a class=headerlink href=#key-name-in-exceptions title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Can I get the key of the object item that caused an exception?</p> </div> <p>Yes, you can. Please define the symbol <a href=../../api/macros/json_diagnostics/ ><code>JSON_DIAGNOSTICS</code></a> to get <a href=../exceptions/#extended-diagnostic-messages>extended diagnostics messages</a>.</p> <h2 id=serialization-issues>Serialization issues<a class=headerlink href=#serialization-issues title="Permanent link">&para;</a></h2> <h3 id=number-precision>Number precision<a class=headerlink href=#number-precision title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <ul> <li>It seems that precision is lost when serializing a double.</li> <li>Can I change the precision for floating-point serialization?</li> </ul> </div> <p>The library serializes floating-point numbers with the shortest representation that parses back to the same value, using at most <code>std::numeric_limits&lt;number_float_t&gt;::max_digits10</code> (17 for <abbr title="Institute of Electrical and Electronics Engineers">IEEE</abbr> <code>double</code>s) significant digits. This guarantees that value -&gt; string -&gt; value round-trips. The reverse direction, string -&gt; value -&gt; string, is only guaranteed for numbers with at most <code>std::numeric_limits&lt;number_float_t&gt;::digits10</code> (15 for <abbr title="Institute of Electrical and Electronics Engineers">IEEE</abbr> <code>double</code>s) significant digits; a number with more digits may not be representable exactly and is then serialized as the closest <code>double</code>.</p> <div class="admonition quote"> <p class=admonition-title><a href="https://en.cppreference.com/w/cpp/types/numeric_limits/max_digits10">cppreference.com</a></p> <p>The value of <code>std::numeric_limits&lt;T&gt;::max_digits10</code> is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type T, such as necessary for serialization/deserialization to text.</p> </div> <div class="admonition tip"> <p class=admonition-title>Tip</p> <p>The website <a href="https://float.exposed">https://float.exposed</a> gives a good insight into the internal storage of floating-point numbers.</p> </div> <p>See <a href=../../features/types/number_handling/#number-serialization>this section</a> on the library's number handling for more information.</p> <h3 id=serializing-untrusted-or-invalid-utf-8>Serializing untrusted or invalid <abbr title="Unicode Transformation Format">UTF</abbr>-8<a class=headerlink href=#serializing-untrusted-or-invalid-utf-8 title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Questions</p> <ul> <li>Why does <code>dump()</code> throw when I serializLine truncated
</code></pre></div> </div> <h2 id=usage>Usage<a class=headerlink href=#usage title="Permanent link">&para;</a></h2> <h3 id=thread-safety>Thread safety<a class=headerlink href=#thread-safety title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Is <code>basic_json</code> thread-safe?</p> </div> <p>No. <code>basic_json</code> provides no built-in synchronization, the same as <code>std::map</code> or <code>std::vector</code>. Concurrent reads of the same value from multiple threads are safe, as are concurrent (non-overlapping) accesses to independent <code>json</code> objects. However, any concurrent write to a <code>json</code> object -- or a concurrent read while another thread writes to the same object -- is a data race and requires external synchronization (e.g., a <code>std::mutex</code>) by the caller.</p> <h3 id=schema-validation>Schema validation<a class=headerlink href=#schema-validation title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Does this library support <abbr title="JavaScript Object Notation">JSON</abbr> Schema validation?</p> </div> <p>Not directly, but the companion project <a href="https://github.com/pboettch/json-schema-validator">json-schema-validator</a> builds <abbr title="JavaScript Object Notation">JSON</abbr> Schema (draft 7; draft 4 in its older, now-superseded 1.x releases) validation on top of this library and is a common recommendation for this use case.</p> <h3 id=memory-use>Memory use<a class=headerlink href=#memory-use title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Does the library leak memory? My process stays large after I free a <code>json</code> value.</p> </div> <p>Destroying a value frees everything it owns. Freed memory is returned to the allocator, which does not necessarily give it back to the operating system, so a high resident size alone is not a leak. Copies are deep, and <code>clear()</code> keeps the capacity of an array. See <a href=../../features/performance/#memory>Memory</a>, and use Valgrind or the sanitizers to tell a leak from retained memory.</p> <h3 id=reproducible-builds>Reproducible builds<a class=headerlink href=#reproducible-builds title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>The header path ends up in my binary. How do I get path-independent builds?</p> </div> <p>The runtime assertions embed <code>__FILE__</code>. Define <code>NDEBUG</code> (the default for release builds) or map the path prefix; see <a href=../../integration/#notes-for-builds-and-distribution>Notes for builds and distribution</a>.</p> <h3 id=slow-debug-builds>Slow debug builds<a class=headerlink href=#slow-debug-builds title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Parsing a large file is very slow in my debug build. Can I compile the library with optimizations?</p> </div> <p>The library is header-only, so there is no separate source file. Keep the code that uses <code>json</code> in its own source file and compile that file with optimizations; see <a href=../../integration/#notes-for-builds-and-distribution>Notes for builds and distribution</a>.</p> <h2 id=exceptions>Exceptions<a class=headerlink href=#exceptions title="Permanent link">&para;</a></h2> <h3 id=parsing-without-exceptions>Parsing without exceptions<a class=headerlink href=#parsing-without-exceptions title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Is it possible to indicate a parse error without throwing an exception?</p> </div> <p>Yes, see <a href=../../features/parsing/parse_exceptions/ >Parsing and exceptions</a> and <a href=../../features/no_exceptions/ >Working without exceptions</a>.</p> <h3 id=key-name-in-exceptions>Key name in exceptions<a class=headerlink href=#key-name-in-exceptions title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Can I get the key of the object item that caused an exception?</p> </div> <p>Yes, you can. Please define the symbol <a href=../../api/macros/json_diagnostics/ ><code>JSON_DIAGNOSTICS</code></a> to get <a href=../exceptions/#extended-diagnostic-messages>extended diagnostics messages</a>.</p> <h2 id=serialization-issues>Serialization issues<a class=headerlink href=#serialization-issues title="Permanent link">&para;</a></h2> <h3 id=number-precision>Number precision<a class=headerlink href=#number-precision title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <ul> <li>It seems that precision is lost when serializing a double.</li> <li>Can I change the precision for floating-point serialization?</li> </ul> </div> <p>The library serializes floating-point numbers with theLine truncated
<span class=k>const</span><span class=w> </span><span class=k>auto</span><span class=w> </span><span class=n>s</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>dump</span><span class=p>(</span><span class=mi>-1</span><span class=p>,</span><span class=w> </span><span class=sc>' '</span><span class=p>,</span><span class=w> </span><span class=nb>false</span><span class=p>,</span><span class=w> </span><span class=n>json</span><span class=o>::</span><span class=n>error_handler_t</span><span class=o>::</span><span class=n>replace</span><span class=p>);</span>
</code></pre></div> <h3 id=using-json-values-with-stdformat-or-fmt>Using <abbr title="JavaScript Object Notation">JSON</abbr> values with <code>std::format</code> or <code>fmt</code><a class=headerlink href=#using-json-values-with-stdformat-or-fmt title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <ul> <li>Can I use <code>std::format("{}", j)</code> on a <abbr title="JavaScript Object Notation">JSON</abbr> value?</li> <li>Can I use <code>fmt::format("{}", j)</code> or <code>fmt::print("{}", j)</code> (the <a href="https://github.com/fmtlib/fmt">{fmt}</a> library) on a <abbr title="JavaScript Object Notation">JSON</abbr> value?</li> </ul> </div> <p><code>std::format</code> works out of the box since version 3.13.0 <span class=unreleased-version title="Not part of a release yet; the latest release is 3.12.0.">unreleased</span>, as long as the standard library provides <code>&lt;format&gt;</code> (see <a href=../../api/macros/json_has_std_format/ ><code>JSON_HAS_STD_FORMAT</code></a>); see <a href=../../api/basic_json/std_formatter/ ><code>std::formatter&lt;basic_json&gt;</code></a> for details, including the <code class=highlight><span class=s>"{:#}"</span></code> pretty-print spec, indent widths (<code class=highlight><span class=s>"{:2}"</span></code>), and custom indent characters (<code class=highlight><span class=s>"{:.&gt;#}"</span></code>).</p> <p>For <code>fmt</code>, the library ships <a href=../../api/basic_json/format_as/ ><code>format_as</code></a>, a small customization point <code>fmt</code> looks for via argument-dependent lookup. It only has an effect on fmt 10.0.0 through 11.0.2 — from fmt 11.1.0 onwards, <code>fmt</code> no longer picks up a <code>format_as</code> overload that returns a <code>std::string</code>. On such versions (or any version, if you also want the same <code class=highlight><span class=s>"{:#}"</span></code>/width/fill-and-align spec support that <code>std::formatter&lt;basic_json&gt;</code> has), define your own <code>fmt::formatter</code> specialization; see <a href=../../api/basic_json/format_as/ ><code>format_as</code></a> for a recipe that mirrors it.</p> <p>If you get ambiguous-overload errors when passing a <abbr title="JavaScript Object Notation">JSON</abbr> value to <code>fmt::format</code>/<code>fmt::print</code> without any <code>fmt::formatter&lt;json&gt;</code> specialization in scope, that's <code>fmt</code> picking up <code>basic_json</code>'s implicit <code>operator ValueType()</code> conversion operator (see <a href="https://github.com/nlohmann/json/issues/964">#964</a> and <a href="https://github.com/nlohmann/json/issues/958">#958</a>); disabling it via <a href=../../api/macros/json_use_implicit_conversions/ ><code>JSON_USE_IMPLICIT_CONVERSIONS 0</code></a> avoids the ambiguity.</p> <h2 id=compilation-issues>Compilation issues<a class=headerlink href=#compilation-issues title="Permanent link">&para;</a></h2> <h3 id=android-sdk>Android <abbr title="Software Development Kit">SDK</abbr><a class=headerlink href=#android-sdk title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Why does the code not compile with Android <abbr title="Software Development Kit">SDK</abbr>?</p> </div> <p>Since <a href="https://github.com/android/ndk/wiki/Changelog-r18"><abbr title="Native Development Kit">NDK</abbr> r18</a> (2018), <abbr title="GNU Compiler Collection">GCC</abbr> and the <code>gnustl</code>/<code>stlport</code> C++ libraries have been removed from the Android <abbr title="Native Development Kit">NDK</abbr>; Clang and <code>libc++</code> are now the only compiler and C++ library, and they support C++11 and later out of the box. With a current <abbr title="Native Development Kit">NDK</abbr>, no special configuration is needed to use this library.</p> <p>Only very old NDKs (before r18), which defaulted to <abbr title="GNU Compiler Collection">GCC</abbr> and <code>gnustl</code>, lacked C++11 library features such as <code>std::to_string</code>. If you run into this, update to a current <abbr title="Native Development Kit">NDK</abbr>.</p> <h3 id=incomplete-detector-type-with-gcc-11>Incomplete <code>detector</code> type with <abbr title="GNU Compiler Collection">GCC</abbr> &lt; 11<a class=headerlink href=#incomplete-detector-type-with-gcc-11 title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Question</p> <p>Why does <abbr title="GNU Compiler Collection">GCC</abbr> 10 or older fail with <code>invalid use of incomplete type 'struct nlohmann::detail::detector&lt;..., to_json_function, ...&gt;'</code> for a type that holds an <code>optional</code> member?</p> </div> <p>This happens with <abbr title="GNU Compiler Collection">GCC</abbr> 10 and older in C++11/C++14 mode when all of these hold:</p> <ul> <li>a class <code>Holder</code> has an <code>optional&lt;Dummy&gt;</code> member (e.g., <code>boost::optiLine truncated
<span class=w> </span><span class=k>public</span><span class=o>:</span>
@@ -56,4 +56,4 @@
<span class=w> </span><span class=k>friend</span><span class=w> </span><span class=kt>void</span><span class=w> </span><span class=nf>to_json</span><span class=p>(</span><span class=n>nlohmann</span><span class=o>::</span><span class=n>json</span><span class=o>&amp;</span><span class=w> </span><span class=n>j</span><span class=p>,</span><span class=w> </span><span class=k>const</span><span class=w> </span><span class=n>Holder</span><span class=o>&amp;</span><span class=w> </span><span class=n>h</span><span class=p>)</span><span class=w> </span><span class=p>{</span><span class=w> </span><span class=cm>/* ... */</span><span class=w> </span><span class=p>}</span>
<span class=p>};</span>
</code></pre></div> <p>The <a href=../../api/macros/nlohmann_define_type_intrusive/ ><code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code></a> macros define hidden friends as well. See <a href="https://github.com/nlohmann/json/issues/3669">#3669</a> for details.</p> <h3 id=missing-stl-function>Missing <abbr title="Standard Template Library">STL</abbr> function<a class=headerlink href=#missing-stl-function title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Questions</p> <ul> <li>Why do I get a compilation error <code>'to_string' is not a member of 'std'</code> (or similarly, for <code>strtod</code> or <code>strtof</code>)?</li> <li>Why does the code not compile with MinGW or Android <abbr title="Software Development Kit">SDK</abbr>?</li> </ul> </div> <p>This is not an issue with the code, but rather with the compiler itself. On Android, use a current <abbr title="Native Development Kit">NDK</abbr> (see above). For MinGW, please refer to <a href="http://tehsausage.com/mingw-to-string">this site</a> and <a href="https://github.com/nlohmann/json/issues/136">this discussion</a> for information on how to fix this bug.</p> <!-- 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 05:18:07 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 &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, CLine truncated
</code></pre></div> <p>The <a href=../../api/macros/nlohmann_define_type_intrusive/ ><code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code></a> macros define hidden friends as well. See <a href="https://github.com/nlohmann/json/issues/3669">#3669</a> for details.</p> <h3 id=missing-stl-function>Missing <abbr title="Standard Template Library">STL</abbr> function<a class=headerlink href=#missing-stl-function title="Permanent link">&para;</a></h3> <div class="admonition question"> <p class=admonition-title>Questions</p> <ul> <li>Why do I get a compilation error <code>'to_string' is not a member of 'std'</code> (or similarly, for <code>strtod</code> or <code>strtof</code>)?</li> <li>Why does the code not compile with <abbr title="Minimalist GNU for Windows">MinGW</abbr> or Android <abbr title="Software Development Kit">SDK</abbr>?</li> </ul> </div> <p>This is not an issue with the code, but rather with the compiler itself. On Android, use a current <abbr title="Native Development Kit">NDK</abbr> (see above). For <abbr title="Minimalist GNU for Windows">MinGW</abbr>, please refer to <a href="http://tehsausage.com/mingw-to-string">this site</a> and <a href="https://github.com/nlohmann/json/issues/136">this discussion</a> for information on how to fix this bug.</p> <!-- 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 &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://fontaweLine truncated
+193 -1
View File
@@ -58,6 +58,174 @@ json j{obj}; // -> {"key":"value"} (copy, not array)
Without the macro (default behavior), `json j{obj}` creates `[{"key":"value"}]`. This opt-in macro fixes issue #5074 while preserving backwards compatibility for existing code.
## Getting started
### Which file do I need?
Question
Do I have to clone the repository or build the library?
No. The library is header-only: the single file [`json.hpp`](https://github.com/nlohmann/json/releases) from the releases page is all you need, including the `_json` literals. Put it in a directory `nlohmann` on your include path. Companion headers (`json_fwd.hpp`, `json_view.hpp`, `json_literals.hpp`) are only needed if you use them. See [Integration](https://json.nlohmann.me/integration/#header-only).
### Using CMake or a package manager
Question
How do I add the library with CMake, Conan, vcpkg, Homebrew, or another tool?
See [CMake](https://json.nlohmann.me/integration/cmake/index.md) for `find_package`, `add_subdirectory`, and `FetchContent`, and [Package managers](https://json.nlohmann.me/integration/package_managers/index.md) for the list of supported package managers.
### The IDE cannot open the header
Question
The compiler finds `nlohmann/json.hpp`, but my IDE reports "cannot open source file". Why?
The compiler's include path is set correctly, but the IDE's is not. Add the same directory to the include paths of the IDE (or of its language server); the build itself is not affected.
### Compile times
Question
Including the library slows down my build. What can I do?
Include [`json_fwd.hpp`](https://json.nlohmann.me/integration/compile_times/#include-json_fwdhpp-in-headers) in headers and `json.hpp` only in the source files that need it, instantiate `basic_json` once, and consider precompiled headers or [C++20 modules](https://json.nlohmann.me/features/modules/index.md). See [Compile times](https://json.nlohmann.me/integration/compile_times/index.md).
## Parsing
### Parsing a file fails with "unexpected end of input"
Question
`json::parse(file)` throws `parse_error.101` at line 1, column 1 for a file that is valid JSON. Why?
The parser did not see any character: the file was most likely not opened. A relative path is resolved against the working directory of the running program, which is often the build directory of your IDE, not the source directory. Check `is_open()` and try an absolute path. Other causes are an empty file and a stream that was already read. See [`parse_error.101`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error101).
### Input that arrives in chunks
Question
My data comes from a socket in pieces. How do I parse it?
The parser cannot be resumed. Frame the messages (one value per line, a length prefix) and parse each complete frame, or buffer the chunks until the value is complete; a `parse_error` at the end of the buffer means the input ended prematurely. See [Large, streamed, and partial input](https://json.nlohmann.me/features/parsing/large_and_partial_input/#input-arriving-in-chunks).
### Several values in one stream
Question
How do I read concatenated JSON values or one value per line?
Read newline-delimited input line by line ([JSON Lines](https://json.nlohmann.me/features/parsing/json_lines/index.md)). For concatenated values, use `operator>>` and check for the end of the stream before each read, as shown in [Several values in one stream](https://json.nlohmann.me/features/parsing/large_and_partial_input/#several-values-in-one-stream).
### Files that are too large for memory
Question
How do I process a huge JSON file?
Handle and discard the records of a large array with a [parser callback](https://json.nlohmann.me/features/parsing/parser_callbacks/index.md), stop early with the [SAX interface](https://json.nlohmann.me/features/parsing/sax_interface/index.md), or read parts of the text through a [`json_document`](https://json.nlohmann.me/features/json_view/index.md) (added in version 3.13.0 unreleased). See [Input too large for memory](https://json.nlohmann.me/features/parsing/large_and_partial_input/#input-too-large-for-memory).
### Position of a parse error
Question
How do I get the line and column of a parse error?
The message contains them. The exception stores the byte index in `byte`, from which you can compute both; see [Where did the error occur?](https://json.nlohmann.me/features/parsing/parse_exceptions/#where-did-the-error-occur). To locate a value that causes a *later* error, such as a `type_error`, use [`JSON_DIAGNOSTIC_POSITIONS`](https://json.nlohmann.me/features/parsing/parse_exceptions/#where-is-the-value-that-caused-a-later-error).
### Comments and trailing commas
Question
Can the parser read JSON with comments or trailing commas?
Yes, when asked to: see [Comments](https://json.nlohmann.me/features/comments/index.md) and [Trailing commas](https://json.nlohmann.me/features/trailing_commas/index.md). Both are rejected by default.
## Accessing and creating values
### Reading a value into a variable
Question
How do I get a C++ value out of a `json` value?
Use [`get<T>()`](https://json.nlohmann.me/api/basic_json/get/index.md), for example `int age = j["age"].get<int>();`, or an implicit conversion. `auto x = j["age"];` is **not** a conversion: it copies the `json` value. See [Converting values](https://json.nlohmann.me/features/conversions/index.md).
### Strings are printed with quotes
Question
`std::cout << j["name"]` prints `"Mary"` with quotes. How do I get the string?
The value is a `json`, and printing it produces JSON text. Convert it first: `j["name"].get<std::string>()`. See [Getting a string without quotes](https://json.nlohmann.me/features/conversions/#getting-values-out).
### Testing whether a key exists
Question
How do I check if a key exists, without changing the object?
Use `contains` or `find`. Do not test with the non-const `operator[]`: like `std::map::operator[]`, it inserts a `null` value for a missing key. See [Does this key exist?](https://json.nlohmann.me/features/element_access/#does-this-key-exist).
### Reading a value with a fallback
Question
How do I read a value that may be missing?
Use [`value`](https://json.nlohmann.me/features/element_access/default_value/index.md), which returns a default for a missing key. It still throws if the key exists with a different type; see [Working without exceptions](https://json.nlohmann.me/features/no_exceptions/index.md).
### Iterating and nested values
Question
How do I loop over an array or object, or reach a nested value?
See [Iterators](https://json.nlohmann.me/features/iterators/index.md) and [`items()`](https://json.nlohmann.me/api/basic_json/items/index.md) for loops, and [JSON Pointer](https://json.nlohmann.me/features/json_pointer/index.md) to address or test a nested value by path.
### Unexpected arrays when creating values
Question
Why does `json j{x}` or `{{"a", 1}, {"b"}}` produce an array instead of what I expected?
Braces create arrays and objects based on their content, and single-element braces create a one-element array. See [Brace initialization yields arrays](#brace-initialization-yields-arrays) and the table in [Creating values](https://json.nlohmann.me/features/creating_values/#what-does-this-produce).
### Keeping the order of object keys
Question
The keys of my object come out sorted. How do I keep the insertion order?
Use `ordered_json`, and call `ordered_json::parse` when reading. See [Object order](https://json.nlohmann.me/features/object_order/index.md).
## Converting your own types
### Structs, enums, and optional fields
Question
How do I convert my own types to and from JSON?
Write `to_json`/`from_json` functions or use the `NLOHMANN_DEFINE_TYPE_*` macros; see [Arbitrary type conversions](https://json.nlohmann.me/features/arbitrary_types/index.md). Enums can be mapped to strings ([Enum conversion](https://json.nlohmann.me/features/enum_conversion/index.md)), and an empty `std::optional` can be omitted ([Omitting a field](https://json.nlohmann.me/features/conversions/#omitting-a-field-when-serializing-stdoptional)).
### Smart pointers, variants, chrono, and class hierarchies
Question
Why can't I convert `std::shared_ptr`, `std::variant`, `std::chrono` types, or a pointer to a base class?
There is more than one sensible JSON representation for them, so the library leaves the choice to you. [Recipes for common types](https://json.nlohmann.me/features/type_recipes/index.md) shows one for each.
### My `to_json` is not found
Question
I wrote `to_json`/`from_json`, but the compiler does not find them. Why?
Typical causes are a type alias of a standard type, a function in the wrong namespace, or a declaration that comes too late. See [Why isn't my `to_json` found?](https://json.nlohmann.me/features/arbitrary_types/#why-isnt-my-to_json-or-from_json-found).
## Limitations
### Relaxed parsing
@@ -194,6 +362,30 @@ Does this library support JSON Schema validation?
Not directly, but the companion project [json-schema-validator](https://github.com/pboettch/json-schema-validator) builds JSON Schema (draft 7; draft 4 in its older, now-superseded 1.x releases) validation on top of this library and is a common recommendation for this use case.
### Memory use
Question
Does the library leak memory? My process stays large after I free a `json` value.
Destroying a value frees everything it owns. Freed memory is returned to the allocator, which does not necessarily give it back to the operating system, so a high resident size alone is not a leak. Copies are deep, and `clear()` keeps the capacity of an array. See [Memory](https://json.nlohmann.me/features/performance/#memory), and use Valgrind or the sanitizers to tell a leak from retained memory.
### Reproducible builds
Question
The header path ends up in my binary. How do I get path-independent builds?
The runtime assertions embed `__FILE__`. Define `NDEBUG` (the default for release builds) or map the path prefix; see [Notes for builds and distribution](https://json.nlohmann.me/integration/#notes-for-builds-and-distribution).
### Slow debug builds
Question
Parsing a large file is very slow in my debug build. Can I compile the library with optimizations?
The library is header-only, so there is no separate source file. Keep the code that uses `json` in its own source file and compile that file with optimizations; see [Notes for builds and distribution](https://json.nlohmann.me/integration/#notes-for-builds-and-distribution).
## Exceptions
### Parsing without exceptions
@@ -202,7 +394,7 @@ Question
Is it possible to indicate a parse error without throwing an exception?
Yes, see [Parsing and exceptions](https://json.nlohmann.me/features/parsing/parse_exceptions/index.md).
Yes, see [Parsing and exceptions](https://json.nlohmann.me/features/parsing/parse_exceptions/index.md) and [Working without exceptions](https://json.nlohmann.me/features/no_exceptions/index.md).
### Key name in exceptions