Files
simdjson-simdjson/md_doc_basics.html
T
2023-09-20 15:16:39 +00:00

1536 lines
153 KiB
HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>simdjson: The Basics</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="doxygen-awesome.css" rel="stylesheet" type="text/css"/>
<link href="doxygen-awesome-sidebar-only.css" rel="stylesheet" type="text/css"/>
<link href="doxygen-awesome-sidebar-only-darkmode-toggle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logotiny.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">simdjson
&#160;<span id="projectnumber">3.3.0</span>
</div>
<div id="projectbrief">Ridiculously Fast JSON</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('md_doc_basics.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="PageDoc"><div class="header">
<div class="headertitle">
<div class="title">The Basics </div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>An overview of what you need to know to use simdjson, with examples.</p>
<ul>
<li><a href="#the-basics">The Basics</a><ul>
<li><a href="#requirements">Requirements</a></li>
<li><a href="#including-simdjson">Including simdjson</a></li>
<li><a href="#using-simdjson-with-package-managers">Using simdjson with package managers</a></li>
<li><a href="#using-simdjson-as-a-cmake-dependency">Using simdjson as a CMake dependency</a></li>
<li><a href="#versions">Versions</a></li>
<li><a href="#the-basics-loading-and-parsing-json-documents">The Basics: Loading and Parsing JSON Documents</a></li>
<li><a href="#documents-are-iterators">Documents are Iterators</a><ul>
<li><a href="#parser-document-and-json-scope">Parser, Document and JSON Scope</a></li>
</ul>
</li>
<li><a href="#string_view">string_view</a></li>
<li><a href="#using-the-parsed-json">Using the Parsed JSON</a><ul>
<li><a href="#using-the-parsed-json-additional-examples">Using the Parsed JSON: Additional examples</a></li>
</ul>
</li>
<li><a href="#minifying-json-strings-without-parsing">Minifying JSON strings without parsing</a></li>
<li><a href="#utf-8-validation-alone">UTF-8 validation (alone)</a></li>
<li><a href="#json-pointer">JSON Pointer</a></li>
<li><a href="#error-handling">Error Handling</a><ul>
<li><a href="#error-handling-examples-without-exceptions">Error Handling Examples without Exceptions</a></li>
<li><a href="#disabling-exceptions">Disabling Exceptions</a></li>
<li><a href="#exceptions">Exceptions</a></li>
<li><a href="#current-location-in-document">Current location in document</a></li>
<li><a href="#checking-for-trailing-content">Checking for trailing content</a></li>
</ul>
</li>
<li><a href="#rewinding">Rewinding</a></li>
<li><a href="#newline-delimited-json-ndjson-and-json-lines">Newline-Delimited JSON (ndjson) and JSON lines</a></li>
<li><a href="#parsing-numbers-inside-strings">Parsing Numbers Inside Strings</a></li>
<li><a href="#dynamic-number-types">Dynamic Number Types</a></li>
<li><a href="#raw-strings">Raw Strings</a></li>
<li><a href="#general-direct-access-to-the-raw-json-string">General Direct Access to the Raw JSON String</a></li>
<li><a href="#thread-safety">Thread Safety</a></li>
<li><a href="#standard-compliance">Standard Compliance</a></li>
<li><a href="#backwards-compatibility">Backwards Compatibility</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#performance-tips">Performance Tips</a></li>
</ul>
</li>
</ul>
<h1><a class="anchor" id="autotoc_md0"></a>
Requirements</h1>
<ul>
<li>A recent compiler (LLVM clang 6 or better, GNU GCC 7.4 or better, Xcode 11 or better) on a 64-bit (PPC, ARM or x64 Intel/AMD) POSIX systems such as macOS, freeBSD or Linux. We require that the compiler supports the C++11 standard or better.</li>
<li>Visual Studio 2017 or better under 64-bit Windows. Users should target a 64-bit build (x64 or ARM64) instead of a 32-bit build (x86). We support the LLVM clang compiler under Visual Studio (clangcl) as well as as the regular Visual Studio compiler. We also support MinGW 64-bit under Windows.</li>
</ul>
<p>Support for AVX-512 require a processor with AVX512-VBMI2 support (Ice Lake or better, AMD Zen 4 or better) under a 64-bit system and a recent compiler (LLVM clang 6 or better, GCC 8 or better, Visual Studio 2019 or better). You need a correspondingly recent assembler such as gas (2.30+) or nasm (2.14+): recent compilers usually come with recent assemblers. If you mix a recent compiler with an incompatible/old assembler (e.g., when using a recent compiler with an old Linux distribution), you may get errors at build time because the compiler produces instructions that the assembler does not recognize: you should update your assembler to match your compiler (e.g., upgrade binutils to version 2.30 or better under Linux) or use an older compiler matching the capabilities of your assembler.</p>
<p>We test the library on a big-endian system (IBM s390x with Linux) .</p>
<h1><a class="anchor" id="autotoc_md1"></a>
Including simdjson</h1>
<p>To include simdjson, copy <a href="/singleheader/simdjson.h">simdjson.h</a> and <a href="/singleheader/simdjson.cpp">simdjson.cpp</a> into your project. Then include it in your project with:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">#include &quot;simdjson.h&quot;</div>
<div class="line">using namespace simdjson; // optional</div>
</div><!-- fragment --><p>You can compile with:</p>
<div class="fragment"><div class="line">c++ myproject.cpp simdjson.cpp</div>
</div><!-- fragment --><p>Note:</p><ul>
<li>Users on macOS and other platforms where default compilers do not provide C++11 compliant by default should request it with the appropriate flag (e.g., <code>c++ -std=c++11 myproject.cpp simdjson.cpp</code>).</li>
<li>The library relies on <a class="el" href="md_doc_implementation_selection.html">runtime CPU detection</a>: avoid specifying an architecture at compile time (e.g., <code>-march-native</code>).</li>
</ul>
<h1><a class="anchor" id="autotoc_md2"></a>
Using simdjson with package managers</h1>
<p>You can install the simdjson library on your system or in your project using multiple package managers such as MSYS2, the conan package manager, vcpkg, brew, the apt package manager (debian-based Linux systems), the FreeBSD package manager (FreeBSD), and so on. <a href="https://github.com/simdjson/simdjson/wiki/Installing-simdjson-with-a-package-manager">Visit our wiki for more details</a>.</p>
<h1><a class="anchor" id="autotoc_md3"></a>
Using simdjson as a CMake dependency</h1>
<p>You can include the simdjson library as a CMake dependency by including the following lines in your <code>CMakeLists.txt</code>:</p>
<div class="fragment"><div class="line">include(FetchContent)</div>
<div class="line"> </div>
<div class="line">FetchContent_Declare(</div>
<div class="line"> simdjson</div>
<div class="line"> GIT_REPOSITORY https://github.com/simdjson/simdjson.git</div>
<div class="line"> GIT_TAG tags/v0.9.6</div>
<div class="line"> GIT_SHALLOW TRUE)</div>
<div class="line"> </div>
<div class="line">FetchContent_MakeAvailable(simdjson)</div>
</div><!-- fragment --><p>You should provide <code>GIT_TAG</code> with the release you need. If you omit <code>GIT_TAG ...</code>, you will work from the main branch of simdjson: we recommend that if you are working on production code, you always work from a release.</p>
<p>Elsewhere in your project, you can declare dependencies on simdjson with lines such as these:</p>
<div class="fragment"><div class="line">add_executable(myprogram myprogram.cpp)</div>
<div class="line">target_link_libraries(myprogram simdjson)</div>
</div><!-- fragment --><p>We recommend CMake version 3.15 or better.</p>
<p>See <a href="https://github.com/simdjson/cmake_demo_single_file">our CMake demonstration</a>. It works under Linux, FreeBSD, macOS and Windows (including Visual Studio).</p>
<p>The CMake build in simdjson can be tailored with a few variables. You can see the available variables and their default values by entering the <code>cmake -LA</code> command.</p>
<h1><a class="anchor" id="autotoc_md4"></a>
Versions</h1>
<p>Users are discouraged from building production code from the project's main branch. The main branch is used for development: it may contain new features but also additional bugs.</p>
<p>Users should pick a release. They should also access the documentation matching the release that they have chosen. Note that new features may be added over time.</p>
<p>Our releases are tagged using semantic versioning: the tags are made of three numbers prefixed by the letter <code>v</code> and separated by periods.</p>
<p>You can always find the latest release at the following hyperlink:</p>
<p><a href="https://github.com/simdjson/simdjson/releases/latest/">https://github.com/simdjson/simdjson/releases/latest/</a></p>
<p>The archive you download at this location contains its own corresponding documentation.</p>
<p>You can also choose to browse a specific version of the documentation and the code using GitHub, by appending the version number to the hyperlink, like so:</p>
<p><a href="https://github.com/simdjson/simdjson/blob/vx.y.z/doc/basics.md">https://github.com/simdjson/simdjson/blob/vx.y.z/doc/basics.md</a></p>
<p>where <code>x.y.z</code> should correspond to the version number you have chosen.</p>
<h1><a class="anchor" id="autotoc_md5"></a>
The Basics: Loading and Parsing JSON Documents</h1>
<p>The simdjson library allows you to navigate and validate JSON documents (<a href="https://www.tbray.org/ongoing/When/201x/2017/12/14/rfc8259.html">RFC 8259</a>). As required by the standard, your JSON document should be in a Unicode (UTF-8) string. The whole string, from the beginning to the end, needs to be valid: we do not attempt to tolerate bad inputs before or after a document.</p>
<p>For efficiency reasons, simdjson requires a string with a few bytes (<code><a class="el" href="namespacesimdjson.html#aecdd750132f0eb123a6d61113b4197bf" title="The amount of padding needed in a buffer to parse JSON.">simdjson::SIMDJSON_PADDING</a></code>) at the end, these bytes may be read but their content does not affect the parsing. In practice, it means that the JSON inputs should be stored in a memory region with <code><a class="el" href="namespacesimdjson.html#aecdd750132f0eb123a6d61113b4197bf" title="The amount of padding needed in a buffer to parse JSON.">simdjson::SIMDJSON_PADDING</a></code> extra bytes at the end. You do not have to set these bytes to specific values though you may want to if you want to avoid runtime warnings with some sanitizers.</p>
<p>The simdjson library offers a tree-like <a href="https://en.wikipedia.org/wiki/API">API</a>, which you can access by creating a <code>ondemand::parser</code> and calling the <code>iterate()</code> method. The iterate method quickly indexes the input string and may detect some errors. The following example illustrates how to get started with an input JSON file (<code>"twitter.json"</code>):</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto json = padded_string::load(&quot;twitter.json&quot;); // load JSON file &#39;twitter.json&#39;.</div>
<div class="line">ondemand::document doc = parser.iterate(json); // position a pointer at the beginning of the JSON data</div>
</div><!-- fragment --><p>You can also create a padded string&mdash;and call <code>iterate()</code>:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto json = &quot;[1,2,3]&quot;_padded; // The _padded suffix creates a simdjson::padded_string instance</div>
<div class="line">ondemand::document doc = parser.iterate(json); // parse a string</div>
</div><!-- fragment --><p>If you have a buffer of your own with enough padding already (SIMDJSON_PADDING extra bytes allocated), you can use <code>padded_string_view</code> to pass it in:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">char json[3+SIMDJSON_PADDING];</div>
<div class="line">strcpy(json, &quot;[1]&quot;);</div>
<div class="line">ondemand::document doc = parser.iterate(json, strlen(json), sizeof(json));</div>
</div><!-- fragment --><p>The simdjson library will also accept <code>std::string</code> instances, as long as the <code>capacity()</code> of the string exceeds the <code>size()</code> by at least <code>SIMDJSON_PADDING</code>. You can increase the <code>capacity()</code> with the <code>reserve()</code> function of your strings.</p>
<p>You can copy your data directly on a <code><a class="el" href="structsimdjson_1_1padded__string.html" title="String with extra allocation for ease of use with parser::parse()">simdjson::padded_string</a></code> as follows:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">const char * data = &quot;my data&quot;; // 7 bytes</div>
<div class="line">simdjson::padded_string my_padded_data(data, 7); // copies to a padded buffer</div>
</div><!-- fragment --><p>Or as follows...</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">std::string data = &quot;my data&quot;;</div>
<div class="line">simdjson::padded_string my_padded_data(data); // copies to a padded buffer</div>
</div><!-- fragment --><p>We recommend against creating many <code>std::string</code> or many <code>std::padding_string</code> instances in your application to store your JSON data. Consider reusing the same buffers and limiting memory allocations.</p>
<p>By default, the simdjson library throws exceptions (<code>simdjson_error</code>) on errors. We omit <code>try</code>-<code>catch</code> clauses from our illustrating examples: if you omit <code>try</code>-<code>catch</code> in your code, an uncaught exception will halt your program. It is also possible to use simdjson without generating exceptions, and you may even build the library without exception support at all. See <a href="#error-handling">Error Handling</a> for details.</p>
<p>Some users may want to browse code along with the compiled assembly. You want to check out the following lists of examples:</p>
<ul>
<li><a href="https://godbolt.org/z/98Kx9Kqjn">simdjson examples with errors handled through exceptions</a></li>
<li><a href="https://godbolt.org/z/PKG7GdbPo">simdjson examples with errors without exceptions</a></li>
</ul>
<h1><a class="anchor" id="autotoc_md6"></a>
Documents are Iterators</h1>
<p>The simdjson library relies on an approach to parsing JSON that we call "On Demand". A <code>document</code> is <em>not</em> a fully-parsed JSON value; rather, it is an <b>iterator</b> over the JSON text. This means that while you iterate an array, or search for a field in an object, it is actually walking through the original JSON text, merrily reading commas and colons and brackets to make sure you get where you are going. This is the key to On Demand's performance: since it's just an iterator, it lets you parse values as you use them. And particularly, it lets you <em>skip</em> values you do not want to use.</p>
<p>We refer to "On Demand" as a front-end component since it is an interface between the low-level parsing functions and the user. It hides much of the complexity of parsing JSON documents.</p>
<h2><a class="anchor" id="autotoc_md7"></a>
Parser, Document and JSON Scope</h2>
<p>For code safety, you should keep (1) the <code>parser</code> instance, (2) the input string and (3) the document instance alive throughout your parsing. Additionally, you should follow the following rules:</p>
<ul>
<li>A <code>parser</code> may have at most one document open at a time, since it holds allocated memory used for the parsing.</li>
<li>By design, you should only have one <code>document</code> instance per JSON document. Thus, if you must pass a document instance to a function, you should avoid passing it by value: choose to pass it by reference instance to avoid the copy. (We also provide a <code>document_reference</code> class if you need to pass by value.)</li>
</ul>
<p>During the <code>iterate</code> call, the original JSON text is never modified&ndash;only read. After you are done with the document, the source (whether file or string) can be safely discarded.</p>
<p>For best performance, a <code>parser</code> instance should be reused over several files: otherwise you will needlessly reallocate memory, an expensive process. It is also possible to avoid entirely memory allocations during parsing when using simdjson. <a class="el" href="md_doc_performance.html">See our performance notes for details</a>.</p>
<p>If you need to have several documents active at once, you should have several parser instances.</p>
<h1><a class="anchor" id="autotoc_md8"></a>
string_view</h1>
<p>The simdjson library builds on compilers supporting the <a href="https://en.wikipedia.org/wiki/C%2B%2B11">C++11 standard</a>. It is also a strict requirement: we have no plan to support older C++ compilers.</p>
<p>We represent parsed Unicode (UTF-8) strings in simdjson using the <code>std::string_view</code> class. It avoids the need to copy the data, as would be necessary with the <code>std::string</code> class. It also avoids the pitfalls of null-terminated C strings. It makes it easier for our users to copy the data into their own favorite class instances (e.g., alternatives to <code>std::string</code>).</p>
<p>A <code>std::string_view</code> instance is effectively just a pointer to a region in memory representing a string. In simdjson, we return <code>std::string_view</code> instances that either point within the input string you parsed, or to a temporary string buffer inside our parser class instances. When using <code>std::string_view</code> instances, it is your responsibility to ensure that <code>std::string_view</code> instance does not outlive the pointed-to memory (e.g., either the input buffer or the parser instance). Furthermore, some operations reset the string buffer inside our parser instances: e.g., when we parse a new document. Thus a <code>std::string_view</code> instance is often best viewed as a temporary string value that is tied to the document you are parsing. At the cost of some memory allocation, you may convert your <code>std::string_view</code> instances for long-term storage into <code>std::string</code> instances: <code>std::string mycopy(view)</code> (C++17) or <code>std::string mycopy(view.begin(), view.end())</code> (prior to C++17).</p>
<p>The <code>std::string_view</code> class has become standard as part of C++17 but it is not always available on compilers which only supports C++11. When we detect that <code>string_view</code> is natively available, we define the macro <code>SIMDJSON_HAS_STRING_VIEW</code>.</p>
<p>When we detect that it is unavailable, we use <a href="https://github.com/martinmoene/string-view-lite">string-view-lite</a> as a substitute. In such cases, we use the type alias <code>using string_view = nonstd::string_view;</code> to offer the same API, irrespective of the compiler and standard library. The macro <code>SIMDJSON_HAS_STRING_VIEW</code> will be <em>undefined</em> to indicate that we emulate <code>string_view</code>.</p>
<p>Some users prefer to use non-JSON native encoding formats such as UTF-16 or UTF-32. Users may transcode the UTF-8 strings produced by the simdjson library to other formats. See the <a href="https://github.com/simdutf/simdutf">simdutf library</a>, for example.</p>
<h1><a class="anchor" id="autotoc_md9"></a>
Using the Parsed JSON</h1>
<p>We recommend that you first compile and run your code in Debug mode: under Visual Studio, it means having the <code>_DEBUG</code> macro defined, and, for other compilers, it means leaving the <code>__OPTIMIZE__</code> macro undefined. The simdjson code will set <code>SIMDJSON_DEVELOPMENT_CHECKS=1</code>. Alternatively, you can set the macro <code>SIMDJSON_DEVELOPMENT_CHECKS</code> to 1 prior to including the <code><a class="el" href="simdjson_8h.html">simdjson.h</a></code> header to enable these additional checks: just make sure you remove the definition once your code has been tested. When <code>SIMDJSON_DEVELOPMENT_CHECKS</code> is set to 1, the simdjson library runs additional (expensive) tests on your code to help ensure that you are using the library in a safe manner. Once your code has been tested, you can then run it in Release mode: under Visual Studio, it means having the <code>_DEBUG</code> macro undefined, and, for other compilers, it means setting <code>__OPTIMIZE__</code> to a positive integer. You can also forcefully disable these checks by setting <code>SIMDJSON_DEVELOPMENT_CHECKS</code> to 0. Once your code is tested, we further encourage you to define <code>NDEBUG</code> in your Release builds to disable additional runtime testing and get the best performance.</p>
<p>Once you have a document (<code>simdjson::ondemand::document</code>), you can navigate it with idiomatic C++ iterators, operators and casts. Besides the document instances and native types (<code>double</code>, <code>uint64_t</code>, <code>int64_t</code>, <code>bool</code>), we also access Unicode (UTF-8) strings (<code>std::string_view</code>), objects (<code>simdjson::ondemand::object</code>) and arrays (<code>simdjson::ondemand::array</code>). We also have a generic ephemeral type (<code>simdjson::ondemand::value</code>) which represents a potential array or object, or scalar type (<code>double</code>, <code>uint64_t</code>, <code>int64_t</code>, <code>bool</code>, <code>null</code>, string) inside an array or an object. Both generic types (<code>simdjson::ondemand::document</code> and <code>simdjson::ondemand::value</code>) have a <code>type()</code> method returning a <code>json_type</code> value describing the value (<code>json_type::array</code>, <code>json_type::object</code>, <code>json_type::number</code>, <code>json_type::string</code>, <code>json_type::boolean</code>, <code>json_type::null</code>). A generic value (<code>simdjson::ondemand::value</code>) is only valid temporarily, as soon as you access other values, other keys in objects, etc. it becomes invalid: you should therefore consume the value immediately by converting it to a scalar type, an array or an object.</p>
<p>Advanced users who need to determine the number types (integer or float) dynamically, should review our section <a href="#dynamic-number-types">dynamic number types</a>. Indeed, we have an additional <code>ondemand::number</code> type which may represent either integers or floating-point values, depending on how the numbers are formatted. floating-point values followed by an integer.</p>
<p>We invite you to keep the following rules in mind:</p><ol type="1">
<li>While you are accessing the document, the <code>document</code> instance should remain in scope: it is your "iterator" which keeps track of where you are in the JSON document. By design, there is one and only one <code>document</code> instance per JSON document.</li>
<li>Because On Demand is really just an iterator, you must fully consume the current object or array before accessing a sibling object or array.</li>
<li>Values can only be consumed once, you should get the values and store them if you plan to need them multiple times. You are expected to access the keys of an object just once. You are expected to go through the values of an array just once.</li>
</ol>
<p>The simdjson library makes generous use of <code>std::string_view</code> instances. If you are unfamiliar with <code>std::string_view</code> in C++, make sure to <a href="#string_view">read the section on std::string_view</a>. They behave much like an immutable <code>std::string</code> but they require no memory allocation. You can create a <code>std::string</code> instance from an <code>std::string_view</code> when you need it.</p>
<p>The following specific instructions indicate how to use the JSON when exceptions are enabled, but simdjson has full, idiomatic support for users who avoid exceptions. See <a href="basics.md#error-handling">the simdjson error handling documentation</a> for more.</p>
<ul>
<li><b>Validate What You Use:</b> When calling <code>iterate</code>, the document is quickly indexed. If it is not a valid Unicode (UTF-8) string or if there is an unclosed string, an error may be reported right away. However, it is not fully validated. On Demand only fully validates the values you use and the structure leading to it. It means that at every step as you traverse the document, you may encounter an error. You can handle errors either with exceptions or with error codes.</li>
<li><b>Extracting Values:</b> You can cast a JSON element to a native type: <code>double(element)</code>. This works for <code>std::string_view</code>, double, uint64_t, int64_t, bool, ondemand::object and ondemand::array. We also have explicit methods such as <code>get_string()</code>, <code>get_double()</code>, <code>get_uint64()</code>, <code>get_int64()</code>, <code>get_bool()</code>, <code>get_object()</code> and <code>get_array()</code>. After a cast or an explicit method, the number, string or boolean will be parsed, or the initial <code>{</code> or <code>[</code> will be verified for <code>ondemand::object</code> and <code>ondemand::array</code>. An exception may be thrown if the cast is not possible: there error code is <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9a1de02af1d67e8350f612eee0dcf634b4" title="JSON element has a different type than user expected.">simdjson::INCORRECT_TYPE</a></code> (see <a href="#error-handling">Error Handling</a>). Importantly, when getting an ondemand::object or ondemand::array instance, its content is not validated: you are only guaranteed that the corresponding initial character (<code>{</code> or <code>[</code>) is present. Thus, for example, you could have an ondemand::object instance pointing at the invalid JSON <code>{ "this is not a valid object" }</code>: the validation occurs as you access the content. The <code>get_string()</code> returns a valid UTF-8 string, after unescaping characters as needed: unmatched surrogate pairs are treated as an error unless you pass <code>true</code> (<code>get_string(true)</code>) as a parameter to get replacement characters where errors occur. If you somehow need to access non-UTF-8 strings in a lossless manner (e.g., if you strings contain unpaired surrogates), you may use the <code>get_wobbly_string()</code> function to get a string in the <a href="https://simonsapin.github.io/wtf-8">WTF-8 format</a>. When calling <code>get_uint64()</code> and <code>get_int64()</code>, if the number does not fit in a corresponding 64-bit integer type, it is also considered an error. When parsing numbers or other scalar values, the library checks that the value is followed by an expected character, thus you <em>may</em> get a number parsing error when accessing the digits as an integer in the following strings: <code>{"number":12332a</code>, <code>{"number":12332\0</code>, <code>{"number":12332</code> (the digits appear at the end). We always abide by the <a href="https://www.tbray.org/ongoing/When/201x/2017/12/14/rfc8259.html">RFC 8259</a> JSON specification so that, for example, numbers prefixed by the <code>+</code> sign are in error.</li>
</ul>
<blockquote class="doxtable">
<p>IMPORTANT NOTE: values can only be parsed once. Since documents are <em>iterators</em>, once you have parsed a value (such as by casting to double), you cannot get at it again. It is an error to call <code>get_string()</code> twice on an object (or to cast an object twice to <code>std::string_view</code>). </p>
</blockquote>
<p>* <b>Field Access:</b> To get the value of the "foo" field in an object, use <code>object["foo"]</code>. This will scan through the object looking for the field with the matching string, doing a character-by-character comparison. It may generate the error <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9a4a2c71f8eca438b3f0553a2811bdab9a" title="JSON field not found in object.">simdjson::NO_SUCH_FIELD</a></code> if there is no such key in the object, it may throw an exception (see <a href="#error-handling">Error Handling</a>). For efficiency reason, you should avoid looking up the same field repeatedly: e.g., do not do <code>object["foo"]</code> followed by <code>object["foo"]</code> with the same <code>object</code> instance. Keep in mind that On Demand does not buffer or save the result of the parsing: if you repeatedly access <code>object["foo"]</code>, then it must repeatedly seek the key and parse the content. The library does not provide a distinct function to check if a key is present, instead we recommend you attempt to access the key: e.g., by doing <code>ondemand::value val{}; if (!object["foo"].get(val)) {...}</code>, you have that <code>val</code> contains the requested value inside the if clause. It is your responsibility as a user to temporarily keep a reference to the value (<code>auto v = object["foo"]</code>), or to consume the content and store it in your own data structures. If you consume an object twice: <code>std::string_view(object["foo"]</code> followed by <code>std::string_view(object["foo"]</code> then your code is in error. Furthermore, you can only consume one field at a time, on the same object. The value instance you get from <code>content["bids"]</code> becomes invalid when you call <code>content["asks"]</code>. If you have retrieved <code>content["bids"].get_array()</code> and you later call <code>content["asks"].get_array()</code>, then the first array should no longer be accessed: it would be unsafe to do so. You can detect such mistakes by first compiling and running the code in Debug mode: an OUT_OF_ORDER_ITERATION error is generated.</p>
<blockquote class="doxtable">
<p>NOTE: JSON allows you to escape characters in keys. E.g., the key <code>"date"</code> may be written as <code>"\u0064\u0061\u0074\u0065"</code>. By default, simdjson does <em>not</em> unescape keys when matching by default. Thus if you search for the key <code>"date"</code> and the JSON document uses <code>"\u0064\u0061\u0074\u0065"</code> as a key, it will not be recognized. This is not generally a problem. Nevertheless, if you do need to support escaped keys, the method <code>unescaped_key()</code> provides the desired unescaped keys by parsing and writing out the unescaped keys to a string buffer and returning a <code>std::string_view</code> instance. The <code>unescaped_key</code> takes an optional Boolean value: passing it true will decode invalid Unicode sequences with replacement, meaning that the decoding always succeeds but bogus Unicode replacement characters are inserted. In general, you should expect a performance penalty when using <code>unescaped_key()</code> compared to <code>key()</code> because of the string processing: the <code>key()</code> function just points inside the source JSON document.</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json = R&quot;({&quot;k\u0065y&quot;: 1})&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">ondemand::object object = doc.get_object();</div>
<div class="line">for(auto field : object) {</div>
<div class="line"> // parses and writes out the key, after unescaping it,</div>
<div class="line"> // to a string buffer. It causes a performance penalty.</div>
<div class="line"> std::string_view keyv = field.unescaped_key();</div>
<div class="line"> if (keyv == &quot;key&quot;) { std::cout &lt;&lt; uint64_t(field.value()); }</div>
<div class="line"> }</div>
</div><!-- fragment --><p>By default, field lookup is order-insensitive, so you can look up values in any order. However, we still encourage you to look up fields in the order you expect them in the JSON, as it is still faster.</p>
<p>If you want to enforce finding fields in order, you can use <code>object.find_field("foo")</code> instead. This will only look forward, and will fail to find fields in the wrong order: for example, this will fail:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto json = R&quot;( { &quot;x&quot;: 1, &quot;y&quot;: 2 } )&quot;_padded;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">double y = doc.find_field(&quot;y&quot;); // The cursor is now after the 2 (at })</div>
<div class="line">double x = doc.find_field(&quot;x&quot;); // This fails, because there are no more fields after &quot;y&quot;</div>
</div><!-- fragment --><p>By contrast, using the default (order-insensitive) lookup succeeds:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto json = R&quot;( { &quot;x&quot;: 1, &quot;y&quot;: 2 } )&quot;_padded;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">double y = doc[&quot;y&quot;]; // The cursor is now after the 2 (at })</div>
<div class="line">double x = doc[&quot;x&quot;]; // Success: [] loops back around to find &quot;x&quot;</div>
</div><!-- fragment --> </blockquote>
<p>* <b>Array Iteration:</b> To iterate through an array, use <code>for (auto value : array) { ... }</code>. This will step through each value in the JSON array.</p>
<p>If you know the type of the value, you can cast it right there, too! <code>for (double value : array) { ... }</code>.</p>
<p>You may also use explicit iterators: <code>for(auto i = array.begin(); i != array.end(); i++) {}</code>. You can check that an array is empty with the condition <code>auto i = array.begin(); if(i == array.end()) {...}</code>.</p><ul>
<li><b>Object Iteration:</b> You can iterate through an object's fields, as well: <code>for (auto field : object) { ... }</code>. You may also use explicit iterators : <code>for(auto i = object.begin(); i != object.end(); i++) { auto field = *i; .... }</code>. You can check that an object is empty with the condition <code>auto i = object.begin(); if(i == object.end()) {...}</code>.<ul>
<li><code>field.unescaped_key()</code> will get you the unescaped key string. E.g., the JSON string <code>"\u00e1"</code> becomes the Unicode string <code>á</code>. Optionally, you pass <code>true</code> as a parameter to the <code>unescaped_key</code> method if you want invalid escape sequences to be replaced by a default replacement character (e.g., <code>\ud800\ud801\ud811</code>): otherwise bad escape sequences lead to an immediate error.</li>
<li><code>field.value()</code> will get you the value, which you can then use all these other methods on.</li>
</ul>
</li>
<li><b>Array Index:</b> Because it is forward-only, you cannot look up an array element by index by index. Instead, you should iterate through the array and keep an index yourself.</li>
<li><b>Output to strings:</b> Given a document, a value, an array or an object in a JSON document, you can output a JSON string version suitable to be parsed again as JSON content: <code>simdjson::to_json_string(element)</code>. A call to <code>to_json_string</code> consumes fully the element: if you apply it on a document, the JSON pointer is advanced to the end of the document. The <code><a class="el" href="namespacesimdjson.html#a2cda17221b852e5c398bad5bf350d270" title="Create a string-view instance out of a document instance.">simdjson::to_json_string</a></code> does not allocate memory. The <code>to_json_string</code> function should not be confused with retrieving the value of a string instance which are escaped and represented using a lightweight <code>std::string_view</code> instance pointing at an internal string buffer inside the parser instance. To illustrate, the first of the following two code segments will print the unescaped string <code>"test"</code> complete with the quote whereas the second one will print the escaped content of the string (without the quotes). <blockquote class="doxtable">
<p>```C++ // serialize a JSON to an escaped std::string instance so that it can be parsed again as JSON auto silly_json = R"( { "test": "result" } )"_padded; ondemand::document doc = parser.iterate(silly_json); std::cout &lt;&lt; <a class="el" href="namespacesimdjson.html#a2cda17221b852e5c398bad5bf350d270" title="Create a string-view instance out of a document instance.">simdjson::to_json_string</a>(doc["test"]) &lt;&lt; std::endl; // Requires simdjson 1.0 or better &gt;`<code> </code>C++ // retrieves an unescaped string value as a string_view instance auto silly_json = R"( { "test": "result" } )"_padded; ondemand::document doc = parser.iterate(silly_json); std::cout &lt;&lt; std::string_view(doc["test"]) &lt;&lt; std::endl; &gt;```<code> &lt;/blockquote&gt; You can use</code>to_json_string<code>to efficiently extract components of a JSON document to reconstruct a new JSON document, as in the following example: &lt;blockquote&gt;</code>``C++ auto cars_json = R"( [
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
] )"_padded; std::vector&lt;std::string_view&gt; arrays; // We are going to collect string_view instances which point inside the <code>cars_json</code> string // and are therefore valid as long as <code>cars_json</code> remains in scope. { ondemand::parser parser; for (ondemand::object car : parser.iterate(cars_json)) { if (uint64_t(car["year"]) &gt; 2000) { arrays.push_back(<a class="el" href="namespacesimdjson.html#a2cda17221b852e5c398bad5bf350d270" title="Create a string-view instance out of a document instance.">simdjson::to_json_string</a>(car["tire_pressure"])); } } } // We can now convert to a JSON string: std::ostringstream oss; oss &lt;&lt; "["; for(size_t i = 0; i &lt; arrays.size(); i++) { if (i&gt;0) { oss &lt;&lt; ","; } oss &lt;&lt; arrays[i]; } oss &lt;&lt; "]"; auto json_string = oss.str(); // json_string == "[[ 40.1, 39.9, 37.7, 40.4 ],[ 30.1, 31.0, 28.6, 28.7 ]]" &gt;```<code> &lt;/blockquote&gt;* **Extracting Values (without exceptions):** You can use a variant usage of</code>get()<code>with error codes to avoid exceptions. You first declare the variable of the appropriate type (</code>double<code>, </code>uint64_t<code>,</code>int64_t<code>,</code>bool<code>,</code>ondemand::object&lt;tt&gt;andondemand::array&lt;tt&gt;) and pass it by reference toget()` which gives you back an error code: e.g.,</p>
<div class="fragment"><div class="line">{c++}</div>
<div class="line"> auto abstract_json = R&quot;(</div>
<div class="line"> { &quot;str&quot; : { &quot;123&quot; : {&quot;abc&quot; : 3.14 } } }</div>
<div class="line"> )&quot;_padded;</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> </div>
<div class="line"> double value;</div>
<div class="line"> auto doc = parser.iterate(abstract_json);</div>
<div class="line"> auto error = doc[&quot;str&quot;][&quot;123&quot;][&quot;abc&quot;].get(value);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return EXIT_FAILURE; }</div>
<div class="line"> cout &lt;&lt; value &lt;&lt; endl; // Prints 3.14</div>
</div><!-- fragment --><p> This examples also show how we can string several operations and only check for the error once, a strategy we call <em>error chaining</em>. Though error chaining makes the code very compact, it also makes error reporting less precise: in this instance, you may get the same error whether the field "str", "123" or "abc" is missing. If you need to break down error handling per operation, avoid error chaining. Furthermore, you should be mindful that chaining that harm performance by encouraging redundancies: writing both <code>doc["str"]["123"]["abc"].get(value)</code> and <code>doc["str"]["123"]["zyw"].get(value)</code> in the same program may force multiple accesses to the same keys (<code>"str"</code> and <code>"123"</code>).</p>
</blockquote>
</li>
<li><b>Counting elements in arrays:</b> Sometimes it is useful to scan an array to determine its length prior to parsing it. For this purpose, <code>array</code> instances have a <code>count_elements</code> method. Users should be aware that the <code>count_elements</code> method can be costly since it requires scanning the whole array. You should only call <code>count_elements</code> as a last resort as it may require scanning the document twice or more. You may use it as follows if your document is itself an array:</li>
</ul>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> auto cars_json = R&quot;( [ 40.1, 39.9, 37.7, 40.4 ] )&quot;_padded;</div>
<div class="line"> auto doc = parser.iterate(cars_json);</div>
<div class="line"> size_t count = doc.count_elements(); // requires simdjson 1.0 or better</div>
<div class="line"> std::vector&lt;double&gt; values(count);</div>
<div class="line"> size_t index = 0;</div>
<div class="line"> for(double x : doc) { values[index++] = x; }</div>
</div><!-- fragment --><p> If you access an array inside a document, you can use the <code>count_elements</code> method as follow. You should not let the array instance go out of scope before consuming it after calling the <code>count_elements</code> method: </p><div class="fragment"><div class="line">ondemand::parser parser;</div>
<div class="line">auto cars_json = R&quot;( { &quot;test&quot;:[ { &quot;val1&quot;:1, &quot;val2&quot;:2 }, { &quot;val1&quot;:1, &quot;val2&quot;:2 } ] } )&quot;_padded;</div>
<div class="line">auto doc = parser.iterate(cars_json);</div>
<div class="line">auto test_array = doc.find_field(&quot;test&quot;).get_array();</div>
<div class="line">size_t count = test_array.count_elements(); // requires simdjson 1.0 or better</div>
<div class="line">std::cout &lt;&lt; &quot;Number of elements: &quot; &lt;&lt; count &lt;&lt; std::endl;</div>
<div class="line">for(ondemand::object elem: test_array) {</div>
<div class="line"> std::cout &lt;&lt; simdjson::to_json_string(elem);</div>
<div class="line">}</div>
</div><!-- fragment --><ul>
<li><b>Counting fields in objects:</b> Other times, it is useful to scan an object to determine the number of fields prior to parsing it. For this purpose, <code>object</code> instances have a <code>count_fields</code> method. Again, users should be aware that the <code>count_fields</code> method can be costly since it requires scanning the whole objects. You should only call <code>count_fields</code> as a last resort as it may require scanning the document twice or more. You may use it as follows if your document is itself an object:</li>
</ul>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> auto json = R&quot;( { &quot;test&quot;:{ &quot;val1&quot;:1, &quot;val2&quot;:2 } } )&quot;_padded;</div>
<div class="line"> auto doc = parser.iterate(json);</div>
<div class="line"> size_t count = doc.count_fields(); // requires simdjson 1.0 or better</div>
<div class="line"> std::cout &lt;&lt; &quot;Number of fields: &quot; &lt;&lt; new_count &lt;&lt; std::endl; // Prints &quot;Number of fields: 1&quot;</div>
</div><!-- fragment --><p> Similarly to <code>count_elements</code>, you should not let an object instance go out of scope before consuming it after calling the <code>count_fields</code> method. If you access an object inside a document, you can use the <code>count_fields</code> method as follow. </p><div class="fragment"><div class="line">ondemand::parser parser;</div>
<div class="line">auto json = R&quot;( { &quot;test&quot;:{ &quot;val1&quot;:1, &quot;val2&quot;:2 } } )&quot;_padded;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">auto test_object = doc.find_field(&quot;test&quot;).get_object();</div>
<div class="line">size_t count = test_object.count_fields(); // requires simdjson 1.0 or better</div>
<div class="line">std::cout &lt;&lt; &quot;Number of fields: &quot; &lt;&lt; count &lt;&lt; std::endl; // Prints &quot;Number of fields: 2&quot;</div>
</div><!-- fragment --><ul>
<li><p class="startli"><b>Tree Walking and JSON Element Types:</b> Sometimes you don't necessarily have a document with a known type, and are trying to generically inspect or walk over JSON elements. You can also represent arbitrary JSON values with <code>ondemand::value</code> instances: it can represent anything except a scalar document (lone number, string, null or Boolean). You can check for scalar documents with the method <code>scalar()</code>. You can query the type of a document or a value with the <code>type()</code> method. The <code>type()</code> method does not consume or validate documents and values, but it tells you whether they are</p><ul>
<li>arrays (<code>json_type::array</code>),</li>
<li>objects (<code>json_type::object</code>)</li>
<li>numbers (<code>json_type::number</code>),</li>
<li>strings (<code>json_type::string</code>),</li>
<li>Booleans (<code>json_type::boolean</code>),</li>
<li>null (<code>json_type::null</code>).</li>
</ul>
<p class="startli">You must still validate and consume the values (e.g., call <code>is_null()</code>) after calling <code>type()</code>. You may also access <a href="#raw-strings">raw strings</a>. For example, the following is a quick and dirty recursive function that verbosely prints the JSON document as JSON. This example also illustrates lifecycle requirements: the <code>document</code> instance holds the iterator. The document must remain in scope while you are accessing instances of <code>value</code>, <code>object</code> and <code>array</code>. </p><div class="fragment"><div class="line">{c++}</div>
<div class="line"> void recursive_print_json(ondemand::value element) {</div>
<div class="line"> bool add_comma;</div>
<div class="line"> switch (element.type()) {</div>
<div class="line"> case ondemand::json_type::array:</div>
<div class="line"> cout &lt;&lt; &quot;[&quot;;</div>
<div class="line"> add_comma = false;</div>
<div class="line"> for (auto child : element.get_array()) {</div>
<div class="line"> if (add_comma) {</div>
<div class="line"> cout &lt;&lt; &quot;,&quot;;</div>
<div class="line"> }</div>
<div class="line"> // We need the call to value() to get</div>
<div class="line"> // an ondemand::value type.</div>
<div class="line"> recursive_print_json(child.value());</div>
<div class="line"> add_comma = true;</div>
<div class="line"> }</div>
<div class="line"> cout &lt;&lt; &quot;]&quot;;</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::json_type::object:</div>
<div class="line"> cout &lt;&lt; &quot;{&quot;;</div>
<div class="line"> add_comma = false;</div>
<div class="line"> for (auto field : element.get_object()) {</div>
<div class="line"> if (add_comma) {</div>
<div class="line"> cout &lt;&lt; &quot;,&quot;;</div>
<div class="line"> }</div>
<div class="line"> // key() returns the key as it appears in the raw</div>
<div class="line"> // JSON document, if we want the unescaped key,</div>
<div class="line"> // we should do field.unescaped_key().</div>
<div class="line"> cout &lt;&lt; &quot;\&quot;&quot; &lt;&lt; field.key() &lt;&lt; &quot;\&quot;: &quot;;</div>
<div class="line"> recursive_print_json(field.value());</div>
<div class="line"> add_comma = true;</div>
<div class="line"> }</div>
<div class="line"> cout &lt;&lt; &quot;}\n&quot;;</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::json_type::number:</div>
<div class="line"> // assume it fits in a double</div>
<div class="line"> cout &lt;&lt; element.get_double();</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::json_type::string:</div>
<div class="line"> // get_string() would return escaped string, but</div>
<div class="line"> // we are happy with unescaped string.</div>
<div class="line"> cout &lt;&lt; &quot;\&quot;&quot; &lt;&lt; element.get_raw_json_string() &lt;&lt; &quot;\&quot;&quot;;</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::json_type::boolean:</div>
<div class="line"> cout &lt;&lt; element.get_bool();</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::json_type::null:</div>
<div class="line"> // We check that the value is indeed null</div>
<div class="line"> // otherwise: an error is thrown.</div>
<div class="line"> if (element.is_null()) {</div>
<div class="line"> cout &lt;&lt; &quot;null&quot;;</div>
<div class="line"> }</div>
<div class="line"> break;</div>
<div class="line"> }</div>
<div class="line"> }</div>
<div class="line"> void basics_treewalk() {</div>
<div class="line"> padded_string json = R&quot;( [</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line"> ] )&quot;_padded;</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> ondemand::document doc = parser.iterate(json);</div>
<div class="line"> ondemand::value val = doc;</div>
<div class="line"> recursive_print_json(val);</div>
<div class="line"> std::cout &lt;&lt; std::endl;</div>
<div class="line"> }</div>
</div><!-- fragment --></li>
</ul>
<h2><a class="anchor" id="autotoc_md10"></a>
Using the Parsed JSON: Additional examples</h2>
<p>Let us review these concepts with some additional examples. For simplicity, we omit the include clauses (<code>#include "simdjson.h"</code>) as well as namespace-using clauses (<code>using namespace simdjson;</code>).</p>
<p>The first example illustrates how we can chain operations. In this instance, we repeatedly select keys using the bracket operator (<code>doc["str"]</code>) and then finally request a number (using <code>get_double()</code>). It is safe to write code in this manner: if any step causes an error, the error status propagates and an exception is thrown at the end. You do not need to constantly check for errors.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">auto abstract_json = R&quot;(</div>
<div class="line"> { &quot;str&quot; : { &quot;123&quot; : {&quot;abc&quot; : 3.14 } } }</div>
<div class="line">)&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(abstract_json);</div>
<div class="line">cout &lt;&lt; doc[&quot;str&quot;][&quot;123&quot;][&quot;abc&quot;].get_double() &lt;&lt; endl; // Prints 3.14</div>
</div><!-- fragment --><p>In the following example, we start with a JSON document that contains an array of objects. We iterate through the objects using a for-loop. Within each object, we use the bracket operator (e.g., <code>car["make"]</code>) to select values. We also show how we can iterate through an array, corresponding to the key <code>tire_pressure</code>, that is contained inside each object.</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto cars_json = R&quot;( [</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line">] )&quot;_padded;</div>
<div class="line"> </div>
<div class="line">// Iterating through an array of objects</div>
<div class="line">for (ondemand::object car : parser.iterate(cars_json)) {</div>
<div class="line"> // Accessing a field by name</div>
<div class="line"> cout &lt;&lt; &quot;Make/Model: &quot; &lt;&lt; std::string_view(car[&quot;make&quot;]) &lt;&lt; &quot;/&quot; &lt;&lt; std::string_view(car[&quot;model&quot;]) &lt;&lt; endl;</div>
<div class="line"> </div>
<div class="line"> // Casting a JSON element to an integer</div>
<div class="line"> uint64_t year = car[&quot;year&quot;];</div>
<div class="line"> cout &lt;&lt; &quot;- This car is &quot; &lt;&lt; 2020 - year &lt;&lt; &quot;years old.&quot; &lt;&lt; endl;</div>
<div class="line"> </div>
<div class="line"> // Iterating through an array of floats</div>
<div class="line"> double total_tire_pressure = 0;</div>
<div class="line"> for (double tire_pressure : car[&quot;tire_pressure&quot;]) {</div>
<div class="line"> total_tire_pressure += tire_pressure;</div>
<div class="line"> }</div>
<div class="line"> cout &lt;&lt; &quot;- Average tire pressure: &quot; &lt;&lt; (total_tire_pressure / 4) &lt;&lt; endl;</div>
<div class="line">}</div>
</div><!-- fragment --><p>The previous example had an array of objects, but we can use essentially the same approach with an object of objects.</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto cars_json = R&quot;( {</div>
<div class="line"> &quot;identifier1&quot;:{ &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> &quot;identifier2&quot;:{ &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> &quot;identifier3&quot;:{ &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line">} )&quot;_padded;</div>
<div class="line">// Iterating through an array of objects</div>
<div class="line">ondemand::document doc = parser.iterate(cars_json);</div>
<div class="line">for (ondemand::field key_car : doc.get_object()) {</div>
<div class="line"> // If I need a string_view and/or, I can use key_car.unescaped_key() instead, but</div>
<div class="line"> // key_car.key() will be more performant otherwise.</div>
<div class="line"> cout &lt;&lt; &quot;identifier : &quot; &lt;&lt; key_car.key() &lt;&lt; std::endl;</div>
<div class="line"> // I can now access the subobject:</div>
<div class="line"> ondemand::object car = key_car.value();</div>
<div class="line"> // Accessing a field by name</div>
<div class="line"> cout &lt;&lt; &quot;Make/Model: &quot; &lt;&lt; std::string_view(car[&quot;make&quot;]) &lt;&lt; &quot;/&quot; &lt;&lt; std::string_view(car[&quot;model&quot;]) &lt;&lt; endl;</div>
<div class="line"> </div>
<div class="line"> // Casting a JSON element to an integer</div>
<div class="line"> uint64_t year = car[&quot;year&quot;];</div>
<div class="line"> cout &lt;&lt; &quot;- This car is &quot; &lt;&lt; 2020 - year &lt;&lt; &quot;years old.&quot; &lt;&lt; endl;</div>
<div class="line"> </div>
<div class="line"> // Iterating through an array of floats</div>
<div class="line"> double total_tire_pressure = 0;</div>
<div class="line"> for (double tire_pressure : car[&quot;tire_pressure&quot;]) {</div>
<div class="line"> total_tire_pressure += tire_pressure;</div>
<div class="line"> }</div>
<div class="line"> cout &lt;&lt; &quot;- Average tire pressure: &quot; &lt;&lt; (total_tire_pressure / 4) &lt;&lt; endl;</div>
<div class="line">}</div>
</div><!-- fragment --><p>The following example illustrates how you may also iterate through object values, effectively visiting all key-value pairs in the object.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">#include &lt;iostream&gt;</div>
<div class="line">#include &quot;simdjson.h&quot;</div>
<div class="line">using namespace std;</div>
<div class="line">using namespace simdjson;</div>
<div class="line"> </div>
<div class="line">// ...</div>
<div class="line"> </div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto points_json = R&quot;( [</div>
<div class="line"> { &quot;12345&quot; : {&quot;x&quot;:12.34, &quot;y&quot;:56.78, &quot;z&quot;: 9998877} },</div>
<div class="line"> { &quot;12545&quot; : {&quot;x&quot;:11.44, &quot;y&quot;:12.78, &quot;z&quot;: 11111111} }</div>
<div class="line"> ] )&quot;_padded;</div>
<div class="line"> </div>
<div class="line">// Parse and iterate through an array of objects</div>
<div class="line">for (ondemand::object points : parser.iterate(points_json)) {</div>
<div class="line"> // Iterating through an object, you iterate through key-value pairs (a &#39;field&#39;).</div>
<div class="line"> for (auto point : points) {</div>
<div class="line"> // Get the key corresponding the the field &#39;point&#39;.</div>
<div class="line"> cout &lt;&lt; &quot;id: &quot; &lt;&lt; std::string_view(point.unescaped_key()) &lt;&lt; &quot;: (&quot;;</div>
<div class="line"> // Get the value corresponding the the field &#39;point&#39;.</div>
<div class="line"> ondemand::object xyz = point.value();</div>
<div class="line"> cout &lt;&lt; xyz[&quot;x&quot;].get_double() &lt;&lt; &quot;, &quot;;</div>
<div class="line"> cout &lt;&lt; xyz[&quot;y&quot;].get_double() &lt;&lt; &quot;, &quot;;</div>
<div class="line"> cout &lt;&lt; xyz[&quot;z&quot;].get_int64() &lt;&lt; endl;</div>
<div class="line"> }</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md11"></a>
Minifying JSON strings without parsing</h1>
<p>In some cases, you may have valid JSON strings that you do not wish to parse but that you wish to minify. That is, you wish to remove all unnecessary spaces. We have a fast function for this purpose (<code>simdjson::minify(const char * input, size_t length, const char * output, size_t&amp; new_length)</code>). This function does not validate your content, and it does not parse it. It is much faster than parsing the string and re-serializing it in minified form (<code><a class="el" href="namespacesimdjson.html#aeb4ef5cab43d52da3fdd99cb689aff2c" title="Minifies a JSON element or document, printing the smallest possible valid JSON.">simdjson::minify</a>(parser.parse())</code>). Usage is relatively simple. You must pass an input pointer with a length parameter, as well as an output pointer and an output length parameter (by reference). The output length parameter is not read, but written to. The output pointer should point to a valid memory region that is as large as the original string length. The input pointer and input length are read, but not written to.</p>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> // Starts with a valid JSON document as a string.</div>
<div class="line"> // It does not have to be null-terminated.</div>
<div class="line"> const char * some_string = &quot;[ 1, 2, 3, 4] &quot;;</div>
<div class="line"> size_t length = std::strlen(some_string);</div>
<div class="line"> // Create a buffer to receive the minified string. Make sure that there is enough room (length bytes).</div>
<div class="line"> std::unique_ptr&lt;char[]&gt; buffer{new char[length]};</div>
<div class="line"> size_t new_length{}; // It will receive the minified length.</div>
<div class="line"> auto error = simdjson::minify(some_string, length, buffer.get(), new_length);</div>
<div class="line"> // The buffer variable now has &quot;[1,2,3,4]&quot; and new_length has value 9.</div>
</div><!-- fragment --><p>Though it does not validate the JSON input, it will detect when the document ends with an unterminated string. E.g., it would refuse to minify the string <code>"this string is not terminated</code> because of the missing final quote.</p>
<h1><a class="anchor" id="autotoc_md12"></a>
UTF-8 validation (alone)</h1>
<p>The simdjson library has fast functions to validate UTF-8 strings. They are many times faster than most functions commonly found in libraries. You can use our fast functions, even if you do not care about JSON.</p>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> const char * some_string = &quot;[ 1, 2, 3, 4] &quot;;</div>
<div class="line"> size_t length = std::strlen(some_string);</div>
<div class="line"> bool is_ok = simdjson::validate_utf8(some_string, length);</div>
</div><!-- fragment --><p>The UTF-8 validation function merely checks that the input is valid UTF-8: it works with strings in general, not just JSON strings.</p>
<p>Your input string does not need any padding. Any string will do. The <code>validate_utf8</code> function does not do any memory allocation on the heap, and it does not throw exceptions.</p>
<p>If you find yourself needing only fast Unicode functions, consider using the simdutf library instead: <a href="https://github.com/simdutf/simdutf">https://github.com/simdutf/simdutf</a></p>
<h1><a class="anchor" id="autotoc_md13"></a>
JSON Pointer</h1>
<p>The simdjson library also supports <a href="https://tools.ietf.org/html/rfc6901">JSON pointer</a> through the <code>at_pointer()</code> method, letting you reach further down into the document in a single call. JSON pointer is supported by both the <a href="https://github.com/simdjson/simdjson/blob/master/doc/dom.md#json-pointer">DOM approach</a> as well as the On Demand approach.</p>
<p><b>Note:</b> The On Demand implementation of JSON pointer relies on <code>find_field</code> which implies that it does not unescape keys when matching.</p>
<p>Consider the following example:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto cars_json = R&quot;( [</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line">] )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto cars = parser.iterate(cars_json);</div>
<div class="line">cout &lt;&lt; cars.at_pointer(&quot;/0/tire_pressure/1&quot;) &lt;&lt; endl; // Prints 39.9</div>
</div><!-- fragment --><p>A JSON Path is a sequence of segments each starting with the '/' character. Within arrays, an integer index allows you to select the indexed node. Within objects, the string value of the key allows you to select the value. If your keys contain the characters '/' or '~', they must be escaped as '~1' and '~0' respectively. An empty JSON Path refers to the whole document.</p>
<p>For multiple JSON pointer queries on a document, one can call <code>at_pointer</code> multiple times.</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto cars_json = R&quot;( [</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line">] )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto cars = parser.iterate(cars_json);</div>
<div class="line">size_t size = cars.count_elements();</div>
<div class="line"> </div>
<div class="line">for (size_t i = 0; i &lt; size; i++) {</div>
<div class="line"> std::string json_pointer = &quot;/&quot; + std::to_string(i) + &quot;/tire_pressure/1&quot;;</div>
<div class="line"> double x = cars.at_pointer(json_pointer);</div>
<div class="line"> std::cout &lt;&lt; x &lt;&lt; std::endl; // Prints 39.9, 31 and 30</div>
<div class="line">}</div>
</div><!-- fragment --><p>Note that <code>at_pointer</code> calls <a href="#rewind"><code>rewind</code></a> to reset the parser at the beginning of the document. Hence, it invalidates all previously parsed values, objects and arrays: make sure to consume the values between each call to <code>at_pointer</code>. Consider the following example where one wants to store each object from the JSON into a vector of <code>struct car_type</code>:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">struct car_type {</div>
<div class="line"> std::string make;</div>
<div class="line"> std::string model;</div>
<div class="line"> uint64_t year;</div>
<div class="line"> std::vector&lt;double&gt; tire_pressure;</div>
<div class="line"> car_type(std::string_view _make, std::string_view _model, uint64_t _year,</div>
<div class="line"> std::vector&lt;double&gt;&amp;&amp; _tire_pressure) :</div>
<div class="line"> make{_make}, model{_model}, year(_year), tire_pressure(_tire_pressure) {}</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">auto cars_json = R&quot;( [</div>
<div class="line">{ &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line">{ &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line">{ &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line">] )&quot;_padded;</div>
<div class="line"> </div>
<div class="line">ondemand::parser parser;</div>
<div class="line">std::vector&lt;double&gt; measured;</div>
<div class="line">ondemand::document cars = parser.iterate(cars_json);</div>
<div class="line">std::vector&lt;car_type&gt; content;</div>
<div class="line">for (int i = 0; i &lt; 3; i++) {</div>
<div class="line"> std::string json_pointer = &quot;/&quot; + std::to_string(i);</div>
<div class="line"> // Each successive at_pointer call invalidates</div>
<div class="line"> // previously parsed values, strings, objects and array.</div>
<div class="line"> ondemand::object obj(cars.at_pointer(json_pointer).get_object());</div>
<div class="line"> // We materialize the object.</div>
<div class="line"> std::string_view make = obj[&quot;make&quot;];</div>
<div class="line"> std::string_view model = obj[&quot;model&quot;];</div>
<div class="line"> uint64_t year(obj[&quot;year&quot;]);</div>
<div class="line"> // We materialize the array.</div>
<div class="line"> ondemand::array arr(obj[&quot;tire_pressure&quot;].get_array());</div>
<div class="line"> std::vector&lt;double&gt; values;</div>
<div class="line"> for(auto x : arr) {</div>
<div class="line"> double value_double(x.get_double());</div>
<div class="line"> values.push_back(value_double);</div>
<div class="line"> }</div>
<div class="line"> content.emplace_back(make, model, year, std::move(values));</div>
<div class="line">}</div>
</div><!-- fragment --><p>Furthermore, <code>at_pointer</code> calls <code>rewind</code> at the beginning of the call (i.e. the document is not reset after <code>at_pointer</code>). Consider the following example,</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json = R&quot;( {</div>
<div class="line"> &quot;k0&quot;: 27,</div>
<div class="line"> &quot;k1&quot;: [13,26],</div>
<div class="line"> &quot;k2&quot;: true</div>
<div class="line">} )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">std::cout &lt;&lt; doc.at_pointer(&quot;/k1/1&quot;) &lt;&lt; std::endl; // Prints 26</div>
<div class="line">std::cout &lt;&lt; doc.at_pointer(&quot;/k2&quot;) &lt;&lt; std::endl; // Prints true</div>
<div class="line">doc.rewind(); // Need to manually rewind to be able to use find_field properly from start of document</div>
<div class="line">std::cout &lt;&lt; doc.find_field(&quot;k0&quot;) &lt;&lt; std::endl; // Prints 27</div>
</div><!-- fragment --><p>When the JSON path is the empty string (<code>""</code>) applied to a scalar document (lone string, number, Boolean or null), a SCALAR_DOCUMENT_AS_VALUE error is returned because scalar document cannot be represented as <code>value</code> instances. You can check that a document is a scalar with the method <code>scalar()</code>.</p>
<h1><a class="anchor" id="autotoc_md14"></a>
Error Handling</h1>
<p>Error handing with exception and a single try/catch clause makes the code simple, but it gives you little control over errors. For easier debugging or more robust error handling, you may want to consider our exception-free approach.</p>
<p>The entire simdjson API is usable with and without exceptions. All simdjson APIs that can fail return <code>simdjson_result&lt;T&gt;</code>, which is a &lt;value, error_code&gt; pair. You can retrieve the value with .get() without generating an exception, like so:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::document doc;</div>
<div class="line">auto error = parser.iterate(json).get(doc);</div>
<div class="line">if (error) { cerr &lt;&lt; error &lt;&lt; endl; exit(1); }</div>
</div><!-- fragment --><p>When there is no error, the error code <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9aa4ffc800804829a88c5b52ac3c4c6681" title="No error.">simdjson::SUCCESS</a></code>is returned: it evaluates as false as a Boolean. We have several error codes to indicate errors, they all evaluate to true as a Boolean: your software should not generally not depend on exact error codes. We may change the error codes in future releases and the exact error codes could vary depending on your system.</p>
<p>Some errors are recoverable:</p>
<ul>
<li>You may get the error <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9a1de02af1d67e8350f612eee0dcf634b4" title="JSON element has a different type than user expected.">simdjson::INCORRECT_TYPE</a></code> after trying to convert a value to an incorrect type: e.g., you expected a number and try to convert the value to a number, but it is an array.</li>
<li>You may query a key from an object, but the key is missing in which case you get the error <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9a4a2c71f8eca438b3f0553a2811bdab9a" title="JSON field not found in object.">simdjson::NO_SUCH_FIELD</a></code>: e.g., you call <code>obj["myname"]</code> and the object does not have a key <code>"myname"</code>.</li>
</ul>
<p>Other errors (e.g., <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9ab8a4df583110f900741d0b3f229f349a" title="The document ends early.">simdjson::INCOMPLETE_ARRAY_OR_OBJECT</a></code>) may indicate a fatal error and often follow from the fact that the document is not valid JSON. In which case, it is no longer possible to continue accessing the document: calling the method <code>is_alive()</code> on the document instance returns false. All following accesses will keep returning the same fatal error (e.g., <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9ab8a4df583110f900741d0b3f229f349a" title="The document ends early.">simdjson::INCOMPLETE_ARRAY_OR_OBJECT</a></code>).</p>
<p>When you use the code without exceptions, it is your responsibility to check for error before using the result: if there is an error, the result value will not be valid and using it will caused undefined behavior. Most compilers should be able to help you if you activate the right set of warnings: they can identify variables that are written to but never otherwise accessed.</p>
<p>Let us illustrate with an example where we try to access a number that is not valid (<code>3.14.1</code>). If we want to proceed without throwing and catching exceptions, we can do so as follows:</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">bool simple_error_example() {</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> auto json = R&quot;({&quot;bad number&quot;:3.14.1 })&quot;_padded;</div>
<div class="line"> ondemand::document doc;</div>
<div class="line"> if (parser.iterate(json).get(doc) != SUCCESS) { return false; }</div>
<div class="line"> double x;</div>
<div class="line"> auto error = doc[&quot;bad number&quot;].get_double().get(x);</div>
<div class="line"> // returns &quot;simdjson::NUMBER_ERROR&quot;</div>
<div class="line"> if (error != SUCCESS) {</div>
<div class="line"> std::cout &lt;&lt; error &lt;&lt; std::endl;</div>
<div class="line"> return false;</div>
<div class="line"> }</div>
<div class="line"> std::cout &lt;&lt; &quot;Got &quot; &lt;&lt; x &lt;&lt; std::endl;</div>
<div class="line"> return true;</div>
<div class="line">}</div>
</div><!-- fragment --><p>Observe how we verify the error variable before accessing the retrieved number (variable <code>x</code>).</p>
<p>The equivalent with exception handling might look as follows.</p>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> bool simple_error_example_except() {</div>
<div class="line"> TEST_START();</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> auto json = R&quot;({&quot;bad number&quot;:3.14.1 })&quot;_padded;</div>
<div class="line"> try {</div>
<div class="line"> ondemand::document doc = parser.iterate(json);</div>
<div class="line"> double x = doc[&quot;bad number&quot;].get_double();</div>
<div class="line"> std::cout &lt;&lt; &quot;Got &quot; &lt;&lt; x &lt;&lt; std::endl;</div>
<div class="line"> return true;</div>
<div class="line"> } catch(simdjson_error&amp; e) {</div>
<div class="line"> // e.error() == NUMBER_ERROR</div>
<div class="line"> std::cout &lt;&lt; e.error() &lt;&lt; std::endl;</div>
<div class="line"> return false;</div>
<div class="line"> }</div>
<div class="line"> }</div>
</div><!-- fragment --><p>Notice how we can retrieve the exact error condition (in this instance <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9adfcabbbd1ddb0843a0f320e062866ae8" title="Problem while parsing a number.">simdjson::NUMBER_ERROR</a></code>) from the exception.</p>
<p>We can write a "quick start" example where we attempt to parse the following JSON file and access some data, without triggering exceptions: </p><div class="fragment"><div class="line">{</div>
<div class="line"> &quot;statuses&quot;: [</div>
<div class="line"> {</div>
<div class="line"> &quot;id&quot;: 505874924095815700</div>
<div class="line"> },</div>
<div class="line"> {</div>
<div class="line"> &quot;id&quot;: 505874922023837700</div>
<div class="line"> }</div>
<div class="line"> ],</div>
<div class="line"> &quot;search_metadata&quot;: {</div>
<div class="line"> &quot;count&quot;: 100</div>
<div class="line"> }</div>
<div class="line">}</div>
</div><!-- fragment --><p>Our program loads the file, selects value corresponding to key <code>"search_metadata"</code> which expected to be an object, and then it selects the key <code>"count"</code> within that object.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">#include &lt;iostream&gt;</div>
<div class="line">#include &quot;simdjson.h&quot;</div>
<div class="line"> </div>
<div class="line">int main(void) {</div>
<div class="line"> simdjson::ondemand::parser parser;</div>
<div class="line"> auto error = padded_string::load(&quot;twitter.json&quot;).get(json);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return EXIT_FAILURE; }</div>
<div class="line"> simdjson::ondemand::document tweets;</div>
<div class="line"> error = parser.iterate(json).get(tweets);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return EXIT_FAILURE; }</div>
<div class="line"> simdjson::ondemand::value res;</div>
<div class="line"> error = tweets[&quot;search_metadata&quot;][&quot;count&quot;].get(res);</div>
<div class="line"> if (error != SUCCESS) {</div>
<div class="line"> std::cerr &lt;&lt; &quot;could not access keys : &quot; &lt;&lt; error &lt;&lt; std::endl;</div>
<div class="line"> return EXIT_FAILURE;</div>
<div class="line"> }</div>
<div class="line"> std::cout &lt;&lt; res &lt;&lt; &quot; results.&quot; &lt;&lt; std::endl;</div>
<div class="line"> return EXIT_SUCCESS;</div>
<div class="line">}</div>
</div><!-- fragment --><p>The following is a similar example where one wants to get the id of the first tweet without triggering exceptions. To do this, we use <code>["statuses"].at(0)["id"]</code>. We break that expression down:</p>
<ul>
<li>Get the list of tweets (the <code>"statuses"</code> key of the document) using <code>["statuses"]</code>). The result is expected to be an array.</li>
<li>Get the first tweet using <code>.at(0)</code>. The result is expected to be an object.</li>
<li>Get the id of the tweet using ["id"]. We expect the value to be a non-negative integer.</li>
</ul>
<p>Observe how we use the <code>at</code> method when querying an index into an array, and not the bracket operator.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">#include &lt;iostream&gt;</div>
<div class="line">#include &quot;simdjson.h&quot;</div>
<div class="line"> </div>
<div class="line">int main(void) {</div>
<div class="line"> simdjson::ondemand::parser parser;</div>
<div class="line"> simdjson::ondemand::document tweets;</div>
<div class="line"> padded_string json;</div>
<div class="line"> auto error = padded_string::load(&quot;twitter.json&quot;).get(json);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return EXIT_FAILURE; }</div>
<div class="line"> error = parser.iterate(json).get(tweets);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return EXIT_FAILURE; }</div>
<div class="line"> uint64_t identifier;</div>
<div class="line"> error = tweets[&quot;statuses&quot;].at(0)[&quot;id&quot;].get(identifier);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return EXIT_FAILURE; }</div>
<div class="line"> std::cout &lt;&lt; identifier &lt;&lt; std::endl;</div>
<div class="line">}</div>
</div><!-- fragment --><p>The <code>at</code> method can only be called once on an array. It cannot be used to iterate through the values of an array.</p>
<h2><a class="anchor" id="autotoc_md15"></a>
Error Handling Examples without Exceptions</h2>
<p>This is how the example in "Using the Parsed JSON" could be written using only error code checking (without exceptions):</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">bool parse() {</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> auto cars_json = R&quot;( [</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line"> ] )&quot;_padded;</div>
<div class="line"> ondemand::document doc;</div>
<div class="line"> </div>
<div class="line"> // Iterating through an array of objects</div>
<div class="line"> auto error = parser.iterate(cars_json).get(doc);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> ondemand::array cars; // invalid until the get() succeeds</div>
<div class="line"> error = doc.get_array().get(cars);</div>
<div class="line"> </div>
<div class="line"> for (auto car_value : cars) {</div>
<div class="line"> ondemand::object car; // invalid until the get() succeeds</div>
<div class="line"> error = car_value.get_object().get(car);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> </div>
<div class="line"> // Accessing a field by name</div>
<div class="line"> std::string_view make;</div>
<div class="line"> std::string_view model;</div>
<div class="line"> error = car[&quot;make&quot;].get(make);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> error = car[&quot;model&quot;].get(model);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> </div>
<div class="line"> cout &lt;&lt; &quot;Make/Model: &quot; &lt;&lt; make &lt;&lt; &quot;/&quot; &lt;&lt; model &lt;&lt; endl;</div>
<div class="line"> </div>
<div class="line"> // Casting a JSON element to an integer</div>
<div class="line"> uint64_t year{};</div>
<div class="line"> error = car[&quot;year&quot;].get(year);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> cout &lt;&lt; &quot;- This car is &quot; &lt;&lt; 2020 - year &lt;&lt; &quot; years old.&quot; &lt;&lt; endl;</div>
<div class="line"> </div>
<div class="line"> // Iterating through an array of floats</div>
<div class="line"> double total_tire_pressure = 0;</div>
<div class="line"> ondemand::array pressures;</div>
<div class="line"> error = car[&quot;tire_pressure&quot;].get_array().get(pressures);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> for (auto tire_pressure_value : pressures) {</div>
<div class="line"> double tire_pressure;</div>
<div class="line"> error = tire_pressure_value.get_double().get(tire_pressure);</div>
<div class="line"> if (error) { std::cerr &lt;&lt; error &lt;&lt; std::endl; return false; }</div>
<div class="line"> total_tire_pressure += tire_pressure;</div>
<div class="line"> }</div>
<div class="line"> cout &lt;&lt; &quot;- Average tire pressure: &quot; &lt;&lt; (total_tire_pressure / 4) &lt;&lt; endl;</div>
<div class="line"> }</div>
<div class="line"> return true;</div>
<div class="line">}</div>
</div><!-- fragment --><p>For safety, you should only use our ondemand instances (e.g., <code>ondemand::object</code>) after you have initialized them and checked that there is no error:</p>
<div class="fragment"><div class="line">{c++}</div>
<div class="line"> ondemand::object car; // invalid until the get() succeeds</div>
<div class="line"> // the `car` instance should not use used before it is initialized</div>
<div class="line"> error = car_value.get_object().get(car);</div>
<div class="line"> if (error) {</div>
<div class="line"> // the `car` instance should not use used</div>
<div class="line"> } else {</div>
<div class="line"> // the `car` instance can be safely used</div>
<div class="line"> }</div>
</div><!-- fragment --><p>The following examples illustrates how to iterate through the content of an object without having to handle exceptions. </p><div class="fragment"><div class="line">{c++}</div>
<div class="line"> auto json = R&quot;({&quot;k\u0065y&quot;: 1})&quot;_padded;</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> ondemand::document doc;</div>
<div class="line"> auto error = parser.iterate(json).get(doc);</div>
<div class="line"> if (error) { return false; }</div>
<div class="line"> ondemand::object object; // invalid until the get() succeeds</div>
<div class="line"> error = doc.get_object().get(object);</div>
<div class="line"> if (error) { return false; }</div>
<div class="line"> for(auto field : object) {</div>
<div class="line"> // We could replace &#39;field.key() with field.unescaped_key(),</div>
<div class="line"> // and ondemand::raw_json_string by std::string_view.</div>
<div class="line"> ondemand::raw_json_string keyv;</div>
<div class="line"> error = field.key().get(keyv);</div>
<div class="line"> if (error) { return false; }</div>
<div class="line"> if (keyv == &quot;key&quot;) {</div>
<div class="line"> uint64_t intvalue;</div>
<div class="line"> error = field.value().get(intvalue);</div>
<div class="line"> if (error) { return false; }</div>
<div class="line"> std::cout &lt;&lt; intvalue;</div>
<div class="line"> }</div>
<div class="line"> }</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md16"></a>
Disabling Exceptions</h2>
<p>The simdjson can be build with exceptions entirely disabled. It checks the <code>__cpp_exceptions</code> macro at compile time. Even if exceptions are enabled in your compiler, you may still disable exceptions specifically for simdjson, by setting <code>SIMDJSON_EXCEPTIONS</code> to <code>0</code> (false) at compile-time when building the simdjson library. If you are building with CMake, to ensure you don't write any code that uses exceptions, you compile with <code>SIMDJSON_EXCEPTIONS=OFF</code>. For example, if including the project via cmake:</p>
<div class="fragment"><div class="line">target_compile_definitions(simdjson PUBLIC SIMDJSON_EXCEPTIONS=OFF)</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md17"></a>
Exceptions</h2>
<p>Users more comfortable with an exception flow may choose to directly cast the <code>simdjson_result&lt;T&gt;</code> to the desired type:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">simdjson::ondemand::document doc = parser.iterate(json); // Throws an exception if there was an error!</div>
</div><!-- fragment --><p>When used this way, a <code>simdjson_error</code> exception will be thrown if an error occurs, preventing the program from continuing if there was an error.</p>
<p>If one is willing to trigger exceptions, it is possible to write simpler code:</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">#include &lt;iostream&gt;</div>
<div class="line">#include &quot;simdjson.h&quot;</div>
<div class="line"> </div>
<div class="line">int main(void) {</div>
<div class="line"> simdjson::ondemand::parser parser;</div>
<div class="line"> padded_string json = padded_string::load(&quot;twitter.json&quot;);</div>
<div class="line"> simdjson::ondemand::document tweets = parser.iterate(json);</div>
<div class="line"> uint64_t identifier = tweets[&quot;statuses&quot;].at(0)[&quot;id&quot;];</div>
<div class="line"> std::cout &lt;&lt; identifier &lt;&lt; std::endl;</div>
<div class="line"> return EXIT_SUCCESS;</div>
<div class="line">}</div>
</div><!-- fragment --><p>You can do handle errors gracefully as well...</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">#include &lt;iostream&gt;</div>
<div class="line">#include &quot;simdjson.h&quot;</div>
<div class="line">int main(void) {</div>
<div class="line"> simdjson::ondemand::parser parser;</div>
<div class="line"> simdjson::padded_string json_string;</div>
<div class="line"> simdjson::ondemand::document doc;</div>
<div class="line"> try {</div>
<div class="line"> json_string = padded_string::load(&quot;twitter.json&quot;);</div>
<div class="line"> doc = parser.iterate(json_string);</div>
<div class="line"> uint64_t identifier = doc[&quot;statuses&quot;].at(0)[&quot;id&quot;];</div>
<div class="line"> std::cout &lt;&lt; identifier &lt;&lt; std::endl;</div>
<div class="line"> } catch (simdjson::simdjson_error &amp;error) {</div>
<div class="line"> std::cerr &lt;&lt; &quot;JSON error: &quot; &lt;&lt; error.what() &lt;&lt; &quot; near &quot;</div>
<div class="line"> &lt;&lt; doc.current_location() &lt;&lt; &quot; in &quot; &lt;&lt; json_string &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md18"></a>
Current location in document</h2>
<p>Sometimes, it might be helpful to know the current location in the document during iteration. This is especially useful when encountering errors. The <code>current_location()</code> method on a <code>document</code> instances makes it easy to identify common JSON errors. Users can call the <code>current_location()</code> method on a valid document instance to retrieve a <code>const char *</code> pointer to the current location in the document. This method also works even after an error has invalidated the document and the parser (e.g. <code>TAPE_ERROR</code>, <code>INCOMPLETE_ARRAY_OR_OBJECT</code>). When the input was a <code>padding_string</code> or another null-terminated source, then you may use the <code>const char *</code> pointer as a C string. As an example, consider the following example where we used the exception-free simdjson interface:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto broken_json = R&quot;( {&quot;double&quot;: 13.06, false, &quot;integer&quot;: -343} )&quot;_padded; // Missing key</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(broken_json);</div>
<div class="line">int64_t i;</div>
<div class="line">auto error = doc[&quot;integer&quot;].get_int64().get(i); // Expect to get integer from &quot;integer&quot; key, but get TAPE_ERROR</div>
<div class="line">if (error) {</div>
<div class="line"> std::cout &lt;&lt; error &lt;&lt; std::endl; // Prints TAPE_ERROR error message</div>
<div class="line"> // Recover a pointer to the location of the first error:</div>
<div class="line"> const char * ptr;</div>
<div class="line"> doc.current_location().get(ptr);</div>
<div class="line"> // ptr points at &#39;false, &quot;integer&quot;: -343} &quot; which is the location of the error</div>
<div class="line"> //</div>
<div class="line"> // Because we pad simdjson::padded_string instances with null characters, you may also do the following:</div>
<div class="line"> std::cout&lt;&lt; doc.current_location() &lt;&lt; std::endl; // Prints &quot;false, &quot;integer&quot;: -343} &quot; (location of TAPE_ERROR)</div>
<div class="line">}</div>
</div><!-- fragment --><p>You may also use <code>current_location()</code> with exceptions as follows:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto broken_json = R&quot;( {&quot;double&quot;: 13.06, false, &quot;integer&quot;: -343} )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">ondemand::document doc = parser.iterate(broken_json);</div>
<div class="line">try {</div>
<div class="line"> return int64_t(doc[&quot;integer&quot;]);</div>
<div class="line">} catch(simdjson_error&amp; err) {</div>
<div class="line"> std::cerr &lt;&lt; doc.current_location() &lt;&lt; std::endl;</div>
<div class="line"> return -1;</div>
<div class="line">}</div>
</div><!-- fragment --><p>In these examples, we tried to access the <code>"integer"</code> key, but since the parser had to go through a value without a key before (<code>false</code>), a <code>TAPE_ERROR</code> error is thrown. The pointer returned by the <code>current_location()</code> method then points at the location of the error. The <code>current_location()</code> may also be used when the error is triggered by a user action, even if the JSON input is valid. Consider the following example:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json = R&quot;( [1,2,3] )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">int64_t i;</div>
<div class="line">auto error = doc[&quot;integer&quot;].get_int64().get(i); // Incorrect call on array, INCORRECT_TYPE error</div>
<div class="line">if (error) {</div>
<div class="line"> std::cout &lt;&lt; error &lt;&lt; std::endl; // Prints INCORRECT_TYPE error message</div>
<div class="line"> std::cout&lt;&lt; doc.current_location() &lt;&lt; std::endl; // Prints &quot;[1,2,3] &quot; (location of INCORRECT_TYPE error)</div>
<div class="line">}</div>
</div><!-- fragment --><p>If the location is invalid (i.e. at the end of a document), the <code>current_location()</code> methods returns an <code>OUT_OF_BOUNDS</code> error. For example:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json = R&quot;( [1,2,3] )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">for (auto val : doc) {</div>
<div class="line"> // Do something with val</div>
<div class="line">}</div>
<div class="line">std::cout &lt;&lt; doc.current_location() &lt;&lt; std::endl; // Throws OUT_OF_BOUNDS</div>
</div><!-- fragment --><p>Conversely, if <code>doc.current_location().error() == <a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9aa4ffc800804829a88c5b52ac3c4c6681" title="No error.">simdjson::SUCCESS</a></code>, then the document has more content.</p>
<p>Finally, the <code>current_location()</code> method may also be used even when no exceptions/errors are thrown. This can be helpful for users that want to know the current state of iteration during parsing. For example:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json = R&quot;( [[1,2,3], -23.4, {&quot;key&quot;: &quot;value&quot;}, true] )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">for (auto val : doc) {</div>
<div class="line"> ondemand::object obj; // invalid until the get() succeeds</div>
<div class="line"> auto error = val.get_object().get(obj); // Only get objects</div>
<div class="line"> if (!error) {</div>
<div class="line"> std::cout &lt;&lt; doc.current_location() &lt;&lt; std::endl; // Prints &quot;&quot;key&quot;: &quot;value&quot;}, true] &quot;</div>
<div class="line"> }</div>
<div class="line">}</div>
</div><!-- fragment --><p>The <code>current_location()</code> method requires a valid <code>document</code> instance. If the <code>iterate</code> function fails to return a valid document, then you cannot use <code>current_location()</code> to identify the location of an error in the input string. The errors reported by <code>iterate</code> function include EMPTY if no JSON document is detected, UTF8_ERROR if the string is not a valid UTF-8 string, UNESCAPED_CHARS if a string contains control characters that must be escaped and UNCLOSED_STRING if there is an unclosed string in the document. We do not provide location information for these errors.</p>
<h2><a class="anchor" id="autotoc_md19"></a>
Checking for trailing content</h2>
<p>The parser validates all parsed content, but your code may exhaust the content while not having processed the entire document. Thus, as a final optional step, you may call <code>at_end()</code> on the document instance. If it returns <code>false</code>, then you may conclude that you have trailing content and that your document is not valid JSON. You may then use <code>doc.current_location()</code> to obtain a pointer to the start of the trailing content.</p>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> auto json = R&quot;([1, 2] foo ])&quot;_padded;</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> ondemand::document doc = parser.iterate(json);</div>
<div class="line"> ondemand::array array = doc.get_array();</div>
<div class="line"> for (uint64_t values : array) {</div>
<div class="line"> std::cout &lt;&lt; values &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line"> if (!doc.at_end()) {</div>
<div class="line"> // In this instance, we will be left pointing at &#39;foo&#39; since we have consumed the array [1,2].</div>
<div class="line"> std::cerr &lt;&lt; &quot;trailing content at byte index &quot; &lt;&lt; doc.current_location() - json.data() &lt;&lt; std::endl;</div>
<div class="line"> }</div>
</div><!-- fragment --><p>The <code>at_end()</code> method is equivalent to <code>doc.current_location().error() == <a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9aa4ffc800804829a88c5b52ac3c4c6681" title="No error.">simdjson::SUCCESS</a></code> but more convenient.</p>
<h1><a class="anchor" id="autotoc_md20"></a>
Rewinding</h1>
<p>In some instances, you may need to go through a document more than once. For that purpose, you may call the <code>rewind()</code> method on the document instance. It allows you to restart processing from the beginning without rescanning all of the input data again. It invalidates all values, objects and arrays that you have created so far (including unescaped strings).</p>
<p>In the following example, we print on the screen the number of cars in the JSON input file before printout the data.</p>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> auto cars_json = R&quot;( [</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Camry&quot;, &quot;year&quot;: 2018, &quot;tire_pressure&quot;: [ 40.1, 39.9, 37.7, 40.4 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Kia&quot;, &quot;model&quot;: &quot;Soul&quot;, &quot;year&quot;: 2012, &quot;tire_pressure&quot;: [ 30.1, 31.0, 28.6, 28.7 ] },</div>
<div class="line"> { &quot;make&quot;: &quot;Toyota&quot;, &quot;model&quot;: &quot;Tercel&quot;, &quot;year&quot;: 1999, &quot;tire_pressure&quot;: [ 29.8, 30.0, 30.2, 30.5 ] }</div>
<div class="line"> ] )&quot;_padded;</div>
<div class="line"> </div>
<div class="line"> auto doc = parser.iterate(cars_json);</div>
<div class="line"> for (simdjson_unused ondemand::object car : doc) {</div>
<div class="line"> if (car[&quot;make&quot;] == &quot;Toyota&quot;) { count++; }</div>
<div class="line"> }</div>
<div class="line"> std::cout &lt;&lt; &quot;We have &quot; &lt;&lt; count &lt;&lt; &quot; Toyota cars.\n&quot;;</div>
<div class="line"> doc.rewind(); // requires simdjson 1.0 or better</div>
<div class="line"> for (ondemand::object car : doc) {</div>
<div class="line"> cout &lt;&lt; &quot;Make/Model: &quot; &lt;&lt; std::string_view(car[&quot;make&quot;]) &lt;&lt; &quot;/&quot; &lt;&lt; std::string_view(car[&quot;model&quot;]) &lt;&lt; endl;</div>
<div class="line"> }</div>
</div><!-- fragment --><p>Performance note: the On Demand front-end does not materialize the parsed numbers and other values. If you are accessing everything twice, you may need to parse them twice. Thus the rewind functionality is best suited for cases where the first pass only scans the structure of the document.</p>
<p>Both arrays and objects have a similar method <code>reset()</code>. It is similar to the document <code>rewind()</code> method, except that it does not rewind the internal string buffer. Thus you should consume values only once even if you can iterate through the array or object more than once. If you unescape a string within an array more than once, you have unsafe code.</p>
<h1><a class="anchor" id="autotoc_md21"></a>
Newline-Delimited JSON (ndjson) and JSON lines</h1>
<p>When processing large inputs (e.g., in the context of data engineering), engineers commonly serialize data into streams of multiple JSON documents. That is, instead of one large (e.g., 2 GB) JSON document containing multiple records, it is often preferable to write out multiple records as independent JSON documents, to be read one-by-one.</p>
<p>The simdjson library also supports multithreaded JSON streaming through a large file containing many smaller JSON documents in either <a href="http://ndjson.org">ndjson</a> or <a href="http://jsonlines.org">JSON lines</a> format. If your JSON documents all contain arrays or objects, we even support direct file concatenation without whitespace. However, if there is content between your JSON documents, it should be exclusively ASCII white-space characters.</p>
<p>The concatenated file has no size restrictions (including larger than 4GB), though each individual document must be no larger than 4 GB.</p>
<p>Here is an example:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json = R&quot;({ &quot;foo&quot;: 1 } { &quot;foo&quot;: 2 } { &quot;foo&quot;: 3 } )&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">ondemand::document_stream docs = parser.iterate_many(json);</div>
<div class="line">for (auto doc : docs) {</div>
<div class="line"> std::cout &lt;&lt; doc[&quot;foo&quot;] &lt;&lt; std::endl;</div>
<div class="line">}</div>
<div class="line">// Prints 1 2 3</div>
</div><!-- fragment --><p>Unlike <code>parser.iterate</code>, <code>parser.iterate_many</code> may parse "on demand" (lazily). That is, no parsing may have been done before you enter the loop <code>for (auto doc : docs) {</code> and you should expect the parser to only ever fully parse one JSON document at a time.</p>
<p>As with <code>parser.iterate</code>, when calling <code>parser.iterate_many(string)</code>, no copy is made of the provided string input. The provided memory buffer may be accessed each time a JSON document is parsed. Calling <code>parser.iterate_many(string)</code> on a temporary string buffer (e.g., <code>docs = parser.parse_many("[1,2,3]"_padded)</code>) is unsafe (and will not compile) because the <code>document_stream</code> instance needs access to the buffer to return the JSON documents.</p>
<p>The <code>iterate_many</code> function can also take an optional parameter <code>size_t batch_size</code> which defines the window processing size. It is set by default to a large value (<code>1000000</code> corresponding to 1 MB). None of your JSON documents should exceed this window size, or else you will get the error <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9a2d50048bbe409023df4e88f6ffe3bc71" title="This parser can&#39;t support a document that big.">simdjson::CAPACITY</a></code>. You cannot set this window size larger than 4 GB: you will get the error <code><a class="el" href="namespacesimdjson.html#a7b735a3a50ba79e3f7f14df5f77d8da9a2d50048bbe409023df4e88f6ffe3bc71" title="This parser can&#39;t support a document that big.">simdjson::CAPACITY</a></code>. The smaller the window size is, the less memory the function will use. Setting the window size too small (e.g., less than 100 kB) may also impact performance negatively. Leaving it to 1 MB is expected to be a good choice, unless you have some larger documents.</p>
<p>The following toy examples illustrates how to get capacity errors. It is an artificial example since you should never use a <code>batch_size</code> of 50 bytes (it is far too small).</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">// We are going to set the capacity to 50 bytes which means that we cannot</div>
<div class="line">// loading a document longer than 50 bytes. The first few documents are small,</div>
<div class="line">// but the last one is large. We will get an error at the last document.</div>
<div class="line">auto json = R&quot;([1,2,3,4,5] [1,2,3,4,5] [1,2,3,4,5] [1,2,3,4,5] [1,2,3,4,5] [1,2,3,4,5] [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100])&quot;_padded;</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">ondemand::document_stream stream;</div>
<div class="line">size_t counter{0};</div>
<div class="line">auto error = parser.iterate_many(json, 50).get(stream);</div>
<div class="line">if (error) { /* handle the error */ }</div>
<div class="line">for (auto doc: stream) {</div>
<div class="line"> if (counter &lt; 6) {</div>
<div class="line"> int64_t val;</div>
<div class="line"> error = doc.at_pointer(&quot;/4&quot;).get(val);</div>
<div class="line"> if (error) { /* handle the error */ }</div>
<div class="line"> std::cout &lt;&lt; &quot;5 = &quot; &lt;&lt; val &lt;&lt; std::endl;</div>
<div class="line"> } else {</div>
<div class="line"> ondemand::value val;</div>
<div class="line"> error = doc.at_pointer(&quot;/4&quot;).get(val);</div>
<div class="line"> // error == simdjson::CAPACITY</div>
<div class="line"> if (error) {</div>
<div class="line"> std::cerr &lt;&lt; error &lt;&lt; std::endl;</div>
<div class="line"> // We left 293 bytes unprocessed at the tail end of the input.</div>
<div class="line"> std::cout &lt;&lt; &quot; unprocessed bytes at the end: &quot; &lt;&lt; stream.truncated_bytes() &lt;&lt; std::endl;</div>
<div class="line"> break;</div>
<div class="line"> }</div>
<div class="line"> }</div>
<div class="line"> counter++;</div>
<div class="line">}</div>
</div><!-- fragment --><p>This example should print out:</p>
<div class="fragment"><div class="line">5 = 5</div>
<div class="line">5 = 5</div>
<div class="line">5 = 5</div>
<div class="line">5 = 5</div>
<div class="line">5 = 5</div>
<div class="line">5 = 5</div>
<div class="line">This parser can&#39;t support a document that big</div>
<div class="line"> unprocessed bytes at the end: 293</div>
</div><!-- fragment --><p>If your documents are large (e.g., larger than a megabyte), then the <code>iterate_many</code> function is maybe ill-suited. It is really meant to support reading efficiently streams of relatively small documents (e.g., a few kilobytes each). If you have larger documents, you should use other functions like <code>iterate</code>.</p>
<p>We also provide some support for comma-separated documents and other advanced features. See <a class="el" href="md_doc_iterate_many.html">iterate_many.md</a> for detailed information and design.</p>
<h1><a class="anchor" id="autotoc_md22"></a>
Parsing Numbers Inside Strings</h1>
<p>Though the JSON specification allows for numbers and string values, many engineers choose to integrate the numbers inside strings, e.g., they prefer <code>{"a":"1.9"}</code> to<code>{"a":1.9}</code>. The simdjson library supports parsing valid numbers inside strings which makes it more convenient for people working with those types of documents. This feature is supported through three methods: <code>get_double_in_string</code>, <code>get_int64_in_string</code> and <code>get_uint64_in_string</code>. However, it is important to note that these methods are not substitute to the regular <code>get_double</code>, <code>get_int64</code> and <code>get_uint64</code>. The usage of the <code>get_*_in_string</code> methods is solely to parse valid JSON numbers inside strings, and so we expect users to call these methods appropriately. In particular, a valid JSON number has no leading and no trailing whitespaces, and the strings <code>"nan"</code>, <code>"1e"</code> and <code>"infinity"</code> will not be accepted as valid numbers. As an example, suppose we have the following JSON text:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">auto json =</div>
<div class="line">{</div>
<div class="line"> &quot;ticker&quot;:{</div>
<div class="line"> &quot;base&quot;:&quot;BTC&quot;,</div>
<div class="line"> &quot;target&quot;:&quot;USD&quot;,</div>
<div class="line"> &quot;price&quot;:&quot;443.7807865468&quot;,</div>
<div class="line"> &quot;volume&quot;:&quot;31720.1493969300&quot;,</div>
<div class="line"> &quot;change&quot;:&quot;Infinity&quot;,</div>
<div class="line"> &quot;markets&quot;:[</div>
<div class="line"> {</div>
<div class="line"> &quot;market&quot;:&quot;bitfinex&quot;,</div>
<div class="line"> &quot;price&quot;:&quot;447.5000000000&quot;,</div>
<div class="line"> &quot;volume&quot;:&quot;10559.5293639000&quot;</div>
<div class="line"> },</div>
<div class="line"> {</div>
<div class="line"> &quot;market&quot;:&quot;bitstamp&quot;,</div>
<div class="line"> &quot;price&quot;:&quot;448.5400000000&quot;,</div>
<div class="line"> &quot;volume&quot;:&quot;11628.2880079300&quot;</div>
<div class="line"> },</div>
<div class="line"> {</div>
<div class="line"> &quot;market&quot;:&quot;btce&quot;,</div>
<div class="line"> &quot;price&quot;:&quot;432.8900000000&quot;,</div>
<div class="line"> &quot;volume&quot;:&quot;8561.0563600000&quot;</div>
<div class="line"> }</div>
<div class="line"> ]</div>
<div class="line"> },</div>
<div class="line"> &quot;timestamp&quot;:1399490941,</div>
<div class="line"> &quot;timestampstr&quot;:&quot;1399490941&quot;</div>
<div class="line">}</div>
</div><!-- fragment --><p>Now, suppose that a user wants to get the time stamp from the <code>timestampstr</code> key. One could do the following:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">uint64_t time = doc.at_pointer(&quot;/timestampstr&quot;).get_uint64_in_string();</div>
<div class="line">std::cout &lt;&lt; time &lt;&lt; std::endl; // Prints 1399490941</div>
</div><!-- fragment --><p>Another thing a user might want to do is extract the <code>markets</code> array and get the market name, price and volume. Here is one way to do so:</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line"> </div>
<div class="line">// Getting markets array</div>
<div class="line">ondemand::array markets = doc.find_field(&quot;ticker&quot;).find_field(&quot;markets&quot;).get_array();</div>
<div class="line">// Iterating through markets array</div>
<div class="line">for (auto value : markets) {</div>
<div class="line"> std::cout &lt;&lt; &quot;Market: &quot; &lt;&lt; value.find_field(&quot;market&quot;).get_string();</div>
<div class="line"> std::cout &lt;&lt; &quot;\tPrice: &quot; &lt;&lt; value.find_field(&quot;price&quot;).get_double_in_string();</div>
<div class="line"> std::cout &lt;&lt; &quot;\tVolume: &quot; &lt;&lt; value.find_field(&quot;volume&quot;).get_double_in_string() &lt;&lt; std::endl;</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">/* The above prints</div>
<div class="line">Market: bitfinex Price: 447.5 Volume: 10559.5</div>
<div class="line">Market: bitstamp Price: 448.54 Volume: 11628.3</div>
<div class="line">Market: btce Price: 432.89 Volume: 8561.06</div>
<div class="line">*/</div>
</div><!-- fragment --><p>Finally, here is an example dealing with errors where the user wants to convert the string <code>"Infinity"</code>(<code>"change"</code> key) to a float with infinity value.</p>
<div class="fragment"><div class="line"> {c++}</div>
<div class="line">ondemand::parser parser;</div>
<div class="line">auto doc = parser.iterate(json);</div>
<div class="line">// Get &quot;change&quot;/&quot;Infinity&quot; key/value pair</div>
<div class="line">ondemand::value value = doc.find_field(&quot;ticker&quot;).find_field(&quot;change&quot;);</div>
<div class="line">double d;</div>
<div class="line">std::string_view view;</div>
<div class="line">auto error = value.get_double_in_string().get(d);</div>
<div class="line">// Check if parsed value into double successfully</div>
<div class="line">if (error) {</div>
<div class="line"> error = value.get_string().get(view);</div>
<div class="line"> if (error) { /* Handle error */ }</div>
<div class="line"> else if (view == &quot;Infinity&quot;) {</div>
<div class="line"> d = std::numeric_limits::infinity();</div>
<div class="line"> }</div>
<div class="line"> else { /* Handle wrong value */ }</div>
<div class="line">}</div>
</div><!-- fragment --><p> It is also important to note that when dealing an invalid number inside a string, simdjson will report a <code>NUMBER_ERROR</code> error if the string begins with a number whereas simdjson will report a <code>INCORRECT_TYPE</code> error otherwise.</p>
<p>The <code>*_in_string</code> methods can also be called on a single document instance: e.g., when your document consist solely of a quoted number.</p>
<h1><a class="anchor" id="autotoc_md23"></a>
Dynamic Number Types</h1>
<p>The JSON standard does not offer strongly typed numbers. It suggests that using the binary64 type (<code>double</code> in C++) is a safe choice, but little else. Given the JSON array <code>[1.0,1]</code>, it is not specified whether it is an array of two floating-point numbers, two integers, or one floating-point number followed by an integer.</p>
<p>Given an <code>ondemand::value</code> instance, you may ask whether it is a negative value with the <code>is_negative()</code> method. The function is inexpensive.</p>
<p>To occasionally distinguish between floating-point values and integers given an <code>ondemand::value</code> instance, you may call the <code>is_integer()</code> method. We recognize an integer number by the lack decimal point and the lack of exponential suffix. E.g., <code>1e1</code> is always considered to be a floating-point number. The <code>is_integer()</code> method does not consume the value, but it scans the number string. You should avoid calling it repeatedly.</p>
<p>If you need to determine both the type of the number (integer or floating-point) and its value efficiently, you may call the <code>get_number()</code> method on the <code>ondemand::value</code> instance. Upon success, it returns an <code>ondemand::number</code> instance.</p>
<p>An <code>ondemand::number</code> instance may contain an integer value or a floating-point value. Thus it is a dynamically typed number. Before accessing the value, you must determine the detected type:</p>
<ul>
<li><code>number.get_number_type()</code> has value <code>number_type::signed_integer</code> if we have a integer in [-9223372036854775808,9223372036854775808). You can recover the value by the <code>get_int64()</code> method applied on the <code>ondemand::number</code> instance. When <code>number.get_number_type()</code> has value <code>number_type::signed_integer</code>, you also have that <code>number.is_int64()</code> is true. Calling <code>get_int64()</code> on the <code>ondemand::number</code> instance when <code>number.get_number_type()</code> is not <code>number_type::signed_integer</code> is unsafe. You may replace <code>get_int64()</code> by a cast to a <code>int64_t</code> value.</li>
<li><code>number.get_number_type()</code> has value <code>number_type::unsigned_integer</code> if we have a integer in [9223372036854775808,18446744073709551616). You can recover the value by the <code>get_uint64()</code> method applied on the <code>ondemand::number</code> instance. When <code>number.get_number_type()</code> has value <code>number_type::unsigned_integer</code>, you also have that <code>number.is_uint64()</code> is true. Calling <code>get_uint64()</code> on the <code>ondemand::number</code> instance when <code>number.get_number_type()</code> is not <code>number_type::unsigned_integer</code> is unsafe. You may replace <code>get_uint64()</code> by a cast to a <code>uint64_t</code> value.</li>
<li><code>number.get_number_type()</code> has value <code>number_type::floating_point_number</code> if we have and we have a floating-point (binary64) number. You can recover the value by the <code>get_double()</code> method applied on the <code>ondemand::number</code> instance. When <code>number.get_number_type()</code> has value <code>number_type::floating_point_number</code>, you also have that <code>number.is_double()</code> is true. Calling <code>get_double()</code> on the <code>ondemand::number</code> instance when <code>number.get_number_type()</code> is not <code>number_type::floating_point_number</code> is unsafe. You may replace <code>get_double()</code> by a cast to a <code>double</code> value.</li>
</ul>
<p>You must check the type before accessing the value: it is an error to call <code>get_int64()</code> when <code>number.get_number_type()</code> is not <code>number_type::signed_integer</code> and when <code>number.is_int64()</code> is false. You are responsible for this check as the user of the library.</p>
<p>The <code>get_number()</code> function is designed with performance in mind. When calling <code>get_number()</code>, you scan the number string only once, determining efficiently the type and storing it in an efficient manner.</p>
<p>Consider the following example: </p><div class="fragment"><div class="line">{C++}</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> padded_string docdata = R&quot;([1.0, 3, 1, 3.1415,-13231232,9999999999999999999])&quot;_padded;</div>
<div class="line"> ondemand::document doc = parser.iterate(docdata);</div>
<div class="line"> ondemand::array arr = doc.get_array();</div>
<div class="line"> for(ondemand::value val : arr) {</div>
<div class="line"> std::cout &lt;&lt; val &lt;&lt; &quot; &quot;;</div>
<div class="line"> std::cout &lt;&lt; &quot;negative: &quot; &lt;&lt; val.is_negative() &lt;&lt; &quot; &quot;;</div>
<div class="line"> std::cout &lt;&lt; &quot;is_integer: &quot; &lt;&lt; val.is_integer() &lt;&lt; &quot; &quot;;</div>
<div class="line"> ondemand::number num = val.get_number();</div>
<div class="line"> ondemand::number_type t = num.get_number_type();</div>
<div class="line"> switch(t) {</div>
<div class="line"> case ondemand::number_type::signed_integer:</div>
<div class="line"> std::cout &lt;&lt; &quot;integer: &quot; &lt;&lt; int64_t(num) &lt;&lt; &quot; &quot;;</div>
<div class="line"> std::cout &lt;&lt; &quot;integer: &quot; &lt;&lt; num.get_int64() &lt;&lt; std::endl;</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::number_type::unsigned_integer:</div>
<div class="line"> std::cout &lt;&lt; &quot;large 64-bit integer: &quot; &lt;&lt; uint64_t(num) &lt;&lt; &quot; &quot;;</div>
<div class="line"> std::cout &lt;&lt; &quot;large 64-bit integer: &quot; &lt;&lt; num.get_uint64() &lt;&lt; std::endl;</div>
<div class="line"> break;</div>
<div class="line"> case ondemand::number_type::floating_point_number:</div>
<div class="line"> std::cout &lt;&lt; &quot;float: &quot; &lt;&lt; double(num) &lt;&lt; &quot; &quot;;</div>
<div class="line"> std::cout &lt;&lt; &quot;float: &quot; &lt;&lt; num.get_double() &lt;&lt; std::endl;</div>
<div class="line"> break;</div>
<div class="line"> }</div>
<div class="line"> }</div>
</div><!-- fragment --><p>It will output:</p>
<div class="fragment"><div class="line">1.0 negative: 0 is_integer: 0 float: 1 float: 1</div>
<div class="line">3 negative: 0 is_integer: 1 integer: 3 integer: 3</div>
<div class="line">1 negative: 0 is_integer: 1 integer: 1 integer: 1</div>
<div class="line">3.1415 negative: 0 is_integer: 0 float: 3.1415 float: 3.1415</div>
<div class="line">-13231232 negative: 1 is_integer: 1 integer: -13231232 integer: -13231232</div>
<div class="line">9999999999999999999 negative: 0 is_integer: 1 large 64-bit integer: 9999999999999999999 large 64-bit integer: 9999999999999999999</div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md24"></a>
Raw Strings</h1>
<p>It is sometimes useful to have access to a raw (unescaped) string: we make available a minimalist <code>raw_json_string</code> data type which contains a pointer inside the string in the original document, right after the quote. It is accessible via <code>get_raw_json_string()</code> on a string instance and returned by the <code>key()</code> method on an object's field instance. It is always optional: replacing <code>get_raw_json_string()</code> with <code>get_string()</code> and <code>key()</code> by <code>unescaped_key()</code> returns an <code>string_view</code> instance of the unescaped string.</p>
<p>You can quickly compare a <code>raw_json_string</code> instance with a target string. You may also unescape the <code>raw_json_string</code> on your own string buffer: <code>parser.unescape(mystr, ptr)</code> advances the provided pointer <code>ptr</code> and returns a string_view instance on the newly serialized string upon success, otherwise it returns an error. When unescaping to your own string buffer, you should ensure that you have sufficient memory space: the total size of the strings plus <code><a class="el" href="namespacesimdjson.html#aecdd750132f0eb123a6d61113b4197bf" title="The amount of padding needed in a buffer to parse JSON.">simdjson::SIMDJSON_PADDING</a></code> bytes. The following example illustrates how we can unescape JSON string to a user-provided buffer:</p>
<div class="fragment"><div class="line">{C++}</div>
<div class="line"> auto json = R&quot;( {&quot;name&quot;: &quot;Jack The Ripper \u0033&quot;} )&quot;_padded;</div>
<div class="line"> // We create a buffer large enough to store all strings we need:</div>
<div class="line"> std::unique_ptr&lt;uint8_t[]&gt; buffer(new uint8_t[json.size() + simdjson::SIMDJSON_PADDING]);</div>
<div class="line"> uint8_t * ptr = buffer.get();</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> ondemand::document doc = parser.iterate(json);</div>
<div class="line"> // We store our strings as &#39;string_view&#39; instances in a vector:</div>
<div class="line"> std::vector&lt;std::string_view&gt; mystrings;</div>
<div class="line"> for (auto key_value : doc.get_object()) {</div>
<div class="line"> std::string_view keysv = parser.unescape(key_value.key(), ptr);// writes &#39;name&#39;</div>
<div class="line"> mystrings.push_back(keysv);</div>
<div class="line"> std::string_view valuesv = parser.unescape(key_value.value().get_raw_json_string(), ptr);</div>
<div class="line"> // writes &#39;Jack The Ripper 3&#39;, escaping the \u0033</div>
<div class="line"> mystrings.push_back(valuesv);</div>
<div class="line"> }</div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md25"></a>
General Direct Access to the Raw JSON String</h1>
<p>If your value is a string, the <code>raw_json_string</code> gives you direct access to the unprocess string. The simdjson library allows you to have access to the raw underlying JSON more generally.</p>
<p>The simdjson library makes explicit assumptions about types. For examples, numbers must be integers (up to 64-bit integers) or binary64 floating-point numbers. Some users have different needs. For example, some users might want to support big integers. The library makes this possible by providing a <code>raw_json_token</code> method which returns a <code>std::string_view</code> instance containing the value as a string which you may then parse as you see fit.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">simdjson::ondemand::parser parser;</div>
<div class="line">simdjson::padded_string docdata = R&quot;({&quot;value&quot;:12321323213213213213213213213211223})&quot;_padded;</div>
<div class="line">simdjson::ondemand::document doc = parser.iterate(docdata);</div>
<div class="line">simdjson::ondemand::object obj = doc.get_object();</div>
<div class="line">std::string_view token = obj[&quot;value&quot;].raw_json_token();</div>
<div class="line">// token has value 12321323213213213213213213213211223, it points inside the input string</div>
</div><!-- fragment --><p>The <code>raw_json_token</code> method even works when the JSON value is a string. In such cases, it will return the complete string with the quotes and with eventual escaped sequences as in the source document.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">simdjson::ondemand::parser parser;</div>
<div class="line">simdjson::padded_string docdata = R&quot;({&quot;value&quot;:&quot;12321323213213213213213213213211223&quot;})&quot;_padded;</div>
<div class="line">simdjson::ondemand::document doc = parser.iterate(docdata);</div>
<div class="line">simdjson::ondemand::object obj = doc.get_object();</div>
<div class="line">string_view token = obj[&quot;value&quot;].raw_json_token();</div>
<div class="line">// token has value &quot;12321323213213213213213213213211223&quot;, it points inside the input string</div>
</div><!-- fragment --><p>The <code>raw_json_token()</code> should be fast and free of allocation.</p>
<p>If you value is an array or an object, <code>raw_json_token()</code> returns effectively a single character (<code>[</code>) or (<code>}</code>) which is not very useful. For arrays and objects, we have another method called <code>raw_json()</code> which consumes (traverse) the array or the object.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">simdjson::ondemand::parser parser;</div>
<div class="line">simdjson::padded_string docdata = R&quot;({&quot;value&quot;:123})&quot;_padded;</div>
<div class="line">simdjson::ondemand::document doc = parser.iterate(docdata);</div>
<div class="line">simdjson::ondemand::object obj = doc.get_object();</div>
<div class="line">string_view token = obj.raw_json(); // gives you `{&quot;value&quot;:123}`</div>
</div><!-- fragment --><div class="fragment"><div class="line"> {C++}</div>
<div class="line">simdjson::ondemand::parser parser;</div>
<div class="line">simdjson::padded_string docdata = R&quot;([1,2,3])&quot;_padded;</div>
<div class="line">simdjson::ondemand::document doc = parser.iterate(docdata);</div>
<div class="line">simdjson::ondemand::array arr = doc.get_array();</div>
<div class="line">string_view token = arr.raw_json(); // gives you `[1,2,3]`</div>
</div><!-- fragment --><p>Because <code>raw_json()</code> consumes to object or the array, if you want to both have access to the raw string, and also use the array or object, you should call <code>reset()</code>.</p>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">simdjson::ondemand::parser parser;</div>
<div class="line">simdjson::padded_string docdata = R&quot;({&quot;value&quot;:123})&quot;_padded;</div>
<div class="line">simdjson::ondemand::document doc = parser.iterate(docdata);</div>
<div class="line">simdjson::ondemand::object obj = doc.get_object();</div>
<div class="line">string_view token = obj.raw_json(); // gives you `{&quot;value&quot;:123}`</div>
<div class="line">obj.reset(); // revise the object</div>
<div class="line">uint64_t x = obj[&quot;value&quot;]; // gives me 123</div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md26"></a>
Thread Safety</h1>
<p>We built simdjson with thread safety in mind.</p>
<p>The simdjson library is single-threaded except for <a class="el" href="md_doc_iterate_many.html">`iterate_many`</a> and <a class="el" href="md_doc_parse_many.html">`parse_many`</a> which may use secondary threads under their control when the library is compiled with thread support.</p>
<p>We recommend using one <code>parser</code> object per thread. When using the On Demand front-end (our default), you should access the <code>document</code> instances in a single-threaded manner since it acts as an iterator (and is therefore not thread safe).</p>
<p>The CPU detection, which runs the first time parsing is attempted and switches to the fastest parser for your CPU, is transparent and thread-safe.</p>
<p>In a threaded environment, stack space is often limited. Running code like simdjson in debug mode may require hundreds of kilobytes of stack memory. Thus stack overflows are a possibility. We recommend you turn on optimization when working in an environment where stack space is limited. If you must run your code in debug mode, we recommend you configure your system to have more stack space. We discourage you from running production code based on a debug build.</p>
<h1><a class="anchor" id="autotoc_md27"></a>
Standard Compliance</h1>
<p>The simdjson library is fully compliant with the <a href="https://www.tbray.org/ongoing/When/201x/2017/12/14/rfc8259.html">RFC 8259</a> JSON specification.</p>
<ul>
<li>The only insignificant whitespace characters allowed are the space, the horizontal tab, the line feed and the carriage return. In particular, a JSON document may not contain an unescaped null character.</li>
<li>A single string or a single number is considered to be a valid JSON document.</li>
<li>We fully validate the numbers according to the JSON specification. For example, the string <code>01</code> is not valid JSON document since the specification states that <em>leading zeros are not allowed</em>.</li>
<li>The specification allows implementations to set limits on the range and precision of numbers accepted. We support 64-bit floating-point numbers as well as integer values.<ul>
<li>We parse integers and floating-point numbers as separate types which allows us to support all signed (two's complement) 64-bit integers, like a Java <code>long</code> or a C/C++ <code>long long</code> and all 64-bit unsigned integers. When we cannot represent exactly an integer as a signed or unsigned 64-bit value, we reject the JSON document.</li>
<li>We support the full range of 64-bit floating-point numbers (binary64). The values range from <code>std::numeric_limits&lt;double&gt;::lowest()</code> to <code>std::numeric_limits&lt;double&gt;::max()</code>, so from -1.7976e308 all the way to 1.7975e308. Extreme values (less or equal to -1e308, greater or equal to 1e308) are rejected: we refuse to parse the input document. Numbers are parsed with a perfect accuracy (ULP 0): the nearest floating-point value is chosen, rounding to even when needed. If you serialized your floating-point numbers with 17 significant digits in a standard compliant manner, the simdjson library is guaranteed to recover the same numbers, exactly.</li>
</ul>
</li>
<li>The specification states that JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8. The simdjson library does full UTF-8 validation as part of the parsing. The specification states that implementations MUST NOT add a byte order mark: the simdjson library rejects documents starting with a byte order mark.</li>
<li>The simdjson library validates string content for unescaped characters. Unescaped line breaks and tabs in strings are not allowed.</li>
<li>The simdjson library accepts objects with repeated keys: all of the name/value pairs, including duplicates, are reported. We do not enforce key uniqueness.</li>
<li>The specification states that an implementation may set limits on the size of texts that it accepts. The simdjson library limits single JSON documents to 4 GiB. It will refuse to parse a JSON document larger than 4294967295 bytes. (This limitation does not apply to streams of JSON documents, only to single JSON documents.)</li>
<li>The specification states that an implementation may set limits on the maximum depth of nesting. By default, the simdjson will refuse to parse documents with a depth exceeding 1024.</li>
</ul>
<h1><a class="anchor" id="autotoc_md28"></a>
Backwards Compatibility</h1>
<p>The only header file supported by simdjson is <code><a class="el" href="simdjson_8h.html">simdjson.h</a></code>. Older versions of simdjson published a number of other include files such as <code>document.h</code> or <code><a class="el" href="parsedjson_8h_source.html">ParsedJson.h</a></code> alongside <code><a class="el" href="simdjson_8h.html">simdjson.h</a></code>; these headers may be moved or removed in future versions.</p>
<h1><a class="anchor" id="autotoc_md29"></a>
Examples</h1>
<p>Some users like to have example. The following code samples illustrate how to process specific JSON inputs. For simplicity, we do not include full error support: this code would throw exceptions on error.</p>
<ul>
<li>Example 1: ZuluBBox</li>
</ul>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">struct ZuluBBox {</div>
<div class="line"> double xmin;</div>
<div class="line"> double ymin;</div>
<div class="line"> double width;</div>
<div class="line"> double height;</div>
<div class="line"> </div>
<div class="line"> void print() {</div>
<div class="line"> std::cout &lt;&lt; xmin &lt;&lt; &quot;, &quot; &lt;&lt; ymin &lt;&lt; &quot;, &quot; &lt;&lt; width &lt;&lt; &quot;, &quot; &lt;&lt; height</div>
<div class="line"> &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">bool example() {</div>
<div class="line"> </div>
<div class="line"> auto json = R&quot;+( {</div>
<div class="line"> &quot;ZuluROI&quot;: {</div>
<div class="line"> &quot;ZuluBBox&quot;: {</div>
<div class="line"> &quot;xmin&quot;: 0,</div>
<div class="line"> &quot;ymin&quot;: 0,</div>
<div class="line"> &quot;width&quot;: 1,</div>
<div class="line"> &quot;height&quot;: 1</div>
<div class="line"> },</div>
<div class="line"> &quot;SubObjects&quot;: [</div>
<div class="line"> {</div>
<div class="line"> &quot;ZuluDetection&quot;: {</div>
<div class="line"> &quot;label&quot;: &quot;car&quot;,</div>
<div class="line"> &quot;class_id&quot;: 3,</div>
<div class="line"> &quot;confidence&quot;: 0.7587034106254578,</div>
<div class="line"> &quot;ZuluBBox&quot;: {</div>
<div class="line"> &quot;xmin&quot;: 0.3843536376953125,</div>
<div class="line"> &quot;ymin&quot;: 0.4532909393310547,</div>
<div class="line"> &quot;width&quot;: 0.09115534275770187,</div>
<div class="line"> &quot;height&quot;: 0.04127710685133934</div>
<div class="line"> },</div>
<div class="line"> &quot;SubObjects&quot;: []</div>
<div class="line"> }</div>
<div class="line"> },</div>
<div class="line"> {</div>
<div class="line"> &quot;ZuluDetection&quot;: {</div>
<div class="line"> &quot;label&quot;: &quot;car&quot;,</div>
<div class="line"> &quot;class_id&quot;: 3,</div>
<div class="line"> &quot;confidence&quot;: 0.6718865633010864,</div>
<div class="line"> &quot;ZuluBBox&quot;: {</div>
<div class="line"> &quot;xmin&quot;: 0.7500002980232239,</div>
<div class="line"> &quot;ymin&quot;: 0.5212296843528748,</div>
<div class="line"> &quot;width&quot;: 0.07592231780290604,</div>
<div class="line"> &quot;height&quot;: 0.038947589695453644</div>
<div class="line"> },</div>
<div class="line"> &quot;SubObjects&quot;: []</div>
<div class="line"> }</div>
<div class="line"> },</div>
<div class="line"> {</div>
<div class="line"> &quot;ZuluDetection&quot;: {</div>
<div class="line"> &quot;label&quot;: &quot;car&quot;,</div>
<div class="line"> &quot;class_id&quot;: 3,</div>
<div class="line"> &quot;confidence&quot;: 0.5806200504302979,</div>
<div class="line"> &quot;ZuluBBox&quot;: {</div>
<div class="line"> &quot;xmin&quot;: 0.9025363922119141,</div>
<div class="line"> &quot;ymin&quot;: 0.5925348401069641,</div>
<div class="line"> &quot;width&quot;: 0.05478987470269203,</div>
<div class="line"> &quot;height&quot;: 0.046337299048900604</div>
<div class="line"> },</div>
<div class="line"> &quot;SubObjects&quot;: []</div>
<div class="line"> }</div>
<div class="line"> }</div>
<div class="line"> ]</div>
<div class="line"> },</div>
<div class="line"> &quot;timestamp (ms)&quot;: 1677085594421,</div>
<div class="line"> &quot;buffer_offset&quot;: 35673</div>
<div class="line">} )+&quot;_padded;</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> ondemand::document doc = parser.iterate(json);</div>
<div class="line"> ondemand::object root_object = doc.get_object();</div>
<div class="line"> ondemand::object roi_object = root_object[&quot;ZuluROI&quot;];</div>
<div class="line"> </div>
<div class="line"> ondemand::object box_roi_object = roi_object[&quot;ZuluBBox&quot;];</div>
<div class="line"> ZuluBBox box = {</div>
<div class="line"> double(box_roi_object[&quot;xmin&quot;]), double(box_roi_object[&quot;ymin&quot;]),</div>
<div class="line"> double(box_roi_object[&quot;width&quot;]), double(box_roi_object[&quot;height&quot;])};</div>
<div class="line"> box.print();</div>
<div class="line"> </div>
<div class="line"> for (ondemand::object value : roi_object[&quot;SubObjects&quot;]) {</div>
<div class="line"> ondemand::object detect = value[&quot;ZuluDetection&quot;];</div>
<div class="line"> std::cout &lt;&lt; detect[&quot;label&quot;].get_string() &lt;&lt; std::endl;</div>
<div class="line"> std::cout &lt;&lt; detect[&quot;class_id&quot;].get_uint64() &lt;&lt; std::endl;</div>
<div class="line"> std::cout &lt;&lt; detect[&quot;confidence&quot;].get_double() &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line"> ondemand::object vbox_roi_object = detect[&quot;ZuluBBox&quot;];</div>
<div class="line"> ZuluBBox vbox = {</div>
<div class="line"> double(vbox_roi_object[&quot;xmin&quot;]), double(vbox_roi_object[&quot;ymin&quot;]),</div>
<div class="line"> double(vbox_roi_object[&quot;width&quot;]), double(vbox_roi_object[&quot;height&quot;])};</div>
<div class="line"> vbox.print();</div>
<div class="line"> }</div>
<div class="line"> </div>
<div class="line"> std::cout &lt;&lt; root_object[&quot;timestamp (ms)&quot;].get_uint64() &lt;&lt; std::endl;</div>
<div class="line"> std::cout &lt;&lt; root_object[&quot;buffer_offset&quot;].get_uint64() &lt;&lt; std::endl;</div>
<div class="line"> return true;</div>
<div class="line">}</div>
</div><!-- fragment --><ul>
<li>Example 2: Demos</li>
</ul>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line">bool example() {</div>
<div class="line"> auto json = R&quot;+( {</div>
<div class="line"> &quot;5f08a730b280e54fd1e75a7046b93fdc&quot;: {</div>
<div class="line"> &quot;file&quot;: &quot;/DEMOS/0-9/10_Orbyte.sid&quot;,</div>
<div class="line"> &quot;len&quot;: [</div>
<div class="line"> &quot;1:17&quot;</div>
<div class="line"> ],</div>
<div class="line"> &quot;loud&quot;: [</div>
<div class="line"> &quot;-22.8&quot;</div>
<div class="line"> ],</div>
<div class="line"> &quot;name&quot;: &quot;10 Orbyte&quot;,</div>
<div class="line"> &quot;author&quot;: &quot;Michael Becker (Premium)&quot;,</div>
<div class="line"> &quot;release&quot;: &quot;2014 Tristar &amp; Red Sector Inc.&quot;,</div>
<div class="line"> &quot;bits&quot;: 20</div>
<div class="line"> },</div>
<div class="line"> &quot;2727236ead44a62f0c6e01f6dd4dc484&quot;: {</div>
<div class="line"> &quot;file&quot;: &quot;/DEMOS/0-9/12345.sid&quot;,</div>
<div class="line"> &quot;len&quot;: [</div>
<div class="line"> &quot;0:56&quot;</div>
<div class="line"> ],</div>
<div class="line"> &quot;loud&quot;: [</div>
<div class="line"> &quot;-33.3&quot;</div>
<div class="line"> ],</div>
<div class="line"> &quot;name&quot;: &quot;12345&quot;,</div>
<div class="line"> &quot;author&quot;: &quot;Beal&quot;,</div>
<div class="line"> &quot;release&quot;: &quot;1988 Beal&quot;,</div>
<div class="line"> &quot;bits&quot;: 20</div>
<div class="line"> },</div>
<div class="line"> &quot;7ea765fce6c0f92570b18adc7bf52f54&quot;: {</div>
<div class="line"> &quot;file&quot;: &quot;/DEMOS/0-9/128_Byte_Blues_BASIC.sid&quot;,</div>
<div class="line"> &quot;len&quot;: [</div>
<div class="line"> &quot;0:18&quot;</div>
<div class="line"> ],</div>
<div class="line"> &quot;loud&quot;: [</div>
<div class="line"> &quot;-27.1&quot;</div>
<div class="line"> ],</div>
<div class="line"> &quot;name&quot;: &quot;128 Byte Blues&quot;,</div>
<div class="line"> &quot;author&quot;: &quot;Leonard J. Paul (Freaky DNA)&quot;,</div>
<div class="line"> &quot;release&quot;: &quot;2005 Freaky DNA&quot;,</div>
<div class="line"> &quot;bits&quot;: 62</div>
<div class="line"> }</div>
<div class="line">} )+&quot;_padded;</div>
<div class="line"> ondemand::parser parser;</div>
<div class="line"> ondemand::document doc = parser.iterate(json);</div>
<div class="line"> ondemand::object root_object = doc.get_object();</div>
<div class="line"> for(auto key_value : root_object) {</div>
<div class="line"> // could get std::string_view with &#39;unescaped_key()&#39;:</div>
<div class="line"> std::cout &lt;&lt; &quot;key: &quot; &lt;&lt; key_value.key() &lt;&lt; std::endl;</div>
<div class="line"> ondemand::object obj = key_value.value();</div>
<div class="line"> </div>
<div class="line"> std::cout &lt;&lt; &quot;file: &quot; &lt;&lt; std::string_view(obj[&quot;file&quot;]) &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line"> std::cout &lt;&lt; &quot;len: &quot;;</div>
<div class="line"> for(std::string_view values : obj[&quot;len&quot;]) {</div>
<div class="line"> std::cout &lt;&lt; values &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line"> std::cout &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line"> std::cout &lt;&lt; &quot;loud: &quot;;</div>
<div class="line"> for(std::string_view values : obj[&quot;loud&quot;]) {</div>
<div class="line"> std::cout &lt;&lt; values &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line"> std::cout &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line"> std::cout &lt;&lt; &quot;name: &quot; &lt;&lt; std::string_view(obj[&quot;name&quot;]) &lt;&lt; std::endl;</div>
<div class="line"> std::cout &lt;&lt; &quot;author: &quot; &lt;&lt; std::string_view(obj[&quot;author&quot;]) &lt;&lt; std::endl;</div>
<div class="line"> std::cout &lt;&lt; &quot;release: &quot; &lt;&lt; std::string_view(obj[&quot;release&quot;]) &lt;&lt; std::endl;</div>
<div class="line"> std::cout &lt;&lt; &quot;bits: &quot; &lt;&lt; uint64_t(obj[&quot;bits&quot;]) &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line"> return true;</div>
<div class="line">}</div>
</div><!-- fragment --><ul>
<li>Example 3: CRT</li>
</ul>
<div class="fragment"><div class="line"> {C++}</div>
<div class="line"> </div>
<div class="line">bool example() {</div>
<div class="line"> padded_string padded_input_json = R&quot;([</div>
<div class="line"> { &quot;monitor&quot;: [</div>
<div class="line"> { &quot;id&quot;: &quot;monitor&quot;, &quot;type&quot;: &quot;toggle&quot;, &quot;label&quot;: &quot;monitor&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;profile&quot;, &quot;type&quot;: &quot;selector&quot;, &quot;label&quot;: &quot;collection&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;overlay&quot;, &quot;type&quot;: &quot;selector&quot;, &quot;label&quot;: &quot;overlay&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;zoom&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;zoom&quot; }</div>
<div class="line"> ] },</div>
<div class="line"> </div>
<div class="line"> { &quot;crt&quot;: [</div>
<div class="line"> { &quot;id&quot;: &quot;system&quot;, &quot;type&quot;: &quot;multi&quot;, &quot;label&quot;: &quot;system&quot;, &quot;choices&quot;: &quot;PAL, NTSC&quot; },</div>
<div class="line"> { &quot;type&quot;: &quot;spacer&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;brightness&quot;, &quot;type&quot;: &quot;slider&quot;, &quot;icon&quot;: &quot;brightness&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;contrast&quot;, &quot;type&quot;: &quot;slider&quot;, &quot;icon&quot;: &quot;contrast&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;saturation&quot;, &quot;type&quot;: &quot;slider&quot;, &quot;icon&quot;: &quot;saturation&quot; },</div>
<div class="line"> { &quot;type&quot;: &quot;spacer&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;overscan&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;overscan&quot; },</div>
<div class="line"> { &quot;type&quot;: &quot;spacer&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;emulation&quot;, &quot;type&quot;: &quot;toggle&quot;, &quot;label&quot;: &quot;CRT emulation&quot; },</div>
<div class="line"> { &quot;type&quot;: &quot;spacer&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;curve&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;curve&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;bleed&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;bleed&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;vignette&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;vignette&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;scanlines&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;scanlines&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;gridlines&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;gridlines&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;glow&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;glow&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;flicker&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;flicker&quot; },</div>
<div class="line"> { &quot;id&quot;: &quot;noise&quot;, &quot;type&quot;: &quot;toggleSlider&quot;, &quot;label&quot;: &quot;noise&quot; },</div>
<div class="line"> {}</div>
<div class="line"> ] }</div>
<div class="line">])&quot;_padded;</div>
<div class="line"> auto parser = ondemand::parser{};</div>
<div class="line"> auto doc = parser.iterate(padded_input_json);</div>
<div class="line"> auto root_array = doc.get_array();</div>
<div class="line"> // the root should be an object, not an array, but that&#39;s the JSON we are</div>
<div class="line"> // given.</div>
<div class="line"> for (ondemand::object node : root_array) {</div>
<div class="line"> // We know that we are going to have just one element in the object.</div>
<div class="line"> for (auto field : node) {</div>
<div class="line"> std::cout &lt;&lt; &quot;\n\ntop level:&quot; &lt;&lt; field.key() &lt;&lt; std::endl;</div>
<div class="line"> // You can get a proper std::string_view for the key with:</div>
<div class="line"> // std::string_view key = field.unescaped_key();</div>
<div class="line"> // and second for-range loop to get child-elements here</div>
<div class="line"> for (ondemand::object inner_object : field.value()) {</div>
<div class="line"> auto i = inner_object.begin();</div>
<div class="line"> if (i == inner_object.end()) {</div>
<div class="line"> std::cout &lt;&lt; &quot;empty object&quot; &lt;&lt; std::endl;</div>
<div class="line"> continue;</div>
<div class="line"> } else {</div>
<div class="line"> for (; i != inner_object.end(); ++i) {</div>
<div class="line"> auto inner_field = *i;</div>
<div class="line"> std::cout &lt;&lt; &#39;&quot;&#39; &lt;&lt; inner_field.key()</div>
<div class="line"> &lt;&lt; &quot;\&quot; : &quot; &lt;&lt; inner_field.value() &lt;&lt; &quot;, &quot;;</div>
<div class="line"> // You can get proper std::string_view for the key and value with:</div>
<div class="line"> // std::string_view inner_key = field.unescaped_key();</div>
<div class="line"> // std::string_view value_str = field.value();</div>
<div class="line"> }</div>
<div class="line"> }</div>
<div class="line"> std::cout &lt;&lt; std::endl;</div>
<div class="line"> }</div>
<div class="line"> // You can break here if you only want just the first element.</div>
<div class="line"> // break;</div>
<div class="line"> }</div>
<div class="line"> }</div>
<div class="line"> return true;</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md30"></a>
Performance Tips</h1>
<ul>
<li>The On Demand front-end works best when doing a single pass over the input: avoid calling <code>count_elements</code>, <code>rewind</code> and similar methods.</li>
<li>If you are familiar with assembly language, you may use the online tool godbolt to explore the compiled code. The following example may work: <a href="https://godbolt.org/z/xE4GWs573">https://godbolt.org/z/xE4GWs573</a>.</li>
<li>Given a field <code>field</code> in an object, calling <code>field.key()</code> is often faster than <code>field.unescaped_key()</code> so if you do not need an unescaped <code>std::string_view</code> instance, prefer <code>field.key()</code>.</li>
<li>For release builds, we recommend setting <code>NDEBUG</code> pre-processor directive when compiling the <code>simdjson</code> library. Importantly, using the optimization flags <code>-O2</code> or <code>-O3</code> under GCC and LLVM clang does not set the <code>NDEBUG</code> directive, you must set it manually (e.g., <code>-DNDEBUG</code>).</li>
<li>For long streams of JSON documents, consider <a class="el" href="md_doc_iterate_many.html">`iterate_many`</a> and <a class="el" href="md_doc_parse_many.html">`parse_many`</a> for better performance.</li>
<li>Never seek to access a field twice (e.g., o["data"] and later again o["data"]). Instead capture once an ondemand::value and reuse it.</li>
<li>If you must access several different keys in an object, it might be preferable to iterate through all the fields in the object instead, and branch on the field keys.</li>
<li>If possible, refer to each object and array in your code once. For example, the following code repeatedly refers to the <code>"data"</code> key to create an object... ```C++ std::string_view make = o["data"]["make"]; std::string_view model = o["data"]["model"]; std::string_view year = o["data"]["year"]; <div class="fragment"><div class="line">We expect that it is more efficient to access the `&quot;data&quot;` key once:</div>
<div class="line">```C++</div>
<div class="line"> simdjson::ondemand::object data = o[&quot;data&quot;];</div>
<div class="line"> std::string_view model = data[&quot;model&quot;];</div>
<div class="line"> std::string_view year = data[&quot;year&quot;];</div>
<div class="line"> std::string_view rating = data[&quot;rating&quot;];</div>
</div><!-- fragment --></li>
<li>To better understand the operation of your On Demand parser, and whether it is performing as well as you think it should be, there is a logger feature built in to simdjson! To use it, define the pre-processor directive <code>SIMDJSON_VERBOSE_LOGGING</code> prior to including the <code><a class="el" href="simdjson_8h.html">simdjson.h</a></code> header, which enables logging in simdjson. Run your code. It may generate a lot of logging output; adding printouts from your application that show each section may be helpful. The log's output will show step-by-step information on state, buffer pointer position, depth, and key retrieval status. Importantly, unless <code>SIMDJSON_VERBOSE_LOGGING</code> is defined, logging is entirely disabled and thus carries no overhead. </li>
</ul>
</div></div><!-- contents -->
</div><!-- PageDoc -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.1 </li>
</ul>
</div>
</body>
</html>