mirror of
https://github.com/nlohmann/json
synced 2024-11-23 20:40:08 +00:00
1 line
1016 KiB
JSON
1 line
1016 KiB
JSON
{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"JSON for Modern C++","text":""},{"location":"api/json/","title":"nlohmann::json","text":"<pre><code>using json = basic_json<>;\n</code></pre> <p>This type is the default specialization of the basic_json class which uses the standard template types.</p>"},{"location":"api/json/#examples","title":"Examples","text":"Example <p>The example below demonstrates how to use the type <code>nlohmann::json</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j =\n {\n {\"pi\", 3.141},\n {\"happy\", true},\n {\"name\", \"Niels\"},\n {\"nothing\", nullptr},\n {\n \"answer\", {\n {\"everything\", 42}\n }\n },\n {\"list\", {1, 0, 2}},\n {\n \"object\", {\n {\"currency\", \"USD\"},\n {\"value\", 42.99}\n }\n }\n };\n\n // add new values\n j[\"new\"][\"key\"][\"value\"] = {\"another\", \"list\"};\n\n // count elements\n auto s = j.size();\n j[\"size\"] = s;\n\n // pretty print with indent of 4 spaces\n std::cout << std::setw(4) << j << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"answer\": {\n \"everything\": 42\n },\n \"happy\": true,\n \"list\": [\n 1,\n 0,\n 2\n ],\n \"name\": \"Niels\",\n \"new\": {\n \"key\": {\n \"value\": [\n \"another\",\n \"list\"\n ]\n }\n },\n \"nothing\": null,\n \"object\": {\n \"currency\": \"USD\",\n \"value\": 42.99\n },\n \"pi\": 3.141,\n \"size\": 8\n}\n</code></pre>"},{"location":"api/json/#version-history","title":"Version history","text":"<p>Since version 1.0.0.</p>"},{"location":"api/operator_gtgt/","title":"nlohmann::operator>>(basic_json)","text":"<pre><code>std::istream& operator>>(std::istream& i, basic_json& j);\n</code></pre> <p>Deserializes an input stream to a JSON value.</p>"},{"location":"api/operator_gtgt/#parameters","title":"Parameters","text":"<code>i</code> (in, out) input stream to read a serialized JSON value from <code>j</code> (in, out) JSON value to write the deserialized input to"},{"location":"api/operator_gtgt/#return-value","title":"Return value","text":"<p>the stream <code>i</code></p>"},{"location":"api/operator_gtgt/#exceptions","title":"Exceptions","text":"<ul> <li>Throws <code>parse_error.101</code> in case of an unexpected token.</li> <li>Throws <code>parse_error.102</code> if to_unicode fails or surrogate error.</li> <li>Throws <code>parse_error.103</code> if to_unicode fails.</li> </ul>"},{"location":"api/operator_gtgt/#complexity","title":"Complexity","text":"<p>Linear in the length of the input. The parser is a predictive LL(1) parser.</p>"},{"location":"api/operator_gtgt/#notes","title":"Notes","text":"<p>A UTF-8 byte order mark is silently ignored.</p> <p>Deprecation</p> <p>This function replaces function <code>std::istream& operator<<(basic_json& j, std::istream& i)</code> which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like <code>j << i;</code> with <code>i >> j;</code>.</p>"},{"location":"api/operator_gtgt/#examples","title":"Examples","text":"Example <p>The example below shows how a JSON value is constructed by reading a serialization from a stream.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create stream with serialized JSON\n std::stringstream ss;\n ss << R\"({\n \"number\": 23,\n \"string\": \"Hello, world!\",\n \"array\": [1, 2, 3, 4, 5],\n \"boolean\": false,\n \"null\": null\n })\";\n\n // create JSON value and read the serialization from the stream\n json j;\n ss >> j;\n\n // serialize JSON\n std::cout << std::setw(2) << j << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"array\": [\n 1,\n 2,\n 3,\n 4,\n 5\n ],\n \"boolean\": false,\n \"null\": null,\n \"number\": 23,\n \"string\": \"Hello, world!\"\n}\n</code></pre>"},{"location":"api/operator_gtgt/#see-also","title":"See also","text":"<ul> <li>accept - check if the input is valid JSON</li> <li>parse - deserialize from a compatible input</li> </ul>"},{"location":"api/operator_gtgt/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0. Deprecated in version 3.0.0.</li> </ul>"},{"location":"api/operator_literal_json/","title":"nlohmann::operator\"\"_json","text":"<pre><code>json operator \"\"_json(const char* s, std::size_t n);\n</code></pre> <p>This operator implements a user-defined string literal for JSON objects. It can be used by adding <code>_json</code> to a string literal and returns a <code>json</code> object if no parse error occurred.</p> <p>It is recommended to bring the operator into scope using any of the following lines: <pre><code>using nlohmann::literals::operator \"\"_json;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n</code></pre></p> <p>This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.</p>"},{"location":"api/operator_literal_json/#parameters","title":"Parameters","text":"<code>s</code> (in) a string representation of a JSON object <code>n</code> (in) length of string <code>s</code>"},{"location":"api/operator_literal_json/#return-value","title":"Return value","text":"<p><code>json</code> value parsed from <code>s</code></p>"},{"location":"api/operator_literal_json/#exceptions","title":"Exceptions","text":"<p>The function can throw anything that <code>parse(s, s+n)</code> would throw.</p>"},{"location":"api/operator_literal_json/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/operator_literal_json/#examples","title":"Examples","text":"Example <p>The following code shows how to create JSON values from string literals.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n json j = R\"( {\"hello\": \"world\", \"answer\": 42} )\"_json;\n\n std::cout << std::setw(2) << j << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"answer\": 42,\n \"hello\": \"world\"\n}\n</code></pre>"},{"location":"api/operator_literal_json/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Moved to namespace <code>nlohmann::literals::json_literals</code> in 3.11.0.</li> </ul>"},{"location":"api/operator_literal_json_pointer/","title":"nlohmann::operator\"\"_json_pointer","text":"<pre><code>json_pointer operator \"\"_json_pointer(const char* s, std::size_t n);\n</code></pre> <p>This operator implements a user-defined string literal for JSON Pointers. It can be used by adding <code>_json_pointer</code> to a string literal and returns a <code>json_pointer</code> object if no parse error occurred.</p> <p>It is recommended to bring the operator into scope using any of the following lines: <pre><code>using nlohmann::literals::operator \"\"_json_pointer;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n</code></pre> This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.</p>"},{"location":"api/operator_literal_json_pointer/#parameters","title":"Parameters","text":"<code>s</code> (in) a string representation of a JSON Pointer <code>n</code> (in) length of string <code>s</code>"},{"location":"api/operator_literal_json_pointer/#return-value","title":"Return value","text":"<p><code>json_pointer</code> value parsed from <code>s</code></p>"},{"location":"api/operator_literal_json_pointer/#exceptions","title":"Exceptions","text":"<p>The function can throw anything that <code>json_pointer::json_pointer</code> would throw.</p>"},{"location":"api/operator_literal_json_pointer/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/operator_literal_json_pointer/#examples","title":"Examples","text":"Example <p>The following code shows how to create JSON Pointers from string literals.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n json j = R\"( {\"hello\": \"world\", \"answer\": 42} )\"_json;\n auto val = j[\"/hello\"_json_pointer];\n\n std::cout << std::setw(2) << val << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>\"world\"\n</code></pre>"},{"location":"api/operator_literal_json_pointer/#see-also","title":"See also","text":"<ul> <li>json_pointer - type to represent JSON Pointers</li> </ul>"},{"location":"api/operator_literal_json_pointer/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> <li>Moved to namespace <code>nlohmann::literals::json_literals</code> in 3.11.0.</li> </ul>"},{"location":"api/operator_ltlt/","title":"nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)","text":"<pre><code>std::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)\n</code></pre> <ol> <li>Serialize the given JSON value <code>j</code> to the output stream <code>o</code>. The JSON value will be serialized using the <code>dump</code> member function.<ul> <li>The indentation of the output can be controlled with the member variable <code>width</code> of the output stream <code>o</code>. For instance, using the manipulator <code>std::setw(4)</code> on <code>o</code> sets the indentation level to <code>4</code> and the serialization result is the same as calling <code>dump(4)</code>.</li> <li>The indentation character can be controlled with the member variable <code>fill</code> of the output stream <code>o</code>. For instance, the manipulator <code>std::setfill('\\\\t')</code> sets indentation to use a tab character rather than the default space character.</li> </ul> </li> <li>Write a string representation of the given JSON pointer <code>ptr</code> to the output stream <code>o</code>. The string representation is obtained using the <code>to_string</code> member function.</li> </ol>"},{"location":"api/operator_ltlt/#parameters","title":"Parameters","text":"<code>o</code> (in, out) stream to write to <code>j</code> (in) JSON value to serialize <code>ptr</code> (in) JSON pointer to write"},{"location":"api/operator_ltlt/#return-value","title":"Return value","text":"<p>the stream <code>o</code></p>"},{"location":"api/operator_ltlt/#exceptions","title":"Exceptions","text":"<ol> <li>Throws <code>type_error.316</code> if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike the <code>dump</code> member functions, no <code>error_handler</code> can be set.</li> <li>None.</li> </ol>"},{"location":"api/operator_ltlt/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/operator_ltlt/#notes","title":"Notes","text":"<p>Deprecation</p> <p>Function <code>std::ostream& operator<<(std::ostream& o, const basic_json& j)</code> replaces function <code>std::ostream& operator>>(const basic_json& j, std::ostream& o)</code> which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like <code>j >> o;</code> with <code>o << j;</code>.</p>"},{"location":"api/operator_ltlt/#examples","title":"Examples","text":"Example: (1) serialize JSON value to stream <p>The example below shows the serialization with different parameters to <code>width</code> to adjust the indentation level.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // serialize without indentation\n std::cout << j_object << \"\\n\\n\";\n std::cout << j_array << \"\\n\\n\";\n\n // serialize with indentation\n std::cout << std::setw(4) << j_object << \"\\n\\n\";\n std::cout << std::setw(2) << j_array << \"\\n\\n\";\n std::cout << std::setw(1) << std::setfill('\\t') << j_object << \"\\n\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\n\n[1,2,4,8,16]\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\n{\n \"one\": 1,\n \"two\": 2\n}\n</code></pre> Example: (2) write JSON pointer to stream <p>The example below shows how to write a JSON pointer to a stream.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON poiner\n json::json_pointer ptr(\"/foo/bar/baz\");\n\n // write string representation to stream\n std::cout << ptr << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>/foo/bar/baz\n</code></pre>"},{"location":"api/operator_ltlt/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Added support for indentation character and deprecated <code>std::ostream& operator>>(const basic_json& j, std::ostream& o)</code> in version 3.0.0.</li> <li>Added in version 3.11.0.</li> </ol>"},{"location":"api/ordered_json/","title":"nlohmann::ordered_json","text":"<pre><code>using ordered_json = basic_json<ordered_map>;\n</code></pre> <p>This type preserves the insertion order of object keys.</p>"},{"location":"api/ordered_json/#examples","title":"Examples","text":"Example <p>The example below demonstrates how <code>ordered_json</code> preserves the insertion order of object keys.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing ordered_json = nlohmann::ordered_json;\n\nint main()\n{\n ordered_json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n</code></pre>"},{"location":"api/ordered_json/#see-also","title":"See also","text":"<ul> <li>ordered_map</li> <li>Object Order</li> </ul>"},{"location":"api/ordered_json/#version-history","title":"Version history","text":"<p>Since version 3.9.0.</p>"},{"location":"api/ordered_map/","title":"nlohmann::ordered_map","text":"<pre><code>template<class Key, class T, class IgnoredLess = std::less<Key>,\n class Allocator = std::allocator<std::pair<const Key, T>>>\nstruct ordered_map : std::vector<std::pair<const Key, T>, Allocator>;\n</code></pre> <p>A minimal map-like container that preserves insertion order for use within <code>nlohmann::ordered_json</code> (<code>nlohmann::basic_json<ordered_map></code>).</p>"},{"location":"api/ordered_map/#template-parameters","title":"Template parameters","text":"<code>Key</code> key type <code>T</code> mapped type <code>IgnoredLess</code> comparison function (ignored and only added to ensure compatibility with <code>std::map</code>) <code>Allocator</code> allocator type"},{"location":"api/ordered_map/#member-types","title":"Member types","text":"<ul> <li>key_type - key type (<code>Key</code>)</li> <li>mapped_type - mapped type (<code>T</code>)</li> <li>Container - base container type (<code>std::vector<std::pair<const Key, T>, Allocator></code>)</li> <li>iterator</li> <li>const_iterator</li> <li>size_type</li> <li>value_type</li> <li>key_compare - key comparison function <pre><code>std::equal_to<Key> // until C++14\n\nstd::equal_to<> // since C++14\n</code></pre></li> </ul>"},{"location":"api/ordered_map/#member-functions","title":"Member functions","text":"<ul> <li>(constructor)</li> <li>(destructor)</li> <li>emplace</li> <li>operator[]</li> <li>at</li> <li>erase</li> <li>count</li> <li>find</li> <li>insert</li> </ul>"},{"location":"api/ordered_map/#examples","title":"Examples","text":"Example <p>The example shows the different behavior of <code>std::map</code> and <code>nlohmann::ordered_map</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// simple output function\ntemplate<typename Map>\nvoid output(const char* prefix, const Map& m)\n{\n std::cout << prefix << \" = { \";\n for (auto& element : m)\n {\n std::cout << element.first << \":\" << element.second << ' ';\n }\n std::cout << \"}\" << std::endl;\n}\n\nint main()\n{\n // create and fill two maps\n nlohmann::ordered_map<std::string, std::string> m_ordered;\n m_ordered[\"one\"] = \"eins\";\n m_ordered[\"two\"] = \"zwei\";\n m_ordered[\"three\"] = \"drei\";\n\n std::map<std::string, std::string> m_std;\n m_std[\"one\"] = \"eins\";\n m_std[\"two\"] = \"zwei\";\n m_std[\"three\"] = \"drei\";\n\n // output: m_ordered is ordered by insertion order, m_std is ordered by key\n output(\"m_ordered\", m_ordered);\n output(\"m_std\", m_std);\n\n // erase and re-add \"one\" key\n m_ordered.erase(\"one\");\n m_ordered[\"one\"] = \"eins\";\n\n m_std.erase(\"one\");\n m_std[\"one\"] = \"eins\";\n\n // output: m_ordered shows newly added key at the end; m_std is again ordered by key\n output(\"m_ordered\", m_ordered);\n output(\"m_std\", m_std);\n}\n</code></pre> <p>Output:</p> <pre><code>m_ordered = { one:eins two:zwei three:drei }\nm_std = { one:eins three:drei two:zwei }\nm_ordered = { two:zwei three:drei one:eins }\nm_std = { one:eins three:drei two:zwei }\n</code></pre>"},{"location":"api/ordered_map/#see-also","title":"See also","text":"<ul> <li>ordered_json</li> </ul>"},{"location":"api/ordered_map/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.9.0 to implement <code>nlohmann::ordered_json</code>.</li> <li>Added key_compare member in version 3.11.0.</li> </ul>"},{"location":"api/adl_serializer/","title":"nlohmann::adl_serializer","text":"<pre><code>template<typename, typename>\nstruct adl_serializer;\n</code></pre> <p>Serializer that uses ADL (Argument-Dependent Lookup) to choose <code>to_json</code>/<code>from_json</code> functions from the types' namespaces.</p> <p>It is implemented similar to</p> <pre><code>template<typename ValueType>\nstruct adl_serializer {\n template<typename BasicJsonType>\n static void to_json(BasicJsonType& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n template<typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n</code></pre>"},{"location":"api/adl_serializer/#member-functions","title":"Member functions","text":"<ul> <li>from_json - convert a JSON value to any value type</li> <li>to_json - convert any value type to a JSON value</li> </ul>"},{"location":"api/adl_serializer/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.1.0.</li> </ul>"},{"location":"api/adl_serializer/from_json/","title":"nlohmann::adl_serializer::from_json","text":"<pre><code>// (1)\ntemplate<typename BasicJsonType, typename TargetType = ValueType>\nstatic auto from_json(BasicJsonType && j, TargetType& val) noexcept(\n noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))\n-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())\n\n// (2)\ntemplate<typename BasicJsonType, typename TargetType = ValueType>\nstatic auto from_json(BasicJsonType && j) noexcept(\nnoexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))\n-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))\n</code></pre> <p>This function is usually called by the <code>get()</code> function of the basic_json class (either explicitly or via the conversion operators).</p> <ol> <li>This function is chosen for default-constructible value types.</li> <li>This function is chosen for value types which are not default-constructible.</li> </ol>"},{"location":"api/adl_serializer/from_json/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON value to read from <code>val</code> (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"<p>Copy of the JSON value, converted to <code>ValueType</code></p>"},{"location":"api/adl_serializer/from_json/#examples","title":"Examples","text":"Example: (1) Default-constructible type <p>The example below shows how a <code>from_json</code> function can be implemented for a user-defined type. This function is called by the <code>adl_serializer</code> when <code>template get<ns::person>()</code> is called.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid from_json(const json& j, person& p)\n{\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n}\n} // namespace ns\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>Ned Flanders (60) lives in 744 Evergreen Terrace\n</code></pre> Example: (2) Non-default-constructible type <p>The example below shows how a <code>from_json</code> is implemented as part of a specialization of the <code>adl_serializer</code> to realize the conversion of a non-default-constructible type.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>Ned Flanders (60) lives in 744 Evergreen Terrace\n</code></pre>"},{"location":"api/adl_serializer/from_json/#see-also","title":"See also","text":"<ul> <li>to_json</li> </ul>"},{"location":"api/adl_serializer/from_json/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.1.0.</li> </ul>"},{"location":"api/adl_serializer/to_json/","title":"nlohmann::adl_serializer::to_json","text":"<pre><code>template<typename BasicJsonType, typename TargetType = ValueType>\nstatic auto to_json(BasicJsonType& j, TargetType && val) noexcept(\n noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))\n-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())\n</code></pre> <p>This function is usually called by the constructors of the basic_json class.</p>"},{"location":"api/adl_serializer/to_json/#parameters","title":"Parameters","text":"<code>j</code> (out) JSON value to write to <code>val</code> (in) value to read from"},{"location":"api/adl_serializer/to_json/#examples","title":"Examples","text":"Example <p>The example below shows how a <code>to_json</code> function can be implemented for a user-defined type. This function is called by the <code>adl_serializer</code> when the constructor <code>basic_json(ns::person)</code> is called.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid to_json(json& j, const person& p)\n{\n j = json{ {\"name\", p.name}, {\"address\", p.address}, {\"age\", p.age} };\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n json j = p;\n\n std::cout << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n</code></pre>"},{"location":"api/adl_serializer/to_json/#see-also","title":"See also","text":"<ul> <li>from_json</li> </ul>"},{"location":"api/adl_serializer/to_json/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.1.0.</li> </ul>"},{"location":"api/basic_json/","title":"nlohmann::basic_json","text":"<p>Defined in header <code><nlohmann/json.hpp></code></p> <pre><code>template<\n template<typename U, typename V, typename... Args> class ObjectType = std::map,\n template<typename U, typename... Args> class ArrayType = std::vector,\n class StringType = std::string,\n class BooleanType = bool,\n class NumberIntegerType = std::int64_t,\n class NumberUnsignedType = std::uint64_t,\n class NumberFloatType = double,\n template<typename U> class AllocatorType = std::allocator,\n template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,\n class BinaryType = std::vector<std::uint8_t>,\n class CustomBaseClass = void\n>\nclass basic_json;\n</code></pre>"},{"location":"api/basic_json/#template-parameters","title":"Template parameters","text":"Template parameter Description Derived type <code>ObjectType</code> type for JSON objects <code>object_t</code> <code>ArrayType</code> type for JSON arrays <code>array_t</code> <code>StringType</code> type for JSON strings and object keys <code>string_t</code> <code>BooleanType</code> type for JSON booleans <code>boolean_t</code> <code>NumberIntegerType</code> type for JSON integer numbers <code>number_integer_t</code> <code>NumberUnsignedType</code> type for JSON unsigned integer numbers <code>number_unsigned_t</code> <code>NumberFloatType</code> type for JSON floating-point numbers <code>number_float_t</code> <code>AllocatorType</code> type of the allocator to use <code>JSONSerializer</code> the serializer to resolve internal calls to <code>to_json()</code> and <code>from_json()</code> <code>json_serializer</code> <code>BinaryType</code> type for binary arrays <code>binary_t</code> <code>CustomBaseClass</code> extension point for user code <code>json_base_class_t</code>"},{"location":"api/basic_json/#specializations","title":"Specializations","text":"<ul> <li>json - default specialization</li> <li>ordered_json - specialization that maintains the insertion order of object keys</li> </ul>"},{"location":"api/basic_json/#iterator-invalidation","title":"Iterator invalidation","text":"<p>Todo</p>"},{"location":"api/basic_json/#requirements","title":"Requirements","text":"<p>The class satisfies the following concept requirements:</p>"},{"location":"api/basic_json/#basic","title":"Basic","text":"<ul> <li>DefaultConstructible: JSON values can be default constructed. The result will be a JSON null value.</li> <li>MoveConstructible: A JSON value can be constructed from an rvalue argument.</li> <li>CopyConstructible: A JSON value can be copy-constructed from an lvalue expression.</li> <li>MoveAssignable: A JSON value can be assigned from an rvalue argument.</li> <li>CopyAssignable: A JSON value can be copy-assigned from an lvalue expression.</li> <li>Destructible: JSON values can be destructed.</li> </ul>"},{"location":"api/basic_json/#layout","title":"Layout","text":"<ul> <li>StandardLayoutType: JSON values have standard layout: All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes.</li> </ul>"},{"location":"api/basic_json/#library-wide","title":"Library-wide","text":"<ul> <li>EqualityComparable: JSON values can be compared with <code>==</code>, see <code>operator==</code>.</li> <li>LessThanComparable: JSON values can be compared with <code><</code>, see <code>operator<</code>.</li> <li>Swappable: Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function <code>swap</code>.</li> <li>NullablePointer: JSON values can be compared against <code>std::nullptr_t</code> objects which are used to model the <code>null</code> value.</li> </ul>"},{"location":"api/basic_json/#container","title":"Container","text":"<ul> <li>Container: JSON values can be used like STL containers and provide iterator access.</li> <li>ReversibleContainer: JSON values can be used like STL containers and provide reverse iterator access.</li> </ul>"},{"location":"api/basic_json/#member-types","title":"Member types","text":"<ul> <li>adl_serializer - the default serializer</li> <li>value_t - the JSON type enumeration</li> <li>json_pointer - JSON Pointer implementation</li> <li>json_serializer - type of the serializer to for conversions from/to JSON</li> <li>error_handler_t - type to choose behavior on decoding errors</li> <li>cbor_tag_handler_t - type to choose how to handle CBOR tags</li> <li>initializer_list_t - type for initializer lists of <code>basic_json</code> values</li> <li>input_format_t - type to choose the format to parse</li> <li>json_sax_t - type for SAX events</li> </ul>"},{"location":"api/basic_json/#exceptions","title":"Exceptions","text":"<ul> <li>exception - general exception of the <code>basic_json</code> class<ul> <li>parse_error - exception indicating a parse error</li> <li>invalid_iterator - exception indicating errors with iterators</li> <li>type_error - exception indicating executing a member function with a wrong type</li> <li>out_of_range - exception indicating access out of the defined range</li> <li>other_error - exception indicating other library errors</li> </ul> </li> </ul>"},{"location":"api/basic_json/#container-types","title":"Container types","text":"Type Definition <code>value_type</code> <code>basic_json</code> <code>reference</code> <code>value_type&</code> <code>const_reference</code> <code>const value_type&</code> <code>difference_type</code> <code>std::ptrdiff_t</code> <code>size_type</code> <code>std::size_t</code> <code>allocator_type</code> <code>AllocatorType<basic_json></code> <code>pointer</code> <code>std::allocator_traits<allocator_type>::pointer</code> <code>const_pointer</code> <code>std::allocator_traits<allocator_type>::const_pointer</code> <code>iterator</code> LegacyBidirectionalIterator <code>const_iterator</code> constant LegacyBidirectionalIterator <code>reverse_iterator</code> reverse iterator, derived from <code>iterator</code> <code>const_reverse_iterator</code> reverse iterator, derived from <code>const_iterator</code> <code>iteration_proxy</code> helper type for <code>items</code> function"},{"location":"api/basic_json/#json-value-data-types","title":"JSON value data types","text":"<ul> <li>array_t - type for arrays</li> <li>binary_t - type for binary arrays</li> <li>boolean_t - type for booleans</li> <li>default_object_comparator_t - default comparator for objects</li> <li>number_float_t - type for numbers (floating-point)</li> <li>number_integer_t - type for numbers (integer)</li> <li>number_unsigned_t - type for numbers (unsigned)</li> <li>object_comparator_t - comparator for objects</li> <li>object_t - type for objects</li> <li>string_t - type for strings</li> </ul>"},{"location":"api/basic_json/#parser-callback","title":"Parser callback","text":"<ul> <li>parse_event_t - parser event types</li> <li>parser_callback_t - per-element parser callback type</li> </ul>"},{"location":"api/basic_json/#member-functions","title":"Member functions","text":"<ul> <li>(constructor)</li> <li>(destructor)</li> <li>operator= - copy assignment</li> <li>array (static) - explicitly create an array</li> <li>binary (static) - explicitly create a binary array</li> <li>object (static) - explicitly create an object</li> </ul>"},{"location":"api/basic_json/#object-inspection","title":"Object inspection","text":"<p>Functions to inspect the type of a JSON value.</p> <ul> <li>type - return the type of the JSON value</li> <li>operator value_t - return the type of the JSON value</li> <li>type_name - return the type as string</li> <li>is_primitive - return whether type is primitive</li> <li>is_structured - return whether type is structured</li> <li>is_null - return whether value is null</li> <li>is_boolean - return whether value is a boolean</li> <li>is_number - return whether value is a number</li> <li>is_number_integer - return whether value is an integer number</li> <li>is_number_unsigned - return whether value is an unsigned integer number</li> <li>is_number_float - return whether value is a floating-point number</li> <li>is_object - return whether value is an object</li> <li>is_array - return whether value is an array</li> <li>is_string - return whether value is a string</li> <li>is_binary - return whether value is a binary array</li> <li>is_discarded - return whether value is discarded</li> </ul>"},{"location":"api/basic_json/#value-access","title":"Value access","text":"<p>Direct access to the stored value of a JSON value.</p> <ul> <li>get - get a value</li> <li>get_to - get a value and write it to a destination</li> <li>get_ptr - get a pointer value</li> <li>get_ref - get a reference value</li> <li>operator ValueType - get a value</li> <li>get_binary - get a binary value</li> </ul>"},{"location":"api/basic_json/#element-access","title":"Element access","text":"<p>Access to the JSON value</p> <ul> <li>at - access specified element with bounds checking</li> <li>operator[] - access specified element</li> <li>value - access specified object element with default value</li> <li>front - access the first element</li> <li>back - access the last element</li> </ul>"},{"location":"api/basic_json/#lookup","title":"Lookup","text":"<ul> <li>find - find an element in a JSON object</li> <li>count - returns the number of occurrences of a key in a JSON object</li> <li>contains - check the existence of an element in a JSON object</li> </ul>"},{"location":"api/basic_json/#iterators","title":"Iterators","text":"<ul> <li>begin - returns an iterator to the first element</li> <li>cbegin - returns a const iterator to the first element</li> <li>end - returns an iterator to one past the last element</li> <li>cend - returns a const iterator to one past the last element</li> <li>rbegin - returns an iterator to the reverse-beginning</li> <li>rend - returns an iterator to the reverse-end</li> <li>crbegin - returns a const iterator to the reverse-beginning</li> <li>crend - returns a const iterator to the reverse-end</li> <li>items - wrapper to access iterator member functions in range-based for</li> </ul>"},{"location":"api/basic_json/#capacity","title":"Capacity","text":"<ul> <li>empty - checks whether the container is empty</li> <li>size - returns the number of elements</li> <li>max_size - returns the maximum possible number of elements</li> </ul>"},{"location":"api/basic_json/#modifiers","title":"Modifiers","text":"<ul> <li>clear - clears the contents</li> <li>push_back - add a value to an array/object</li> <li>operator+= - add a value to an array/object</li> <li>emplace_back - add a value to an array</li> <li>emplace - add a value to an object if key does not exist</li> <li>erase - remove elements</li> <li>insert - inserts elements</li> <li>update - updates a JSON object from another object, overwriting existing keys </li> <li>swap - exchanges the values</li> </ul>"},{"location":"api/basic_json/#lexicographical-comparison-operators","title":"Lexicographical comparison operators","text":"<ul> <li>operator== - comparison: equal</li> <li>operator!= - comparison: not equal</li> <li>operator< - comparison: less than</li> <li>operator> - comparison: greater than</li> <li>operator<= - comparison: less than or equal</li> <li>operator>= - comparison: greater than or equal</li> <li>operator<=> - comparison: 3-way</li> </ul>"},{"location":"api/basic_json/#serialization-dumping","title":"Serialization / Dumping","text":"<ul> <li>dump - serialization</li> </ul>"},{"location":"api/basic_json/#deserialization-parsing","title":"Deserialization / Parsing","text":"<ul> <li>parse (static) - deserialize from a compatible input</li> <li>accept (static) - check if the input is valid JSON</li> <li>sax_parse (static) - generate SAX events</li> </ul>"},{"location":"api/basic_json/#json-pointer-functions","title":"JSON Pointer functions","text":"<ul> <li>flatten - return flattened JSON value</li> <li>unflatten - unflatten a previously flattened JSON value</li> </ul>"},{"location":"api/basic_json/#json-patch-functions","title":"JSON Patch functions","text":"<ul> <li>patch - applies a JSON patch</li> <li>patch_inplace - applies a JSON patch in place</li> <li>diff (static) - creates a diff as a JSON patch</li> </ul>"},{"location":"api/basic_json/#json-merge-patch-functions","title":"JSON Merge Patch functions","text":"<ul> <li>merge_patch - applies a JSON Merge Patch</li> </ul>"},{"location":"api/basic_json/#static-functions","title":"Static functions","text":"<ul> <li>meta - returns version information on the library</li> <li>get_allocator - returns the allocator associated with the container</li> </ul>"},{"location":"api/basic_json/#binary-formats","title":"Binary formats","text":"<ul> <li>from_bjdata (static) - create a JSON value from an input in BJData format</li> <li>from_bson (static) - create a JSON value from an input in BSON format</li> <li>from_cbor (static) - create a JSON value from an input in CBOR format</li> <li>from_msgpack (static) - create a JSON value from an input in MessagePack format</li> <li>from_ubjson (static) - create a JSON value from an input in UBJSON format</li> <li>to_bjdata (static) - create a BJData serialization of a given JSON value</li> <li>to_bson (static) - create a BSON serialization of a given JSON value</li> <li>to_cbor (static) - create a CBOR serialization of a given JSON value</li> <li>to_msgpack (static) - create a MessagePack serialization of a given JSON value</li> <li>to_ubjson (static) - create a UBJSON serialization of a given JSON value</li> </ul>"},{"location":"api/basic_json/#non-member-functions","title":"Non-member functions","text":"<ul> <li>operator<<(std::ostream&) - serialize to stream</li> <li>operator>>(std::istream&) - deserialize from stream</li> <li>to_string - user-defined <code>to_string</code> function for JSON values</li> </ul>"},{"location":"api/basic_json/#literals","title":"Literals","text":"<ul> <li>operator\"\"_json - user-defined string literal for JSON values</li> </ul>"},{"location":"api/basic_json/#helper-classes","title":"Helper classes","text":"<ul> <li>std::hash<basic_json> - return a hash value for a JSON object</li> <li>std::swap<basic_json> - exchanges the values of two JSON objects</li> </ul>"},{"location":"api/basic_json/#examples","title":"Examples","text":"Example <p>The example shows how the library is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j =\n {\n {\"pi\", 3.141},\n {\"happy\", true},\n {\"name\", \"Niels\"},\n {\"nothing\", nullptr},\n {\n \"answer\", {\n {\"everything\", 42}\n }\n },\n {\"list\", {1, 0, 2}},\n {\n \"object\", {\n {\"currency\", \"USD\"},\n {\"value\", 42.99}\n }\n }\n };\n\n // add new values\n j[\"new\"][\"key\"][\"value\"] = {\"another\", \"list\"};\n\n // count elements\n auto s = j.size();\n j[\"size\"] = s;\n\n // pretty print with indent of 4 spaces\n std::cout << std::setw(4) << j << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"answer\": {\n \"everything\": 42\n },\n \"happy\": true,\n \"list\": [\n 1,\n 0,\n 2\n ],\n \"name\": \"Niels\",\n \"new\": {\n \"key\": {\n \"value\": [\n \"another\",\n \"list\"\n ]\n }\n },\n \"nothing\": null,\n \"object\": {\n \"currency\": \"USD\",\n \"value\": 42.99\n },\n \"pi\": 3.141,\n \"size\": 8\n}\n</code></pre>"},{"location":"api/basic_json/#see-also","title":"See also","text":"<ul> <li>RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format</li> </ul>"},{"location":"api/basic_json/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/accept/","title":"nlohmann::basic_json::accept","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic bool accept(InputType&& i,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic bool accept(IteratorType first, IteratorType last,\n const bool ignore_comments = false);\n</code></pre> <p>Checks whether the input is valid JSON.</p> <ol> <li>Reads from a compatible input.</li> <li> <p>Reads from a pair of character iterators</p> <p>The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.</p> </li> </ol> <p>Unlike the <code>parse</code> function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.</p>"},{"location":"api/basic_json/accept/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer (must not be null)</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>a <code>std::string</code></li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> <p>a compatible iterator type, for instance.</p> <ul> <li>a pair of <code>std::string::iterator</code> or <code>std::vector<std::uint8_t>::iterator</code></li> <li>a pair of pointers such as <code>ptr</code> and <code>ptr + len</code></li> </ul>"},{"location":"api/basic_json/accept/#parameters","title":"Parameters","text":"<code>i</code> (in) Input to parse from. <code>ignore_comments</code> (in) whether comments should be ignored and treated like whitespace (<code>true</code>) or yield a parse error (<code>false</code>); (optional, <code>false</code> by default) <code>first</code> (in) iterator to start of character range <code>last</code> (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"<p>Whether the input is valid JSON.</p>"},{"location":"api/basic_json/accept/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/accept/#complexity","title":"Complexity","text":"<p>Linear in the length of the input. The parser is a predictive LL(1) parser.</p>"},{"location":"api/basic_json/accept/#notes","title":"Notes","text":"<p>(1) A UTF-8 byte order mark is silently ignored.</p> <p>Runtime assertion</p> <p>The precondition that a passed <code>FILE</code> pointer must not be null is enforced with a runtime assertion.</p>"},{"location":"api/basic_json/accept/#examples","title":"Examples","text":"Example <p>The example below demonstrates the <code>accept()</code> function reading from a string.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a valid JSON text\n auto valid_text = R\"(\n {\n \"numbers\": [1, 2, 3]\n }\n )\";\n\n // an invalid JSON text\n auto invalid_text = R\"(\n {\n \"strings\": [\"extra\", \"comma\", ]\n }\n )\";\n\n std::cout << std::boolalpha\n << json::accept(valid_text) << ' '\n << json::accept(invalid_text) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true false\n</code></pre>"},{"location":"api/basic_json/accept/#see-also","title":"See also","text":"<ul> <li>parse - deserialize from a compatible input</li> <li>operator>> - deserialize from stream</li> </ul>"},{"location":"api/basic_json/accept/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.0.0.</li> <li>Ignoring comments via <code>ignore_comments</code> added in version 3.9.0.</li> </ul> <p>Deprecation</p> <p>Overload (2) replaces calls to <code>accept</code> with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>accept({ptr, ptr+len}, ...);</code> with <code>accept(ptr, ptr+len, ...);</code>.</p> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/array/","title":"nlohmann::basic_json::array","text":"<pre><code>static basic_json array(initializer_list_t init = {});\n</code></pre> <p>Creates a JSON array value from a given initializer list. That is, given a list of values <code>a, b, c</code>, creates the JSON value <code>[a, b, c]</code>. If the initializer list is empty, the empty array <code>[]</code> is created.</p>"},{"location":"api/basic_json/array/#parameters","title":"Parameters","text":"<code>init</code> (in) initializer list with JSON values to create an array from (optional)"},{"location":"api/basic_json/array/#return-value","title":"Return value","text":"<p>JSON array value</p>"},{"location":"api/basic_json/array/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/array/#complexity","title":"Complexity","text":"<p>Linear in the size of <code>init</code>.</p>"},{"location":"api/basic_json/array/#notes","title":"Notes","text":"<p>This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (<code>basic_json(initializer_list_t, bool, value_t)</code>). These cases are:</p> <ol> <li>creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys</li> <li>creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object</li> </ol>"},{"location":"api/basic_json/array/#examples","title":"Examples","text":"Example <p>The following code shows an example for the <code>array</code> function.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON arrays\n json j_no_init_list = json::array();\n json j_empty_init_list = json::array({});\n json j_nonempty_init_list = json::array({1, 2, 3, 4});\n json j_list_of_pairs = json::array({ {\"one\", 1}, {\"two\", 2} });\n\n // serialize the JSON arrays\n std::cout << j_no_init_list << '\\n';\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_nonempty_init_list << '\\n';\n std::cout << j_list_of_pairs << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[]\n[]\n[1,2,3,4]\n[[\"one\",1],[\"two\",2]]\n</code></pre>"},{"location":"api/basic_json/array/#see-also","title":"See also","text":"<ul> <li><code>basic_json(initializer_list_t)</code> - create a JSON value from an initializer list</li> <li><code>object</code> - create a JSON object value from an initializer list</li> </ul>"},{"location":"api/basic_json/array/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/array_t/","title":"nlohmann::basic_json::array_t","text":"<pre><code>using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n</code></pre> <p>The type used to store JSON arrays.</p> <p>RFC 8259 describes JSON arrays as follows:</p> <p>An array is an ordered sequence of zero or more values.</p> <p>To store objects in C++, a type is defined by the template parameters explained below.</p>"},{"location":"api/basic_json/array_t/#template-parameters","title":"Template parameters","text":"<code>ArrayType</code> container type to store arrays (e.g., <code>std::vector</code> or <code>std::list</code>) <code>AllocatorType</code> the allocator to use for objects (e.g., <code>std::allocator</code>)"},{"location":"api/basic_json/array_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/array_t/#default-type","title":"Default type","text":"<p>With the default values for <code>ArrayType</code> (<code>std::vector</code>) and <code>AllocatorType</code> (<code>std::allocator</code>), the default value for <code>array_t</code> is:</p> <pre><code>std::vector<\n basic_json, // value_type\n std::allocator<basic_json> // allocator_type\n>\n</code></pre>"},{"location":"api/basic_json/array_t/#limits","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the maximum depth of nesting.</p> <p>In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the <code>max_size</code> function of a JSON array.</p>"},{"location":"api/basic_json/array_t/#storage","title":"Storage","text":"<p>Arrays are stored as pointers in a <code>basic_json</code> type. That is, for any access to array values, a pointer of type <code>array_t*</code> must be dereferenced.</p>"},{"location":"api/basic_json/array_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>array_t</code> is by default, a typedef to <code>std::vector<nlohmann::json></code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::vector<json>, json::array_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/array_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/at/","title":"nlohmann::basic_json::at","text":"<pre><code>// (1)\nreference at(size_type idx);\nconst_reference at(size_type idx) const;\n\n// (2)\nreference at(const typename object_t::key_type& key);\nconst_reference at(const typename object_t::key_type& key) const;\n\n// (3)\ntemplate<typename KeyType>\nreference at(KeyType&& key);\ntemplate<typename KeyType>\nconst_reference at(KeyType&& key) const;\n\n// (4)\nreference at(const json_pointer& ptr);\nconst_reference at(const json_pointer& ptr) const;\n</code></pre> <ol> <li>Returns a reference to the array element at specified location <code>idx</code>, with bounds checking.</li> <li>Returns a reference to the object element with specified key <code>key</code>, with bounds checking.</li> <li>See 2. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</li> <li>Returns a reference to the element at specified JSON pointer <code>ptr</code>, with bounds checking.</li> </ol>"},{"location":"api/basic_json/at/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17)."},{"location":"api/basic_json/at/#parameters","title":"Parameters","text":"<code>idx</code> (in) index of the element to access <code>key</code> (in) object key of the elements to access <code>ptr</code> (in) JSON pointer to the desired element"},{"location":"api/basic_json/at/#return-value","title":"Return value","text":"<ol> <li>reference to the element at index <code>idx</code></li> <li>reference to the element at key <code>key</code></li> <li>reference to the element at key <code>key</code></li> <li>reference to the element pointed to by <code>ptr</code></li> </ol>"},{"location":"api/basic_json/at/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/at/#exceptions","title":"Exceptions","text":"<ol> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.304</code> if the JSON value is not an array; in this case, calling <code>at</code> with an index makes no sense. See example below.</li> <li>Throws <code>out_of_range.401</code> if the index <code>idx</code> is out of range of the array; that is, <code>idx >= size()</code>. See example below.</li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.304</code> if the JSON value is not an object; in this case, calling <code>at</code> with a key makes no sense. See example below.</li> <li>Throws <code>out_of_range.403</code> if the key <code>key</code> is not stored in the object; that is, <code>find(key) == end()</code>. See example below.</li> </ul> </li> <li>See 2.</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>parse_error.106</code> if an array index in the passed JSON pointer <code>ptr</code> begins with '0'. See example below.</li> <li>Throws <code>parse_error.109</code> if an array index in the passed JSON pointer <code>ptr</code> is not a number. See example below.</li> <li>Throws <code>out_of_range.401</code> if an array index in the passed JSON pointer <code>ptr</code> is out of range. See example below.</li> <li>Throws <code>out_of_range.402</code> if the array index '-' is used in the passed JSON pointer <code>ptr</code>. As <code>at</code> provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.</li> <li>Throws <code>out_of_range.403</code> if the JSON pointer describes a key of an object which cannot be found. See example below.</li> <li>Throws <code>out_of_range.404</code> if the JSON pointer <code>ptr</code> can not be resolved. See example below.</li> </ul> </li> </ol>"},{"location":"api/basic_json/at/#complexity","title":"Complexity","text":"<ol> <li>Constant.</li> <li>Logarithmic in the size of the container.</li> <li>Logarithmic in the size of the container.</li> <li>Logarithmic in the size of the container.</li> </ol>"},{"location":"api/basic_json/at/#examples","title":"Examples","text":"Example: (1) access specified array element with bounds checking <p>The example below shows how array elements can be read and written using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n\n // change element at index 1 (second element) to \"second\"\n array.at(1) = \"second\";\n\n // output changed array\n std::cout << array << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-array type\n json str = \"I am a string\";\n str.at(0) = \"Another string\";\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to write beyond the array limit\n array.at(5) = \"sixth\";\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"third\"\n[\"first\",\"second\",\"third\",\"fourth\"]\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n</code></pre> Example: (1) access specified array element with bounds checking <p>The example below shows how array elements can be read using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-array type\n const json str = \"I am a string\";\n std::cout << str.at(0) << '\\n';\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to read beyond the array limit\n std::cout << array.at(5) << '\\n';\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"third\"\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n</code></pre> Example: (2) access specified object element with bounds checking <p>The example below shows how object elements can be read and written using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON object\n json object =\n {\n {\"the good\", \"il buono\"},\n {\"the bad\", \"il cattivo\"},\n {\"the ugly\", \"il brutto\"}\n };\n\n // output element with key \"the ugly\"\n std::cout << object.at(\"the ugly\") << '\\n';\n\n // change element with key \"the bad\"\n object.at(\"the bad\") = \"il cattivo\";\n\n // output changed array\n std::cout << object << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-object type\n json str = \"I am a string\";\n str.at(\"the good\") = \"Another string\";\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to write at a nonexisting key\n object.at(\"the fast\") = \"il rapido\";\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"il brutto\"\n{\"the bad\":\"il cattivo\",\"the good\":\"il buono\",\"the ugly\":\"il brutto\"}\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.403] key 'the fast' not found\n</code></pre> Example: (2) access specified object element with bounds checking <p>The example below shows how object elements can be read using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON object\n const json object =\n {\n {\"the good\", \"il buono\"},\n {\"the bad\", \"il cattivo\"},\n {\"the ugly\", \"il brutto\"}\n };\n\n // output element with key \"the ugly\"\n std::cout << object.at(\"the ugly\") << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-object type\n const json str = \"I am a string\";\n std::cout << str.at(\"the good\") << '\\n';\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to read from a nonexisting key\n std::cout << object.at(\"the fast\") << '\\n';\n }\n catch (const json::out_of_range)\n {\n std::cout << \"out of range\" << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"il brutto\"\n[json.exception.type_error.304] cannot use at() with string\nout of range\n</code></pre> Example: (3) access specified object element using string_view with bounds checking <p>The example below shows how object elements can be read and written using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON object\n json object =\n {\n {\"the good\", \"il buono\"},\n {\"the bad\", \"il cattivo\"},\n {\"the ugly\", \"il brutto\"}\n };\n\n // output element with key \"the ugly\" using string_view\n std::cout << object.at(\"the ugly\"sv) << '\\n';\n\n // change element with key \"the bad\" using string_view\n object.at(\"the bad\"sv) = \"il cattivo\";\n\n // output changed array\n std::cout << object << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() with string_view on a non-object type\n json str = \"I am a string\";\n str.at(\"the good\"sv) = \"Another string\";\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to write at a nonexisting key using string_view\n object.at(\"the fast\"sv) = \"il rapido\";\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"il brutto\"\n{\"the bad\":\"il cattivo\",\"the good\":\"il buono\",\"the ugly\":\"il brutto\"}\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.403] key 'the fast' not found\n</code></pre> Example: (3) access specified object element using string_view with bounds checking <p>The example below shows how object elements can be read using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON object\n const json object =\n {\n {\"the good\", \"il buono\"},\n {\"the bad\", \"il cattivo\"},\n {\"the ugly\", \"il brutto\"}\n };\n\n // output element with key \"the ugly\" using string_view\n std::cout << object.at(\"the ugly\"sv) << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() with string_view on a non-object type\n const json str = \"I am a string\";\n std::cout << str.at(\"the good\"sv) << '\\n';\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to read from a nonexisting key using string_view\n std::cout << object.at(\"the fast\"sv) << '\\n';\n }\n catch (const json::out_of_range& e)\n {\n std::cout << \"out of range\" << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"il brutto\"\n[json.exception.type_error.304] cannot use at() with string\nout of range\n</code></pre> Example: (4) access specified element via JSON Pointer <p>The example below shows how object elements can be read and written using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j.at(\"/number\"_json_pointer) << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j.at(\"/string\"_json_pointer) << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j.at(\"/array\"_json_pointer) << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j.at(\"/array/1\"_json_pointer) << '\\n';\n\n // writing access\n\n // change the string\n j.at(\"/string\"_json_pointer) = \"bar\";\n // output the changed string\n std::cout << j[\"string\"] << '\\n';\n\n // change an array element\n j.at(\"/array/1\"_json_pointer) = 21;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n\n // out_of_range.106\n try\n {\n // try to use an array index with leading '0'\n json::reference ref = j.at(\"/array/01\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.109\n try\n {\n // try to use an array index that is not a number\n json::reference ref = j.at(\"/array/one\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.401\n try\n {\n // try to use an invalid array index\n json::reference ref = j.at(\"/array/4\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.402\n try\n {\n // try to use the array index '-'\n json::reference ref = j.at(\"/array/-\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.403\n try\n {\n // try to use a JSON pointer to a nonexistent object key\n json::const_reference ref = j.at(\"/foo\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.404\n try\n {\n // try to use a JSON pointer that cannot be resolved\n json::reference ref = j.at(\"/number/foo\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>1\n\"foo\"\n[1,2]\n2\n\"bar\"\n[1,21]\n[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n[json.exception.parse_error.109] parse error: array index 'one' is not a number\n[json.exception.out_of_range.401] array index 4 is out of range\n[json.exception.out_of_range.402] array index '-' (2) is out of range\n[json.exception.out_of_range.403] key 'foo' not found\n[json.exception.out_of_range.404] unresolved reference token 'foo'\n</code></pre> Example: (4) access specified element via JSON Pointer <p>The example below shows how object elements can be read using <code>at()</code>. It also demonstrates the different exceptions that can be thrown.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n const json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j.at(\"/number\"_json_pointer) << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j.at(\"/string\"_json_pointer) << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j.at(\"/array\"_json_pointer) << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j.at(\"/array/1\"_json_pointer) << '\\n';\n\n // out_of_range.109\n try\n {\n // try to use an array index that is not a number\n json::const_reference ref = j.at(\"/array/one\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.401\n try\n {\n // try to use an invalid array index\n json::const_reference ref = j.at(\"/array/4\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.402\n try\n {\n // try to use the array index '-'\n json::const_reference ref = j.at(\"/array/-\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.403\n try\n {\n // try to use a JSON pointer to a nonexistent object key\n json::const_reference ref = j.at(\"/foo\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // out_of_range.404\n try\n {\n // try to use a JSON pointer that cannot be resolved\n json::const_reference ref = j.at(\"/number/foo\"_json_pointer);\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>1\n\"foo\"\n[1,2]\n2\n[json.exception.parse_error.109] parse error: array index 'one' is not a number\n[json.exception.out_of_range.401] array index 4 is out of range\n[json.exception.out_of_range.402] array index '-' (2) is out of range\n[json.exception.out_of_range.403] key 'foo' not found\n[json.exception.out_of_range.404] unresolved reference token 'foo'\n</code></pre>"},{"location":"api/basic_json/at/#see-also","title":"See also","text":"<ul> <li>documentation on checked access</li> <li>see <code>operator[]</code> for unchecked access by reference</li> <li>see <code>value</code> for access with default value</li> </ul>"},{"location":"api/basic_json/at/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0.</li> <li>Added in version 1.0.0.</li> <li>Added in version 3.11.0.</li> <li>Added in version 2.0.0.</li> </ol>"},{"location":"api/basic_json/back/","title":"nlohmann::basic_json::back","text":"<pre><code>reference back();\n\nconst_reference back() const;\n</code></pre> <p>Returns a reference to the last element in the container. For a JSON container <code>c</code>, the expression <code>c.back()</code> is equivalent to</p> <pre><code>auto tmp = c.end();\n--tmp;\nreturn *tmp;\n</code></pre>"},{"location":"api/basic_json/back/#return-value","title":"Return value","text":"<p>In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.</p>"},{"location":"api/basic_json/back/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/back/#exceptions","title":"Exceptions","text":"<p>If the JSON value is <code>null</code>, exception <code>invalid_iterator.214</code> is thrown.</p>"},{"location":"api/basic_json/back/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/back/#notes","title":"Notes","text":"<p>Precondition</p> <p>The array or object must not be empty. Calling <code>back</code> on an empty array or object yields undefined behavior.</p>"},{"location":"api/basic_json/back/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>back()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call back()\n std::cout << j_boolean.back() << '\\n';\n std::cout << j_number_integer.back() << '\\n';\n std::cout << j_number_float.back() << '\\n';\n std::cout << j_object.back() << '\\n';\n //std::cout << j_object_empty.back() << '\\n'; // undefined behavior\n std::cout << j_array.back() << '\\n';\n //std::cout << j_array_empty.back() << '\\n'; // undefined behavior\n std::cout << j_string.back() << '\\n';\n\n // back() called on a null value\n try\n {\n json j_null;\n j_null.back();\n }\n catch (const json::invalid_iterator& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>true\n17\n23.42\n2\n16\n\"Hello, world\"\n[json.exception.invalid_iterator.214] cannot get value\n</code></pre>"},{"location":"api/basic_json/back/#see-also","title":"See also","text":"<ul> <li>front to access the first element</li> </ul>"},{"location":"api/basic_json/back/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Adjusted code to return reference to binary values in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/basic_json/","title":"nlohmann::basic_json::basic_json","text":"<pre><code>// (1)\nbasic_json(const value_t v);\n\n// (2)\nbasic_json(std::nullptr_t = nullptr) noexcept;\n\n// (3)\ntemplate<typename CompatibleType>\nbasic_json(CompatibleType&& val) noexcept(noexcept(\n JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),\n std::forward<CompatibleType>(val))));\n\n// (4)\ntemplate<typename BasicJsonType>\nbasic_json(const BasicJsonType& val);\n\n// (5)\nbasic_json(initializer_list_t init,\n bool type_deduction = true,\n value_t manual_type = value_t::array);\n\n// (6)\nbasic_json(size_type cnt, const basic_json& val);\n\n// (7)\nbasic_json(iterator first, iterator last);\nbasic_json(const_iterator first, const_iterator last);\n\n// (8)\nbasic_json(const basic_json& other);\n\n// (9)\nbasic_json(basic_json&& other) noexcept;\n</code></pre> <ol> <li> <p>Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:</p> Value type initial value null <code>null</code> boolean <code>false</code> string <code>\"\"</code> number <code>0</code> object <code>{}</code> array <code>[]</code> binary empty array <p>The postcondition of this constructor can be restored by calling <code>clear()</code>.</p> </li> <li> <p>Create a <code>null</code> JSON value. It either takes a null pointer as parameter (explicitly creating <code>null</code>) or no parameter (implicitly creating <code>null</code>). The passed null pointer itself is not read -- it is only used to choose the right constructor.</p> </li> <li> <p>This is a \"catch all\" constructor for all compatible JSON types; that is, types for which a <code>to_json()</code> method exists. The constructor forwards the parameter <code>val</code> to that method (to <code>json_serializer<U>::to_json</code> method with <code>U = uncvref_t<CompatibleType></code>, to be exact).</p> <p>Template type <code>CompatibleType</code> includes, but is not limited to, the following types:</p> <ul> <li>arrays: <code>array_t</code> and all kinds of compatible containers such as <code>std::vector</code>, <code>std::deque</code>, <code>std::list</code>, <code>std::forward_list</code>, <code>std::array</code>, <code>std::valarray</code>, <code>std::set</code>, <code>std::unordered_set</code>, <code>std::multiset</code>, and <code>std::unordered_multiset</code> with a <code>value_type</code> from which a <code>basic_json</code> value can be constructed.</li> <li>objects: <code>object_t</code> and all kinds of compatible associative containers such as <code>std::map</code>, <code>std::unordered_map</code>, <code>std::multimap</code>, and <code>std::unordered_multimap</code> with a <code>key_type</code> compatible to <code>string_t</code> and a <code>value_type</code> from which a <code>basic_json</code> value can be constructed.</li> <li>strings: <code>string_t</code>, string literals, and all compatible string containers can be used.</li> <li>numbers: <code>number_integer_t</code>, <code>number_unsigned_t</code>, <code>number_float_t</code>, and all convertible number types such as <code>int</code>, <code>size_t</code>, <code>int64_t</code>, <code>float</code> or <code>double</code> can be used.</li> <li>boolean: <code>boolean_t</code> / <code>bool</code> can be used.</li> <li>binary: <code>binary_t</code> / <code>std::vector<uint8_t></code> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with <code>const char*</code> will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type.</li> </ul> <p>See the examples below.</p> </li> <li> <p>This is a constructor for existing <code>basic_json</code> types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones.</p> <p>The constructor tries to convert the internal <code>m_value</code> of the parameter.</p> </li> <li> <p>Creates a JSON value of type array or object from the passed initializer list <code>init</code>. In case <code>type_deduction</code> is <code>true</code> (default), the type of the JSON value to be created is deducted from the initializer list <code>init</code> according to the following rules:</p> <ol> <li>If the list is empty, an empty JSON object value <code>{}</code> is created.</li> <li>If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values.</li> <li>In all other cases, an array is created.</li> </ol> <p>The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:</p> <ol> <li>The empty initializer list is written as <code>{}</code> which is exactly an empty JSON object.</li> <li>C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object.</li> <li>In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe.</li> </ol> <p>With the rules described above, the following JSON values cannot be expressed by an initializer list:</p> <ul> <li>the empty array (<code>[]</code>): use <code>array(initializer_list_t)</code> with an empty initializer list in this case</li> <li>arrays whose elements satisfy rule 2: use <code>array(initializer_list_t)</code> with the same initializer list in this case</li> </ul> <p>Function <code>array()</code> and <code>object()</code> force array and object creation from initializer lists, respectively.</p> </li> <li> <p>Constructs a JSON array value by creating <code>cnt</code> copies of a passed value. In case <code>cnt</code> is <code>0</code>, an empty array is created.</p> </li> <li> <p>Constructs the JSON value with the contents of the range <code>[first, last)</code>. The semantics depends on the different types a JSON value can have:</p> <ul> <li>In case of a <code>null</code> type, invalid_iterator.206 is thrown.</li> <li>In case of other primitive types (number, boolean, or string), <code>first</code> must be <code>begin()</code> and <code>last</code> must be <code>end()</code>. In this case, the value is copied. Otherwise, <code>invalid_iterator.204</code> is thrown.</li> <li>In case of structured types (array, object), the constructor behaves as similar versions for <code>std::vector</code> or <code>std::map</code>; that is, a JSON array or object is constructed from the values in the range.</li> </ul> </li> <li> <p>Creates a copy of a given JSON value.</p> </li> <li> <p>Move constructor. Constructs a JSON value with the contents of the given value <code>other</code> using move semantics. It \"steals\" the resources from <code>other</code> and leaves it as JSON <code>null</code> value.</p> </li> </ol>"},{"location":"api/basic_json/basic_json/#template-parameters","title":"Template parameters","text":"<code>CompatibleType</code> <p>a type such that:</p> <ul> <li><code>CompatibleType</code> is not derived from <code>std::istream</code>,</li> <li><code>CompatibleType</code> is not <code>basic_json</code> (to avoid hijacking copy/move constructors),</li> <li><code>CompatibleType</code> is not a different <code>basic_json</code> type (i.e. with different template arguments)</li> <li><code>CompatibleType</code> is not a <code>basic_json</code> nested type (e.g., <code>json_pointer</code>, <code>iterator</code>, etc.)</li> <li><code>json_serializer<U></code> (with <code>U = uncvref_t<CompatibleType></code>) has a <code>to_json(basic_json_t&, CompatibleType&&)</code> method</li> </ul> <code>BasicJsonType</code>: <p>a type such that:</p> <ul> <li><code>BasicJsonType</code> is a <code>basic_json</code> type.</li> <li><code>BasicJsonType</code> has different template arguments than <code>basic_json_t</code>.</li> </ul> <code>U</code>: <code>uncvref_t<CompatibleType></code>"},{"location":"api/basic_json/basic_json/#parameters","title":"Parameters","text":"<code>v</code> (in) the type of the value to create <code>val</code> (in) the value to be forwarded to the respective constructor <code>init</code> (in) initializer list with JSON values <code>type_deduction</code> (in) internal parameter; when set to <code>true</code>, the type of the JSON value is deducted from the initializer list <code>init</code>; when set to <code>false</code>, the type provided via <code>manual_type</code> is forced. This mode is used by the functions <code>array(initializer_list_t)</code> and <code>object(initializer_list_t)</code>. <code>manual_type</code> (in) internal parameter; when <code>type_deduction</code> is set to <code>false</code>, the created JSON value will use the provided type (only <code>value_t::array</code> and <code>value_t::object</code> are valid); when <code>type_deduction</code> is set to <code>true</code>, this parameter has no effect <code>cnt</code> (in) the number of JSON copies of <code>val</code> to create <code>first</code> (in) begin of the range to copy from (included) <code>last</code> (in) end of the range to copy from (excluded) <code>other</code> (in) the JSON value to copy/move"},{"location":"api/basic_json/basic_json/#exception-safety","title":"Exception safety","text":"<ol> <li>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</li> <li>No-throw guarantee: this constructor never throws exceptions.</li> <li>Depends on the called constructor. For types directly supported by the library (i.e., all types for which no <code>to_json()</code> function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.</li> <li>Depends on the called constructor. For types directly supported by the library (i.e., all types for which no <code>to_json()</code> function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.</li> <li>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</li> <li>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</li> <li>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</li> <li>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</li> <li>No-throw guarantee: this constructor never throws exceptions.</li> </ol>"},{"location":"api/basic_json/basic_json/#exceptions","title":"Exceptions","text":"<ol> <li>(none)</li> <li>The function does not throw exceptions.</li> <li>(none)</li> <li>(none)</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.301</code> if <code>type_deduction</code> is <code>false</code>, <code>manual_type</code> is <code>value_t::object</code>, but <code>init</code> contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If <code>type_deduction</code> would have been <code>true</code>, an array would have been created. See <code>object(initializer_list_t)</code> for an example.</li> </ul> </li> <li>(none)</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>invalid_iterator.201</code> if iterators <code>first</code> and <code>last</code> are not compatible (i.e., do not belong to the same JSON value). In this case, the range <code>[first, last)</code> is undefined.</li> <li>Throws <code>invalid_iterator.204</code> if iterators <code>first</code> and <code>last</code> belong to a primitive type (number, boolean, or string), but <code>first</code> does not point to the first element anymore. In this case, the range <code>[first, last)</code> is undefined. See example code below.</li> <li>Throws <code>invalid_iterator.206</code> if iterators <code>first</code> and <code>last</code> belong to a <code>null</code> value. In this case, the range <code>[first, last)</code> is undefined.</li> </ul> </li> <li>(none)</li> <li>The function does not throw exceptions.</li> </ol>"},{"location":"api/basic_json/basic_json/#complexity","title":"Complexity","text":"<ol> <li>Constant.</li> <li>Constant.</li> <li>Usually linear in the size of the passed <code>val</code>, also depending on the implementation of the called <code>to_json()</code> method.</li> <li>Usually linear in the size of the passed <code>val</code>, also depending on the implementation of the called <code>to_json()</code> method.</li> <li>Linear in the size of the initializer list <code>init</code>.</li> <li>Linear in <code>cnt</code>.</li> <li>Linear in distance between <code>first</code> and <code>last</code>.</li> <li>Linear in the size of <code>other</code>.</li> <li>Constant.</li> </ol>"},{"location":"api/basic_json/basic_json/#notes","title":"Notes","text":"<ul> <li> <p>Overload 5:</p> <p>Empty initializer list</p> <p>When used without parentheses around an empty initializer list, <code>basic_json()</code> is called instead of this function, yielding the JSON <code>null</code> value.</p> </li> <li> <p>Overload 7:</p> <p>Preconditions</p> <ul> <li>Iterators <code>first</code> and <code>last</code> must be initialized. **This precondition is enforced with a runtime assertion.</li> <li>Range <code>[first, last)</code> is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior.</li> </ul> <p>Runtime assertion</p> <p>A precondition is enforced with a runtime assertion.</p> </li> <li> <p>Overload 8:</p> <p>Postcondition</p> <p><code>*this == other</code></p> </li> <li> <p>Overload 9:</p> <p>Postconditions</p> <ul> <li><code>`*this</code> has the same value as <code>other</code> before the call.</li> <li><code>other</code> is a JSON <code>null</code> value</li> </ul> </li> </ul>"},{"location":"api/basic_json/basic_json/#examples","title":"Examples","text":"Example: (1) create an empty value with a given type <p>The following code shows the constructor for different <code>value_t</code> values.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create the different JSON values with default values\n json j_null(json::value_t::null);\n json j_boolean(json::value_t::boolean);\n json j_number_integer(json::value_t::number_integer);\n json j_number_float(json::value_t::number_float);\n json j_object(json::value_t::object);\n json j_array(json::value_t::array);\n json j_string(json::value_t::string);\n\n // serialize the JSON values\n std::cout << j_null << '\\n';\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null\nfalse\n0\n0.0\n{}\n[]\n\"\"\n</code></pre> Example: (2) create a <code>null</code> object <p>The following code shows the constructor with and without a null pointer parameter.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // implicitly create a JSON null value\n json j1;\n\n // explicitly create a JSON null value\n json j2(nullptr);\n\n // serialize the JSON null value\n std::cout << j1 << '\\n' << j2 << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null\nnull\n</code></pre> Example: (3) create a JSON value from compatible types <p>The following code shows the constructor with several compatible types.</p> <pre><code>#include <iostream>\n#include <deque>\n#include <list>\n#include <forward_list>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <valarray>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // ============\n // object types\n // ============\n\n // create an object from an object_t value\n json::object_t object_value = { {\"one\", 1}, {\"two\", 2} };\n json j_object_t(object_value);\n\n // create an object from std::map\n std::map<std::string, int> c_map\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 3}\n };\n json j_map(c_map);\n\n // create an object from std::unordered_map\n std::unordered_map<const char*, double> c_umap\n {\n {\"one\", 1.2}, {\"two\", 2.3}, {\"three\", 3.4}\n };\n json j_umap(c_umap);\n\n // create an object from std::multimap\n std::multimap<std::string, bool> c_mmap\n {\n {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n };\n json j_mmap(c_mmap); // only one entry for key \"three\" is used\n\n // create an object from std::unordered_multimap\n std::unordered_multimap<std::string, bool> c_ummap\n {\n {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n };\n json j_ummap(c_ummap); // only one entry for key \"three\" is used\n\n // serialize the JSON objects\n std::cout << j_object_t << '\\n';\n std::cout << j_map << '\\n';\n std::cout << j_umap << '\\n';\n std::cout << j_mmap << '\\n';\n std::cout << j_ummap << \"\\n\\n\";\n\n // ===========\n // array types\n // ===========\n\n // create an array from an array_t value\n json::array_t array_value = {\"one\", \"two\", 3, 4.5, false};\n json j_array_t(array_value);\n\n // create an array from std::vector\n std::vector<int> c_vector {1, 2, 3, 4};\n json j_vec(c_vector);\n\n // create an array from std::valarray\n std::valarray<short> c_valarray {10, 9, 8, 7};\n json j_valarray(c_valarray);\n\n // create an array from std::deque\n std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};\n json j_deque(c_deque);\n\n // create an array from std::list\n std::list<bool> c_list {true, true, false, true};\n json j_list(c_list);\n\n // create an array from std::forward_list\n std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};\n json j_flist(c_flist);\n\n // create an array from std::array\n std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};\n json j_array(c_array);\n\n // create an array from std::set\n std::set<std::string> c_set {\"one\", \"two\", \"three\", \"four\", \"one\"};\n json j_set(c_set); // only one entry for \"one\" is used\n\n // create an array from std::unordered_set\n std::unordered_set<std::string> c_uset {\"one\", \"two\", \"three\", \"four\", \"one\"};\n json j_uset(c_uset); // only one entry for \"one\" is used\n\n // create an array from std::multiset\n std::multiset<std::string> c_mset {\"one\", \"two\", \"one\", \"four\"};\n json j_mset(c_mset); // both entries for \"one\" are used\n\n // create an array from std::unordered_multiset\n std::unordered_multiset<std::string> c_umset {\"one\", \"two\", \"one\", \"four\"};\n json j_umset(c_umset); // both entries for \"one\" are used\n\n // serialize the JSON arrays\n std::cout << j_array_t << '\\n';\n std::cout << j_vec << '\\n';\n std::cout << j_valarray << '\\n';\n std::cout << j_deque << '\\n';\n std::cout << j_list << '\\n';\n std::cout << j_flist << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_set << '\\n';\n std::cout << j_uset << '\\n';\n std::cout << j_mset << '\\n';\n std::cout << j_umset << \"\\n\\n\";\n\n // ============\n // string types\n // ============\n\n // create string from a string_t value\n json::string_t string_value = \"The quick brown fox jumps over the lazy dog.\";\n json j_string_t(string_value);\n\n // create a JSON string directly from a string literal\n json j_string_literal(\"The quick brown fox jumps over the lazy dog.\");\n\n // create string from std::string\n std::string s_stdstring = \"The quick brown fox jumps over the lazy dog.\";\n json j_stdstring(s_stdstring);\n\n // serialize the JSON strings\n std::cout << j_string_t << '\\n';\n std::cout << j_string_literal << '\\n';\n std::cout << j_stdstring << \"\\n\\n\";\n\n // ============\n // number types\n // ============\n\n // create a JSON number from number_integer_t\n json::number_integer_t value_integer_t = -42;\n json j_integer_t(value_integer_t);\n\n // create a JSON number from number_unsigned_t\n json::number_integer_t value_unsigned_t = 17;\n json j_unsigned_t(value_unsigned_t);\n\n // create a JSON number from an anonymous enum\n enum { enum_value = 17 };\n json j_enum(enum_value);\n\n // create values of different integer types\n short n_short = 42;\n int n_int = -23;\n long n_long = 1024;\n int_least32_t n_int_least32_t = -17;\n uint8_t n_uint8_t = 8;\n\n // create (integer) JSON numbers\n json j_short(n_short);\n json j_int(n_int);\n json j_long(n_long);\n json j_int_least32_t(n_int_least32_t);\n json j_uint8_t(n_uint8_t);\n\n // create values of different floating-point types\n json::number_float_t v_ok = 3.141592653589793;\n json::number_float_t v_nan = NAN;\n json::number_float_t v_infinity = INFINITY;\n\n // create values of different floating-point types\n float n_float = 42.23;\n float n_float_nan = 1.0f / 0.0f;\n double n_double = 23.42;\n\n // create (floating point) JSON numbers\n json j_ok(v_ok);\n json j_nan(v_nan);\n json j_infinity(v_infinity);\n json j_float(n_float);\n json j_float_nan(n_float_nan);\n json j_double(n_double);\n\n // serialize the JSON numbers\n std::cout << j_integer_t << '\\n';\n std::cout << j_unsigned_t << '\\n';\n std::cout << j_enum << '\\n';\n std::cout << j_short << '\\n';\n std::cout << j_int << '\\n';\n std::cout << j_long << '\\n';\n std::cout << j_int_least32_t << '\\n';\n std::cout << j_uint8_t << '\\n';\n std::cout << j_ok << '\\n';\n std::cout << j_nan << '\\n';\n std::cout << j_infinity << '\\n';\n std::cout << j_float << '\\n';\n std::cout << j_float_nan << '\\n';\n std::cout << j_double << \"\\n\\n\";\n\n // =============\n // boolean types\n // =============\n\n // create boolean values\n json j_truth = true;\n json j_falsity = false;\n\n // serialize the JSON booleans\n std::cout << j_truth << '\\n';\n std::cout << j_falsity << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\n{\"one\":1,\"three\":3,\"two\":2}\n{\"one\":1.2,\"three\":3.4,\"two\":2.3}\n{\"one\":true,\"three\":false,\"two\":true}\n{\"one\":true,\"three\":false,\"two\":true}\n\n[\"one\",\"two\",3,4.5,false]\n[1,2,3,4]\n[10,9,8,7]\n[1.2,2.3,3.4,5.6]\n[true,true,false,true]\n[12345678909876,23456789098765,34567890987654,45678909876543]\n[1,2,3,4]\n[\"four\",\"one\",\"three\",\"two\"]\n[\"four\",\"three\",\"two\",\"one\"]\n[\"four\",\"one\",\"one\",\"two\"]\n[\"four\",\"two\",\"one\",\"one\"]\n\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\n-42\n17\n17\n42\n-23\n1024\n-17\n8\n3.141592653589793\nnull\nnull\n42.22999954223633\nnull\n23.42\n\ntrue\nfalse\n</code></pre> <p>Note the output is platform-dependent.</p> Example: (5) create a container (array or object) from an initializer list <p>The example below shows how JSON values are created from initializer lists.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_empty_init_list = json({});\n json j_object = { {\"one\", 1}, {\"two\", 2} };\n json j_array = {1, 2, 3, 4};\n json j_nested_object = { {\"one\", {1}}, {\"two\", {1, 2}} };\n json j_nested_array = { {{1}, \"one\"}, {{1, 2}, \"two\"} };\n\n // serialize the JSON value\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_nested_object << '\\n';\n std::cout << j_nested_array << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{}\n{\"one\":1,\"two\":2}\n[1,2,3,4]\n{\"one\":[1],\"two\":[1,2]}\n[[[1],\"one\"],[[1,2],\"two\"]]\n</code></pre> Example: (6) construct an array with count copies of given value <p>The following code shows examples for creating arrays with several copies of a given value.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array by creating copies of a JSON value\n json value = \"Hello\";\n json array_0 = json(0, value);\n json array_1 = json(1, value);\n json array_5 = json(5, value);\n\n // serialize the JSON arrays\n std::cout << array_0 << '\\n';\n std::cout << array_1 << '\\n';\n std::cout << array_5 << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[]\n[\"Hello\"]\n[\"Hello\",\"Hello\",\"Hello\",\"Hello\",\"Hello\"]\n</code></pre> Example: (7) construct a JSON container given an iterator range <p>The example below shows several ways to create JSON values by specifying a subrange with iterators.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_array = {\"alpha\", \"bravo\", \"charly\", \"delta\", \"easy\"};\n json j_number = 42;\n json j_object = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n\n // create copies using iterators\n json j_array_range(j_array.begin() + 1, j_array.end() - 2);\n json j_number_range(j_number.begin(), j_number.end());\n json j_object_range(j_object.begin(), j_object.find(\"two\"));\n\n // serialize the values\n std::cout << j_array_range << '\\n';\n std::cout << j_number_range << '\\n';\n std::cout << j_object_range << '\\n';\n\n // example for an exception\n try\n {\n json j_invalid(j_number.begin() + 1, j_number.end());\n }\n catch (const json::invalid_iterator& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[\"bravo\",\"charly\"]\n42\n{\"one\":\"eins\"}\n[json.exception.invalid_iterator.204] iterators out of range\n</code></pre> Example: (8) copy constructor <p>The following code shows an example for the copy constructor.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j1 = {\"one\", \"two\", 3, 4.5, false};\n\n // create a copy\n json j2(j1);\n\n // serialize the JSON array\n std::cout << j1 << \" = \" << j2 << '\\n';\n std::cout << std::boolalpha << (j1 == j2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[\"one\",\"two\",3,4.5,false] = [\"one\",\"two\",3,4.5,false]\ntrue\n</code></pre> Example: (9) move constructor <p>The code below shows the move constructor explicitly called via <code>std::move</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json a = 23;\n\n // move contents of a to b\n json b(std::move(a));\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null\n23\n</code></pre>"},{"location":"api/basic_json/basic_json/#version-history","title":"Version history","text":"<ol> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 2.1.0.</li> <li>Since version 3.2.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> </ol>"},{"location":"api/basic_json/begin/","title":"nlohmann::basic_json::begin","text":"<pre><code>iterator begin() noexcept;\nconst_iterator begin() const noexcept;\n</code></pre> <p>Returns an iterator to the first element.</p> <p></p>"},{"location":"api/basic_json/begin/#return-value","title":"Return value","text":"<p>iterator to the first element</p>"},{"location":"api/basic_json/begin/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/begin/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/begin/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>begin()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the first element\n json::iterator it = array.begin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>1\n</code></pre>"},{"location":"api/basic_json/begin/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/binary/","title":"nlohmann::basic_json::binary","text":"<pre><code>// (1)\nstatic basic_json binary(const typename binary_t::container_type& init);\nstatic basic_json binary(typename binary_t::container_type&& init);\n\n// (2)\nstatic basic_json binary(const typename binary_t::container_type& init,\n std::uint8_t subtype);\nstatic basic_json binary(typename binary_t::container_type&& init,\n std::uint8_t subtype);\n</code></pre> <ol> <li>Creates a JSON binary array value from a given binary container.</li> <li>Creates a JSON binary array value from a given binary container with subtype.</li> </ol> <p>Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.</p>"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"<code>init</code> (in) container containing bytes to use as binary type <code>subtype</code> (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"<p>JSON binary array value</p>"},{"location":"api/basic_json/binary/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/binary/#complexity","title":"Complexity","text":"<p>Linear in the size of <code>init</code>; constant for <code>typename binary_t::container_type&& init</code> versions.</p>"},{"location":"api/basic_json/binary/#notes","title":"Notes","text":"<p>Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a <code>std::vector</code>. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.</p>"},{"location":"api/basic_json/binary/#examples","title":"Examples","text":"Example <p>The following code shows how to create a binary value.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary vector\n std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};\n\n // create a binary JSON value with subtype 42\n json j = json::binary(vec, 42);\n\n // output type and subtype\n std::cout << \"type: \" << j.type_name() << \", subtype: \" << j.get_binary().subtype() << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>type: binary, subtype: 42\n</code></pre>"},{"location":"api/basic_json/binary/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/binary_t/","title":"nlohmann::basic_json::binary_t","text":"<pre><code>using binary_t = byte_container_with_subtype<BinaryType>;\n</code></pre> <p>This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.</p> <p>Additionally, as an implementation detail, the subtype of the binary data is carried around as a <code>std::uint64_t</code>, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to <code>BinaryType</code> via the helper type byte_container_with_subtype.</p> <p>CBOR's RFC 7049 describes this type as:</p> <p>Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).</p> <p>MessagePack's documentation on the bin type family describes this type as:</p> <p>Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.</p> <p>BSON's specifications describe several binary types; however, this type is intended to represent the generic binary type which has the description:</p> <p>Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.</p> <p>None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.</p> <p>The default representation of this binary format is a <code>std::vector<std::uint8_t></code>, which is a very common way to represent a byte array in modern C++.</p>"},{"location":"api/basic_json/binary_t/#template-parameters","title":"Template parameters","text":"<code>BinaryType</code> container type to store arrays"},{"location":"api/basic_json/binary_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/binary_t/#default-type","title":"Default type","text":"<p>The default values for <code>BinaryType</code> is <code>std::vector<std::uint8_t></code>.</p>"},{"location":"api/basic_json/binary_t/#storage","title":"Storage","text":"<p>Binary Arrays are stored as pointers in a <code>basic_json</code> type. That is, for any access to array values, a pointer of the type <code>binary_t*</code> must be dereferenced.</p>"},{"location":"api/basic_json/binary_t/#notes-on-subtypes","title":"Notes on subtypes","text":"<ul> <li> <p>CBOR</p> <ul> <li>Binary values are represented as byte strings. Subtypes are written as tags.</li> </ul> </li> <li> <p>MessagePack</p> <ul> <li>If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as signed 8-bit integer.</li> <li>If no subtype is given, the bin family (bin8, bin16, bin32) is used.</li> </ul> </li> <li> <p>BSON</p> <ul> <li>If a subtype is given, it is used and added as unsigned 8-bit integer.</li> <li>If no subtype is given, the generic binary subtype 0x00 is used.</li> </ul> </li> </ul>"},{"location":"api/basic_json/binary_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>binary_t</code> is by default, a typedef to <code>nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>></code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>, json::binary_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/binary_t/#see-also","title":"See also","text":"<ul> <li>byte_container_with_subtype</li> </ul>"},{"location":"api/basic_json/binary_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0. Changed type of subtype to <code>std::uint64_t</code> in version 3.10.0.</li> </ul>"},{"location":"api/basic_json/boolean_t/","title":"nlohmann::basic_json::boolean_t","text":"<pre><code>using boolean_t = BooleanType;\n</code></pre> <p>The type used to store JSON booleans.</p> <p>RFC 8259 implicitly describes a boolean as a type which differentiates the two literals <code>true</code> and <code>false</code>.</p> <p>To store objects in C++, a type is defined by the template parameter <code>BooleanType</code> which chooses the type to use.</p>"},{"location":"api/basic_json/boolean_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/boolean_t/#default-type","title":"Default type","text":"<p>With the default values for <code>BooleanType</code> (<code>bool</code>), the default value for <code>boolean_t</code> is <code>bool</code>.</p>"},{"location":"api/basic_json/boolean_t/#storage","title":"Storage","text":"<p>Boolean values are stored directly inside a <code>basic_json</code> type.</p>"},{"location":"api/basic_json/boolean_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>boolean_t</code> is by default, a typedef to <code>bool</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<bool, json::boolean_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/boolean_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/cbegin/","title":"nlohmann::basic_json::cbegin","text":"<pre><code>const_iterator cbegin() const noexcept;\n</code></pre> <p>Returns an iterator to the first element.</p> <p></p>"},{"location":"api/basic_json/cbegin/#return-value","title":"Return value","text":"<p>iterator to the first element</p>"},{"location":"api/basic_json/cbegin/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/cbegin/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/cbegin/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>cbegin()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n const json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the first element\n json::const_iterator it = array.cbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>1\n</code></pre>"},{"location":"api/basic_json/cbegin/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/cbor_tag_handler_t/","title":"nlohmann::basic_json::cbor_tag_handler_t","text":"<pre><code>enum class cbor_tag_handler_t\n{\n error,\n ignore,\n store\n};\n</code></pre> <p>This enumeration is used in the <code>from_cbor</code> function to choose how to treat tags:</p> error throw a <code>parse_error</code> exception in case of a tag ignore ignore tags store store tagged values as binary container with subtype (for bytes 0xd8..0xdb)"},{"location":"api/basic_json/cbor_tag_handler_t/#examples","title":"Examples","text":"Example <p>The example below shows how the different values of the <code>cbor_tag_handler_t</code> influence the behavior of <code>from_cbor</code> when reading a tagged byte string.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // tagged byte string\n std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // cbor_tag_handler_t::error throws\n try\n {\n auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n // cbor_tag_handler_t::ignore ignores the tag\n auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);\n std::cout << b_ignore_tag << std::endl;\n\n // cbor_tag_handler_t::store stores the tag as binary subtype\n auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);\n std::cout << b_store_tag << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xD8\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":66}\n</code></pre>"},{"location":"api/basic_json/cbor_tag_handler_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.9.0. Added value <code>store</code> in 3.10.0.</li> </ul>"},{"location":"api/basic_json/cend/","title":"nlohmann::basic_json::cend","text":"<pre><code>const_iterator cend() const noexcept;\n</code></pre> <p>Returns an iterator to one past the last element.</p> <p></p>"},{"location":"api/basic_json/cend/#return-value","title":"Return value","text":"<p>iterator one past the last element</p>"},{"location":"api/basic_json/cend/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/cend/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/cend/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>cend()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to one past the last element\n json::const_iterator it = array.cend();\n\n // decrement the iterator to point to the last element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>5\n</code></pre>"},{"location":"api/basic_json/cend/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/clear/","title":"nlohmann::basic_json::clear","text":"<pre><code>void clear() noexcept;\n</code></pre> <p>Clears the content of a JSON value and resets it to the default value as if <code>basic_json(value_t)</code> would have been called with the current value type from <code>type()</code>:</p> Value type initial value null <code>null</code> boolean <code>false</code> string <code>\"\"</code> number <code>0</code> binary An empty byte vector object <code>{}</code> array <code>[]</code> <p>Has the same effect as calling</p> <pre><code>*this = basic_json(type());\n</code></pre>"},{"location":"api/basic_json/clear/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/clear/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value.</p>"},{"location":"api/basic_json/clear/#notes","title":"Notes","text":"<p>All iterators, pointers and references related to this container are invalidated.</p>"},{"location":"api/basic_json/clear/#examples","title":"Examples","text":"Example <p>The example below shows the effect of <code>clear()</code> to different JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call clear()\n j_null.clear();\n j_boolean.clear();\n j_number_integer.clear();\n j_number_float.clear();\n j_object.clear();\n j_array.clear();\n j_string.clear();\n\n // serialize the cleared values()\n std::cout << j_null << '\\n';\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null\nfalse\n0\n0.0\n{}\n[]\n\"\"\n</code></pre>"},{"location":"api/basic_json/clear/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Added support for binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/contains/","title":"nlohmann::basic_json::contains","text":"<pre><code>// (1)\nbool contains(const typename object_t::key_type& key) const;\n\n// (2)\ntemplate<typename KeyType>\nbool contains(KeyType&& key) const;\n\n// (3)\nbool contains(const json_pointer& ptr) const;\n</code></pre> <ol> <li>Check whether an element exists in a JSON object with a key equivalent to <code>key</code>. If the element is not found or the JSON value is not an object, <code>false</code> is returned.</li> <li>See 1. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</li> <li>Check whether the given JSON pointer <code>ptr</code> can be resolved in the current JSON value.</li> </ol>"},{"location":"api/basic_json/contains/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17)."},{"location":"api/basic_json/contains/#parameters","title":"Parameters","text":"<code>key</code> (in) key value to check its existence. <code>ptr</code> (in) JSON pointer to check its existence."},{"location":"api/basic_json/contains/#return-value","title":"Return value","text":"<ol> <li><code>true</code> if an element with specified <code>key</code> exists. If no such element with such key is found or the JSON value is not an object, <code>false</code> is returned.</li> <li>See 1.</li> <li><code>true</code> if the JSON pointer can be resolved to a stored value, <code>false</code> otherwise.</li> </ol>"},{"location":"api/basic_json/contains/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/contains/#exceptions","title":"Exceptions","text":"<ol> <li>The function does not throw exceptions.</li> <li>The function does not throw exceptions.</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>parse_error.106</code> if an array index begins with <code>0</code>.</li> <li>Throws <code>parse_error.109</code> if an array index was not a number.</li> </ul> </li> </ol>"},{"location":"api/basic_json/contains/#complexity","title":"Complexity","text":"<p>Logarithmic in the size of the JSON object.</p>"},{"location":"api/basic_json/contains/#notes","title":"Notes","text":"<ul> <li>This method always returns <code>false</code> when executed on a JSON type that is not an object.</li> <li>This method can be executed on any JSON value type.</li> </ul> <p>Postconditions</p> <p>If <code>j.contains(x)</code> returns <code>true</code> for a key or JSON pointer <code>x</code>, then it is safe to call <code>j[x]</code>.</p>"},{"location":"api/basic_json/contains/#examples","title":"Examples","text":"Example: (1) check with key <p>The example shows how <code>contains()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create some JSON values\n json j_object = R\"( {\"key\": \"value\"} )\"_json;\n json j_array = R\"( [1, 2, 3] )\"_json;\n\n // call contains\n std::cout << std::boolalpha <<\n \"j_object contains 'key': \" << j_object.contains(\"key\") << '\\n' <<\n \"j_object contains 'another': \" << j_object.contains(\"another\") << '\\n' <<\n \"j_array contains 'key': \" << j_array.contains(\"key\") << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n</code></pre> Example: (2) check with key using string_view <p>The example shows how <code>contains()</code> is used.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create some JSON values\n json j_object = R\"( {\"key\": \"value\"} )\"_json;\n json j_array = R\"( [1, 2, 3] )\"_json;\n\n // call contains\n std::cout << std::boolalpha <<\n \"j_object contains 'key': \" << j_object.contains(\"key\"sv) << '\\n' <<\n \"j_object contains 'another': \" << j_object.contains(\"another\"sv) << '\\n' <<\n \"j_array contains 'key': \" << j_array.contains(\"key\"sv) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n</code></pre> Example: (3) check with JSON pointer <p>The example shows how <code>contains()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n std::cout << std::boolalpha\n << j.contains(\"/number\"_json_pointer) << '\\n'\n << j.contains(\"/string\"_json_pointer) << '\\n'\n << j.contains(\"/array\"_json_pointer) << '\\n'\n << j.contains(\"/array/1\"_json_pointer) << '\\n'\n << j.contains(\"/array/-\"_json_pointer) << '\\n'\n << j.contains(\"/array/4\"_json_pointer) << '\\n'\n << j.contains(\"/baz\"_json_pointer) << std::endl;\n\n try\n {\n // try to use an array index with leading '0'\n j.contains(\"/array/01\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n try\n {\n // try to use an array index that is not a number\n j.contains(\"/array/one\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>true\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/contains/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.11.0.</li> <li>Added in version 3.6.0. Extended template <code>KeyType</code> to support comparable types in version 3.11.0.</li> <li>Added in version 3.7.0.</li> </ol>"},{"location":"api/basic_json/count/","title":"nlohmann::basic_json::count","text":"<pre><code>// (1)\nsize_type count(const typename object_t::key_type& key) const;\n\n// (2)\ntemplate<typename KeyType>\nsize_type count(KeyType&& key) const;\n</code></pre> <ol> <li>Returns the number of elements with key <code>key</code>. If <code>ObjectType</code> is the default <code>std::map</code> type, the return value will always be <code>0</code> (<code>key</code> was not found) or <code>1</code> (<code>key</code> was found).</li> <li>See 1. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</li> </ol>"},{"location":"api/basic_json/count/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17)."},{"location":"api/basic_json/count/#parameters","title":"Parameters","text":"<code>key</code> (in) key value of the element to count."},{"location":"api/basic_json/count/#return-value","title":"Return value","text":"<p>Number of elements with key <code>key</code>. If the JSON value is not an object, the return value will be <code>0</code>.</p>"},{"location":"api/basic_json/count/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/count/#complexity","title":"Complexity","text":"<p>Logarithmic in the size of the JSON object.</p>"},{"location":"api/basic_json/count/#notes","title":"Notes","text":"<p>This method always returns <code>0</code> when executed on a JSON type that is not an object.</p>"},{"location":"api/basic_json/count/#examples","title":"Examples","text":"Example: (1) count number of elements <p>The example shows how <code>count()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call count()\n auto count_two = j_object.count(\"two\");\n auto count_three = j_object.count(\"three\");\n\n // print values\n std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n</code></pre> Example: (2) count number of elements using string_view <p>The example shows how <code>count()</code> is used.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call count()\n auto count_two = j_object.count(\"two\"sv);\n auto count_three = j_object.count(\"three\"sv);\n\n // print values\n std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n</code></pre>"},{"location":"api/basic_json/count/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.11.0.</li> <li>Added in version 1.0.0. Changed parameter <code>key</code> type to <code>KeyType&&</code> in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/crbegin/","title":"nlohmann::basic_json::crbegin","text":"<pre><code>const_reverse_iterator crbegin() const noexcept;\n</code></pre> <p>Returns an iterator to the reverse-beginning; that is, the last element.</p> <p></p>"},{"location":"api/basic_json/crbegin/#return-value","title":"Return value","text":"<p>reverse iterator to the first element</p>"},{"location":"api/basic_json/crbegin/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/crbegin/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/crbegin/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>crbegin()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-beginning\n json::const_reverse_iterator it = array.crbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>5\n</code></pre>"},{"location":"api/basic_json/crbegin/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/crend/","title":"nlohmann::basic_json::crend","text":"<pre><code>const_reverse_iterator crend() const noexcept;\n</code></pre> <p>Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.</p> <p></p>"},{"location":"api/basic_json/crend/#return-value","title":"Return value","text":"<p>reverse iterator to the element following the last element</p>"},{"location":"api/basic_json/crend/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/crend/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/crend/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>eend()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-end\n json::const_reverse_iterator it = array.crend();\n\n // increment the iterator to point to the first element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>1\n</code></pre>"},{"location":"api/basic_json/crend/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/default_object_comparator_t/","title":"nlohmann::basic_json::default_object_comparator_t","text":"<pre><code>using default_object_comparator_t = std::less<StringType>; // until C++14\n\nusing default_object_comparator_t = std::less<>; // since C++14\n</code></pre> <p>The default comparator used by <code>object_t</code>.</p> <p>Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object.</p> <p>The actual comparator used depends on <code>object_t</code> and can be obtained via <code>object_comparator_t</code>.</p>"},{"location":"api/basic_json/default_object_comparator_t/#examples","title":"Examples","text":"Example <p>The example below demonstrates the default comparator.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha\n << \"one < two : \" << json::default_object_comparator_t{}(\"one\", \"two\") << \"\\n\"\n << \"three < four : \" << json::default_object_comparator_t{}(\"three\", \"four\") << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>one < two : true\nthree < four : false\n</code></pre>"},{"location":"api/basic_json/default_object_comparator_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/basic_json/diff/","title":"nlohmann::basic_json::diff","text":"<pre><code>static basic_json diff(const basic_json& source,\n const basic_json& target);\n</code></pre> <p>Creates a JSON Patch so that value <code>source</code> can be changed into the value <code>target</code> by calling <code>patch</code> function.</p> <p>For two JSON values <code>source</code> and <code>target</code>, the following code yields always <code>true</code>: <pre><code>source.patch(diff(source, target)) == target;\n</code></pre></p>"},{"location":"api/basic_json/diff/#parameters","title":"Parameters","text":"<code>source</code> (in) JSON value to compare from <code>target</code> (in) JSON value to compare against"},{"location":"api/basic_json/diff/#return-value","title":"Return value","text":"<p>a JSON patch to convert the <code>source</code> to <code>target</code></p>"},{"location":"api/basic_json/diff/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/diff/#complexity","title":"Complexity","text":"<p>Linear in the lengths of <code>source</code> and <code>target</code>.</p>"},{"location":"api/basic_json/diff/#notes","title":"Notes","text":"<p>Currently, only <code>remove</code>, <code>add</code>, and <code>replace</code> operations are generated.</p>"},{"location":"api/basic_json/diff/#examples","title":"Examples","text":"Example <p>The following code shows how a JSON patch is created as a diff for two JSON values.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the source document\n json source = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the target document\n json target = R\"(\n {\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n }\n )\"_json;\n\n // create the patch\n json patch = json::diff(source, target);\n\n // roundtrip\n json patched_source = source.patch(patch);\n\n // output patch and roundtrip result\n std::cout << std::setw(4) << patch << \"\\n\\n\"\n << std::setw(4) << patched_source << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>[\n {\n \"op\": \"replace\",\n \"path\": \"/baz\",\n \"value\": \"boo\"\n },\n {\n \"op\": \"remove\",\n \"path\": \"/foo\"\n },\n {\n \"op\": \"add\",\n \"path\": \"/hello\",\n \"value\": [\n \"world\"\n ]\n }\n]\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n</code></pre>"},{"location":"api/basic_json/diff/#see-also","title":"See also","text":"<ul> <li>RFC 6902 (JSON Patch)</li> </ul>"},{"location":"api/basic_json/diff/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> </ul>"},{"location":"api/basic_json/dump/","title":"nlohmann::basic_json::dump","text":"<pre><code>string_t dump(const int indent = -1,\n const char indent_char = ' ',\n const bool ensure_ascii = false,\n const error_handler_t error_handler = error_handler_t::strict) const;\n</code></pre> <p>Serialization function for JSON values. The function tries to mimic Python's <code>json.dumps()</code> function, and currently supports its <code>indent</code> and <code>ensure_ascii</code> parameters.</p>"},{"location":"api/basic_json/dump/#parameters","title":"Parameters","text":"<code>indent</code> (in) If <code>indent</code> is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of <code>0</code> will only insert newlines. <code>-1</code> (the default) selects the most compact representation. <code>indent_char</code> (in) The character to use for indentation if <code>indent</code> is greater than <code>0</code>. The default is <code></code> (space). <code>ensure_ascii</code> (in) If <code>ensure_ascii</code> is true, all non-ASCII characters in the output are escaped with <code>\\uXXXX</code> sequences, and the result consists of ASCII characters only. <code>error_handler</code> (in) how to react on decoding errors; there are three possible values (see <code>error_handler_t</code>: <code>strict</code> (throws and exception in case a decoding error occurs; default), <code>replace</code> (replace invalid UTF-8 sequences with U+FFFD), and <code>ignore</code> (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged))."},{"location":"api/basic_json/dump/#return-value","title":"Return value","text":"<p>string containing the serialization of the JSON value</p>"},{"location":"api/basic_json/dump/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</p>"},{"location":"api/basic_json/dump/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.316</code> if a string stored inside the JSON value is not UTF-8 encoded and <code>error_handler</code> is set to <code>strict</code></p>"},{"location":"api/basic_json/dump/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/dump/#notes","title":"Notes","text":"<p>Binary values are serialized as object containing two keys:</p> <ul> <li>\"bytes\": an array of bytes as integers</li> <li>\"subtype\": the subtype as integer or <code>null</code> if the binary has no subtype</li> </ul>"},{"location":"api/basic_json/dump/#examples","title":"Examples","text":"Example <p>The following example shows the effect of different <code>indent</code>, <code>indent_char</code>, and <code>ensure_ascii</code> parameters to the result of the serialization.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hell\u00f6 \ud83d\ude00!\";\n\n // call dump()\n std::cout << \"objects:\" << '\\n'\n << j_object.dump() << \"\\n\\n\"\n << j_object.dump(-1) << \"\\n\\n\"\n << j_object.dump(0) << \"\\n\\n\"\n << j_object.dump(4) << \"\\n\\n\"\n << j_object.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"arrays:\" << '\\n'\n << j_array.dump() << \"\\n\\n\"\n << j_array.dump(-1) << \"\\n\\n\"\n << j_array.dump(0) << \"\\n\\n\"\n << j_array.dump(4) << \"\\n\\n\"\n << j_array.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"strings:\" << '\\n'\n << j_string.dump() << '\\n'\n << j_string.dump(-1, ' ', true) << '\\n';\n\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"\u00e4\\xA9\u00fc\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>objects:\n{\"one\":1,\"two\":2}\n\n{\"one\":1,\"two\":2}\n\n{\n\"one\": 1,\n\"two\": 2\n}\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\narrays:\n[1,2,4,8,16]\n\n[1,2,4,8,16]\n\n[\n1,\n2,\n4,\n8,\n16\n]\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\nstrings:\n\"Hell\u00f6 \ud83d\ude00!\"\n\"Hell\\u00f6 \\ud83d\\ude00!\"\n[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n</code></pre>"},{"location":"api/basic_json/dump/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Indentation character <code>indent_char</code>, option <code>ensure_ascii</code> and exceptions added in version 3.0.0.</li> <li>Error handlers added in version 3.4.0.</li> <li>Serialization of binary values added in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/emplace/","title":"nlohmann::basic_json::emplace","text":"<pre><code>template<class... Args>\nstd::pair<iterator, bool> emplace(Args&& ... args);\n</code></pre> <p>Inserts a new element into a JSON object constructed in-place with the given <code>args</code> if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from <code>args</code>.</p>"},{"location":"api/basic_json/emplace/#template-parameters","title":"Template parameters","text":"<code>Args</code> compatible types to create a <code>basic_json</code> object"},{"location":"api/basic_json/emplace/#parameters","title":"Parameters","text":"<code>args</code> (in) arguments to forward to a constructor of <code>basic_json</code>"},{"location":"api/basic_json/emplace/#return-value","title":"Return value","text":"<p>a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a <code>bool</code> denoting whether the insertion took place.</p>"},{"location":"api/basic_json/emplace/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.311</code> when called on a type other than JSON object or <code>null</code>; example: <code>\"cannot use emplace() with number\"</code></p>"},{"location":"api/basic_json/emplace/#complexity","title":"Complexity","text":"<p>Logarithmic in the size of the container, O(log(<code>size()</code>)).</p>"},{"location":"api/basic_json/emplace/#examples","title":"Examples","text":"Example <p>The example shows how <code>emplace()</code> can be used to add elements to a JSON object. Note how the <code>null</code> value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n auto res1 = object.emplace(\"three\", 3);\n null.emplace(\"A\", \"a\");\n null.emplace(\"B\", \"b\");\n\n // the following call will not add an object, because there is already\n // a value stored at key \"B\"\n auto res2 = null.emplace(\"B\", \"c\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << *res1.first << \" \" << std::boolalpha << res1.second << '\\n';\n\n std::cout << null << '\\n';\n std::cout << *res2.first << \" \" << std::boolalpha << res2.second << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\nnull\n{\"one\":1,\"three\":3,\"two\":2}\n3 true\n{\"A\":\"a\",\"B\":\"b\"}\n\"b\" false\n</code></pre>"},{"location":"api/basic_json/emplace/#version-history","title":"Version history","text":"<ul> <li>Since version 2.0.8.</li> </ul>"},{"location":"api/basic_json/emplace_back/","title":"nlohmann::basic_json::emplace_back","text":"<pre><code>template<class... Args>\nreference emplace_back(Args&& ... args);\n</code></pre> <p>Creates a JSON value from the passed parameters <code>args</code> to the end of the JSON value. If the function is called on a JSON <code>null</code> value, an empty array is created before appending the value created from <code>args</code>.</p>"},{"location":"api/basic_json/emplace_back/#template-parameters","title":"Template parameters","text":"<code>Args</code> compatible types to create a <code>basic_json</code> object"},{"location":"api/basic_json/emplace_back/#parameters","title":"Parameters","text":"<code>args</code> (in) arguments to forward to a constructor of <code>basic_json</code>"},{"location":"api/basic_json/emplace_back/#return-value","title":"Return value","text":"<p>reference to the inserted element</p>"},{"location":"api/basic_json/emplace_back/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.311</code> when called on a type other than JSON array or <code>null</code>; example: <code>\"cannot use emplace_back() with number\"</code></p>"},{"location":"api/basic_json/emplace_back/#complexity","title":"Complexity","text":"<p>Amortized constant.</p>"},{"location":"api/basic_json/emplace_back/#examples","title":"Examples","text":"Example <p>The example shows how <code>emplace_back()</code> can be used to add elements to a JSON array. Note how the <code>null</code> value was silently converted to a JSON array.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.emplace_back(6);\n null.emplace_back(\"first\");\n null.emplace_back(3, \"second\");\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3,4,5]\nnull\n[1,2,3,4,5,6]\n[\"first\",[\"second\",\"second\",\"second\"]]\n</code></pre>"},{"location":"api/basic_json/emplace_back/#version-history","title":"Version history","text":"<ul> <li>Since version 2.0.8.</li> <li>Returns reference since 3.7.0.</li> </ul>"},{"location":"api/basic_json/empty/","title":"nlohmann::basic_json::empty","text":"<pre><code>bool empty() const noexcept;\n</code></pre> <p>Checks if a JSON value has no elements (i.e. whether its <code>size()</code> is <code>0</code>).</p>"},{"location":"api/basic_json/empty/#return-value","title":"Return value","text":"<p>The return value depends on the different types and is defined as follows:</p> Value type return value null <code>true</code> boolean <code>false</code> string <code>false</code> number <code>false</code> binary <code>false</code> object result of function <code>object_t::empty()</code> array result of function <code>array_t::empty()</code>"},{"location":"api/basic_json/empty/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/empty/#complexity","title":"Complexity","text":"<p>Constant, as long as <code>array_t</code> and <code>object_t</code> satisfy the Container concept; that is, their <code>empty()</code> functions have constant complexity.</p>"},{"location":"api/basic_json/empty/#possible-implementation","title":"Possible implementation","text":"<pre><code>bool empty() const noexcept\n{\n return size() == 0;\n}\n</code></pre>"},{"location":"api/basic_json/empty/#notes","title":"Notes","text":"<p>This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is <code>false</code> in the case of a string.</p>"},{"location":"api/basic_json/empty/#examples","title":"Examples","text":"Example <p>The following code uses <code>empty()</code> to check if a JSON object contains any elements.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call empty()\n std::cout << std::boolalpha;\n std::cout << j_null.empty() << '\\n';\n std::cout << j_boolean.empty() << '\\n';\n std::cout << j_number_integer.empty() << '\\n';\n std::cout << j_number_float.empty() << '\\n';\n std::cout << j_object.empty() << '\\n';\n std::cout << j_object_empty.empty() << '\\n';\n std::cout << j_array.empty() << '\\n';\n std::cout << j_array_empty.empty() << '\\n';\n std::cout << j_string.empty() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\ntrue\nfalse\n</code></pre>"},{"location":"api/basic_json/empty/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to return <code>false</code> for binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/end/","title":"nlohmann::basic_json::end","text":"<pre><code>iterator end() noexcept;\nconst_iterator end() const noexcept;\n</code></pre> <p>Returns an iterator to one past the last element.</p> <p></p>"},{"location":"api/basic_json/end/#return-value","title":"Return value","text":"<p>iterator one past the last element</p>"},{"location":"api/basic_json/end/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/end/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/end/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>end()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to one past the last element\n json::iterator it = array.end();\n\n // decrement the iterator to point to the last element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>5\n</code></pre>"},{"location":"api/basic_json/end/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/erase/","title":"nlohmann::basic_json::erase","text":"<pre><code>// (1)\niterator erase(iterator pos);\nconst_iterator erase(const_iterator pos);\n\n// (2)\niterator erase(iterator first, iterator last);\nconst_iterator erase(const_iterator first, const_iterator last);\n\n// (3)\nsize_type erase(const typename object_t::key_type& key);\n\n// (4)\ntemplate<typename KeyType>\nsize_type erase(KeyType&& key);\n\n// (5)\nvoid erase(const size_type idx);\n</code></pre> <ol> <li> <p>Removes an element from a JSON value specified by iterator <code>pos</code>. The iterator <code>pos</code> must be valid and dereferenceable. Thus, the <code>end()</code> iterator (which is valid, but is not dereferenceable) cannot be used as a value for <code>pos</code>.</p> <p>If called on a primitive type other than <code>null</code>, the resulting JSON value will be <code>null</code>.</p> </li> <li> <p>Remove an element range specified by <code>[first; last)</code> from a JSON value. The iterator <code>first</code> does not need to be dereferenceable if <code>first == last</code>: erasing an empty range is a no-op.</p> <p>If called on a primitive type other than <code>null</code>, the resulting JSON value will be <code>null</code>.</p> </li> <li> <p>Removes an element from a JSON object by key.</p> </li> <li> <p>See 3. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</p> </li> <li> <p>Removes an element from a JSON array by index.</p> </li> </ol>"},{"location":"api/basic_json/erase/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17)."},{"location":"api/basic_json/erase/#parameters","title":"Parameters","text":"<code>pos</code> (in) iterator to the element to remove <code>first</code> (in) iterator to the beginning of the range to remove <code>last</code> (in) iterator past the end of the range to remove <code>key</code> (in) object key of the elements to remove <code>idx</code> (in) array index of the element to remove"},{"location":"api/basic_json/erase/#return-value","title":"Return value","text":"<ol> <li>Iterator following the last removed element. If the iterator <code>pos</code> refers to the last element, the <code>end()</code> iterator is returned.</li> <li>Iterator following the last removed element. If the iterator <code>last</code> refers to the last element, the <code>end()</code> iterator is returned.</li> <li>Number of elements removed. If <code>ObjectType</code> is the default <code>std::map</code> type, the return value will always be <code>0</code> (<code>key</code> was not found) or <code>1</code> (<code>key</code> was found).</li> <li>See 3.</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/erase/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/erase/#exceptions","title":"Exceptions","text":"<ol> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.307</code> if called on a <code>null</code> value; example: <code>\"cannot use erase() with null\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> <li>Throws <code>invalid_iterator.205</code> if called on a primitive type with invalid iterator (i.e., any iterator which is not <code>begin()</code>); example: <code>\"iterator out of range\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.307</code> if called on a <code>null</code> value; example: <code>\"cannot use erase() with null\"</code></li> <li>Throws <code>invalid_iterator.203</code> if called on iterators which does not belong to the current JSON value; example: <code>\"iterators do not fit current value\"</code></li> <li>Throws <code>invalid_iterator.204</code> if called on a primitive type with invalid iterators (i.e., if <code>first != begin()</code> and <code>last != end()</code>); example: <code>\"iterators out of range\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.307</code> when called on a type other than JSON object; example: <code>\"cannot use erase() with null\"</code></li> </ul> </li> <li>See 3.</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.307</code> when called on a type other than JSON object; example: <code>\"cannot use erase() with null\"</code></li> <li>Throws <code>out_of_range.401</code> when <code>idx >= size()</code>; example: <code>\"array index 17 is out of range\"</code></li> </ul> </li> </ol>"},{"location":"api/basic_json/erase/#complexity","title":"Complexity","text":"<ol> <li>The complexity depends on the type:<ul> <li>objects: amortized constant</li> <li>arrays: linear in distance between <code>pos</code> and the end of the container</li> <li>strings and binary: linear in the length of the member</li> <li>other types: constant</li> </ul> </li> <li>The complexity depends on the type:<ul> <li>objects: <code>log(size()) + std::distance(first, last)</code></li> <li>arrays: linear in the distance between <code>first</code> and <code>last</code>, plus linear in the distance between <code>last</code> and end of the container</li> <li>strings and binary: linear in the length of the member</li> <li>other types: constant</li> </ul> </li> <li><code>log(size()) + count(key)</code></li> <li><code>log(size()) + count(key)</code></li> <li>Linear in distance between <code>idx</code> and the end of the container.</li> </ol>"},{"location":"api/basic_json/erase/#notes","title":"Notes","text":"<ol> <li>Invalidates iterators and references at or after the point of the <code>erase</code>, including the <code>end()</code> iterator.</li> <li>(none)</li> <li>References and iterators to the erased elements are invalidated. Other references and iterators are not affected.</li> <li>See 3.</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/erase/#examples","title":"Examples","text":"Example: (1) remove element given an iterator <p>The example shows the effect of <code>erase()</code> for different JSON types using an iterator.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call erase()\n j_boolean.erase(j_boolean.begin());\n j_number_integer.erase(j_number_integer.begin());\n j_number_float.erase(j_number_float.begin());\n j_object.erase(j_object.find(\"two\"));\n j_array.erase(j_array.begin() + 2);\n j_string.erase(j_string.begin());\n\n // print values\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null\nnull\nnull\n{\"one\":1}\n[1,2,8,16]\nnull\n</code></pre> Example: (2) remove elements given an iterator range <p>The example shows the effect of <code>erase()</code> for different JSON types using an iterator range.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call erase()\n j_boolean.erase(j_boolean.begin(), j_boolean.end());\n j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());\n j_number_float.erase(j_number_float.begin(), j_number_float.end());\n j_object.erase(j_object.find(\"two\"), j_object.end());\n j_array.erase(j_array.begin() + 1, j_array.begin() + 3);\n j_string.erase(j_string.begin(), j_string.end());\n\n // print values\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null\nnull\nnull\n{\"one\":1}\n[1,8,16]\nnull\n</code></pre> Example: (3) remove element from a JSON object given a key <p>The example shows the effect of <code>erase()</code> for different JSON types using an object key.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call erase()\n auto count_one = j_object.erase(\"one\");\n auto count_three = j_object.erase(\"three\");\n\n // print values\n std::cout << j_object << '\\n';\n std::cout << count_one << \" \" << count_three << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"two\":2}\n1 0\n</code></pre> Example: (4) remove element from a JSON object given a key using string_view <p>The example shows the effect of <code>erase()</code> for different JSON types using an object key.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call erase()\n auto count_one = j_object.erase(\"one\"sv);\n auto count_three = j_object.erase(\"three\"sv);\n\n // print values\n std::cout << j_object << '\\n';\n std::cout << count_one << \" \" << count_three << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"two\":2}\n1 0\n</code></pre> Example: (5) remove element from a JSON array given an index <p>The example shows the effect of <code>erase()</code> using an array index.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j_array = {0, 1, 2, 3, 4, 5};\n\n // call erase()\n j_array.erase(2);\n\n // print values\n std::cout << j_array << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[0,1,3,4,5]\n</code></pre>"},{"location":"api/basic_json/erase/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Added support for binary types in version 3.8.0.</li> <li>Added in version 1.0.0. Added support for binary types in version 3.8.0.</li> <li>Added in version 1.0.0.</li> <li>Added in version 3.11.0.</li> <li>Added in version 1.0.0.</li> </ol>"},{"location":"api/basic_json/error_handler_t/","title":"nlohmann::basic_json::error_handler_t","text":"<pre><code>enum class error_handler_t {\n strict,\n replace,\n ignore\n};\n</code></pre> <p>This enumeration is used in the <code>dump</code> function to choose how to treat decoding errors while serializing a <code>basic_json</code> value. Three values are differentiated:</p> strict throw a <code>type_error</code> exception in case of invalid UTF-8 replace replace invalid UTF-8 sequences with U+FFFD (\ufffd REPLACEMENT CHARACTER) ignore ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged"},{"location":"api/basic_json/error_handler_t/#examples","title":"Examples","text":"Example <p>The example below shows how the different values of the <code>error_handler_t</code> influence the behavior of <code>dump</code> when reading serializing an invalid UTF-8 sequence.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"\u00e4\\xA9\u00fc\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n</code></pre>"},{"location":"api/basic_json/error_handler_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.4.0.</li> </ul>"},{"location":"api/basic_json/exception/","title":"nlohmann::basic_json::exception","text":"<pre><code>class exception : public std::exception;\n</code></pre> <p>This class is an extension of <code>std::exception</code> objects with a member <code>id</code> for exception ids. It is used as the base class for all exceptions thrown by the <code>basic_json</code> class. This class can hence be used as \"wildcard\" to catch exceptions, see example below.</p> <p></p> <p>Subclasses:</p> <ul> <li><code>parse_error</code> for exceptions indicating a parse error</li> <li><code>invalid_iterator</code> for exceptions indicating errors with iterators</li> <li><code>type_error</code> for exceptions indicating executing a member function with a wrong type</li> <li><code>out_of_range</code> for exceptions indicating access out of the defined range</li> <li><code>other_error</code> for exceptions indicating other library errors</li> </ul>"},{"location":"api/basic_json/exception/#member-functions","title":"Member functions","text":"<ul> <li>what - returns explanatory string</li> </ul>"},{"location":"api/basic_json/exception/#member-variables","title":"Member variables","text":"<ul> <li>id - the id of the exception</li> </ul>"},{"location":"api/basic_json/exception/#notes","title":"Notes","text":"<p>To have nothrow-copy-constructible exceptions, we internally use <code>std::runtime_error</code> which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.</p>"},{"location":"api/basic_json/exception/#examples","title":"Examples","text":"Example <p>The following code shows how arbitrary library exceptions can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for a non-existing key\n json j = {{\"foo\", \"bar\"}};\n json k = j.at(\"non-existing\");\n }\n catch (const json::exception& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.out_of_range.403] key 'non-existing' not found\nexception id: 403\n</code></pre>"},{"location":"api/basic_json/exception/#see-also","title":"See also","text":"<p>List of exceptions</p>"},{"location":"api/basic_json/exception/#version-history","title":"Version history","text":"<ul> <li>Since version 3.0.0.</li> </ul>"},{"location":"api/basic_json/find/","title":"nlohmann::basic_json::find","text":"<pre><code>// (1)\niterator find(const typename object_t::key_type& key);\nconst_iterator find(const typename object_t::key_type& key) const;\n\n// (2)\ntemplate<typename KeyType>\niterator find(KeyType&& key);\ntemplate<typename KeyType>\nconst_iterator find(KeyType&& key) const;\n</code></pre> <ol> <li>Finds an element in a JSON object with a key equivalent to <code>key</code>. If the element is not found or the JSON value is not an object, <code>end()</code> is returned.</li> <li>See 1. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</li> </ol>"},{"location":"api/basic_json/find/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17)."},{"location":"api/basic_json/find/#parameters","title":"Parameters","text":"<code>key</code> (in) key value of the element to search for."},{"location":"api/basic_json/find/#return-value","title":"Return value","text":"<p>Iterator to an element with a key equivalent to <code>key</code>. If no such element is found or the JSON value is not an object, a past-the-end iterator (see <code>end()</code>) is returned.</p>"},{"location":"api/basic_json/find/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/find/#complexity","title":"Complexity","text":"<p>Logarithmic in the size of the JSON object.</p>"},{"location":"api/basic_json/find/#notes","title":"Notes","text":"<p>This method always returns <code>end()</code> when executed on a JSON type that is not an object.</p>"},{"location":"api/basic_json/find/#examples","title":"Examples","text":"Example: (1) find object element by key <p>The example shows how <code>find()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call find\n auto it_two = j_object.find(\"two\");\n auto it_three = j_object.find(\"three\");\n\n // print values\n std::cout << std::boolalpha;\n std::cout << \"\\\"two\\\" was found: \" << (it_two != j_object.end()) << '\\n';\n std::cout << \"value at key \\\"two\\\": \" << *it_two << '\\n';\n std::cout << \"\\\"three\\\" was found: \" << (it_three != j_object.end()) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n</code></pre> Example: (2) find object element by key using string_view <p>The example shows how <code>find()</code> is used.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call find\n auto it_two = j_object.find(\"two\"sv);\n auto it_three = j_object.find(\"three\"sv);\n\n // print values\n std::cout << std::boolalpha;\n std::cout << \"\\\"two\\\" was found: \" << (it_two != j_object.end()) << '\\n';\n std::cout << \"value at key \\\"two\\\": \" << *it_two << '\\n';\n std::cout << \"\\\"three\\\" was found: \" << (it_three != j_object.end()) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n</code></pre>"},{"location":"api/basic_json/find/#see-also","title":"See also","text":"<ul> <li>contains checks whether a key exists</li> </ul>"},{"location":"api/basic_json/find/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.11.0.</li> <li>Added in version 1.0.0. Changed to support comparable types in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/flatten/","title":"nlohmann::basic_json::flatten","text":"<pre><code>basic_json flatten() const;\n</code></pre> <p>The function creates a JSON object whose keys are JSON pointers (see RFC 6901) and whose values are all primitive (see <code>is_primitive()</code> for more information). The original JSON value can be restored using the <code>unflatten()</code> function.</p>"},{"location":"api/basic_json/flatten/#return-value","title":"Return value","text":"<p>an object that maps JSON pointers to primitive values</p>"},{"location":"api/basic_json/flatten/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/flatten/#complexity","title":"Complexity","text":"<p>Linear in the size the JSON value.</p>"},{"location":"api/basic_json/flatten/#notes","title":"Notes","text":"<p>Empty objects and arrays are flattened to <code>null</code> and will not be reconstructed correctly by the <code>unflatten()</code> function.</p>"},{"location":"api/basic_json/flatten/#examples","title":"Examples","text":"Example <p>The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value\n json j =\n {\n {\"pi\", 3.141},\n {\"happy\", true},\n {\"name\", \"Niels\"},\n {\"nothing\", nullptr},\n {\n \"answer\", {\n {\"everything\", 42}\n }\n },\n {\"list\", {1, 0, 2}},\n {\n \"object\", {\n {\"currency\", \"USD\"},\n {\"value\", 42.99}\n }\n }\n };\n\n // call flatten()\n std::cout << std::setw(4) << j.flatten() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"/answer/everything\": 42,\n \"/happy\": true,\n \"/list/0\": 1,\n \"/list/1\": 0,\n \"/list/2\": 2,\n \"/name\": \"Niels\",\n \"/nothing\": null,\n \"/object/currency\": \"USD\",\n \"/object/value\": 42.99,\n \"/pi\": 3.141\n}\n</code></pre>"},{"location":"api/basic_json/flatten/#see-also","title":"See also","text":"<ul> <li>unflatten the reverse function</li> </ul>"},{"location":"api/basic_json/flatten/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> </ul>"},{"location":"api/basic_json/from_bjdata/","title":"nlohmann::basic_json::from_bjdata","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic basic_json from_bjdata(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_bjdata(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n</code></pre> <p>Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.</p> <ol> <li>Reads from a compatible input.</li> <li>Reads from an iterator range.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/from_bjdata/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> a compatible iterator type"},{"location":"api/basic_json/from_bjdata/#parameters","title":"Parameters","text":"<code>i</code> (in) an input in BJData format convertible to an input adapter <code>first</code> (in) iterator to start of the input <code>last</code> (in) iterator to end of the input <code>strict</code> (in) whether to expect the input to be consumed until EOF (<code>true</code> by default) <code>allow_exceptions</code> (in) whether to throw exceptions in case of a parse error (optional, <code>true</code> by default)"},{"location":"api/basic_json/from_bjdata/#return-value","title":"Return value","text":"<p>deserialized JSON value; in case of a parse error and <code>allow_exceptions</code> set to <code>false</code>, the return value will be <code>value_t::discarded</code>. The latter can be checked with <code>is_discarded</code>.</p>"},{"location":"api/basic_json/from_bjdata/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/from_bjdata/#exceptions","title":"Exceptions","text":"<ul> <li>Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when <code>strict</code> was set to true</li> <li>Throws parse_error.112 if a parse error occurs</li> <li>Throws parse_error.113 if a string could not be parsed successfully</li> </ul>"},{"location":"api/basic_json/from_bjdata/#complexity","title":"Complexity","text":"<p>Linear in the size of the input.</p>"},{"location":"api/basic_json/from_bjdata/#examples","title":"Examples","text":"Example <p>The example shows the deserialization of a byte vector in BJData format to a JSON value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with BJData\n json j = json::from_bjdata(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"api/basic_json/from_bjdata/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/basic_json/from_bson/","title":"nlohmann::basic_json::from_bson","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic basic_json from_bson(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_bson(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n</code></pre> <p>Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.</p> <ol> <li>Reads from a compatible input.</li> <li>Reads from an iterator range.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/from_bson/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> a compatible iterator type"},{"location":"api/basic_json/from_bson/#parameters","title":"Parameters","text":"<code>i</code> (in) an input in BSON format convertible to an input adapter <code>first</code> (in) iterator to start of the input <code>last</code> (in) iterator to end of the input <code>strict</code> (in) whether to expect the input to be consumed until EOF (<code>true</code> by default) <code>allow_exceptions</code> (in) whether to throw exceptions in case of a parse error (optional, <code>true</code> by default)"},{"location":"api/basic_json/from_bson/#return-value","title":"Return value","text":"<p>deserialized JSON value; in case of a parse error and <code>allow_exceptions</code> set to <code>false</code>, the return value will be <code>value_t::discarded</code>. The latter can be checked with <code>is_discarded</code>.</p>"},{"location":"api/basic_json/from_bson/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/from_bson/#exceptions","title":"Exceptions","text":"<p>Throws <code>parse_error.114</code> if an unsupported BSON record type is encountered.</p>"},{"location":"api/basic_json/from_bson/#complexity","title":"Complexity","text":"<p>Linear in the size of the input.</p>"},{"location":"api/basic_json/from_bson/#examples","title":"Examples","text":"Example <p>The example shows the deserialization of a byte vector in BSON format to a JSON value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d,\n 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73,\n 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00\n };\n\n // deserialize it with BSON\n json j = json::from_bson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"api/basic_json/from_bson/#see-also","title":"See also","text":"<ul> <li>BSON specification</li> <li>to_bson for the analogous serialization</li> <li>from_cbor for the related CBOR format</li> <li>from_msgpack for the related MessagePack format</li> <li>from_ubjson for the related UBJSON format</li> </ul>"},{"location":"api/basic_json/from_bson/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.4.0.</li> </ul> <p>Deprecation</p> <ul> <li>Overload (2) replaces calls to <code>from_bson</code> with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_bson(ptr, len, ...);</code> with <code>from_bson(ptr, ptr+len, ...);</code>.</li> <li>Overload (2) replaces calls to <code>from_bson</code> with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_bson({ptr, ptr+len}, ...);</code> with <code>from_bson(ptr, ptr+len, ...);</code>.</li> </ul> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/from_cbor/","title":"nlohmann::basic_json::from_cbor","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic basic_json from_cbor(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);\n\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_cbor(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);\n</code></pre> <p>Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.</p> <ol> <li>Reads from a compatible input.</li> <li>Reads from an iterator range.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/from_cbor/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> a compatible iterator type"},{"location":"api/basic_json/from_cbor/#parameters","title":"Parameters","text":"<code>i</code> (in) an input in CBOR format convertible to an input adapter <code>first</code> (in) iterator to start of the input <code>last</code> (in) iterator to end of the input <code>strict</code> (in) whether to expect the input to be consumed until EOF (<code>true</code> by default) <code>allow_exceptions</code> (in) whether to throw exceptions in case of a parse error (optional, <code>true</code> by default) <code>tag_handler</code> (in) how to treat CBOR tags (optional, <code>error</code> by default); see <code>cbor_tag_handler_t</code> for more information"},{"location":"api/basic_json/from_cbor/#return-value","title":"Return value","text":"<p>deserialized JSON value; in case of a parse error and <code>allow_exceptions</code> set to <code>false</code>, the return value will be <code>value_t::discarded</code>. The latter can be checked with <code>is_discarded</code>.</p>"},{"location":"api/basic_json/from_cbor/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/from_cbor/#exceptions","title":"Exceptions","text":"<ul> <li>Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when <code>strict</code> was set to true</li> <li>Throws parse_error.112 if unsupported features from CBOR were used in the given input or if the input is not valid CBOR</li> <li>Throws parse_error.113 if a string was expected as map key, but not found</li> </ul>"},{"location":"api/basic_json/from_cbor/#complexity","title":"Complexity","text":"<p>Linear in the size of the input.</p>"},{"location":"api/basic_json/from_cbor/#examples","title":"Examples","text":"Example <p>The example shows the deserialization of a byte vector in CBOR format to a JSON value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with CBOR\n json j = json::from_cbor(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"api/basic_json/from_cbor/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.9.</li> <li>Parameter <code>start_index</code> since version 2.1.1.</li> <li>Changed to consume input adapters, removed <code>start_index</code> parameter, and added <code>strict</code> parameter in version 3.0.0.</li> <li>Added <code>allow_exceptions</code> parameter in version 3.2.0.</li> <li>Added <code>tag_handler</code> parameter in version 3.9.0.</li> </ul> <p>Deprecation</p> <ul> <li>Overload (2) replaces calls to <code>from_cbor</code> with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_cbor(ptr, len, ...);</code> with <code>from_cbor(ptr, ptr+len, ...);</code>.</li> <li>Overload (2) replaces calls to <code>from_cbor</code> with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_cbor({ptr, ptr+len}, ...);</code> with <code>from_cbor(ptr, ptr+len, ...);</code>.</li> </ul> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/from_msgpack/","title":"nlohmann::basic_json::from_msgpack","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic basic_json from_msgpack(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_msgpack(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n</code></pre> <p>Deserializes a given input to a JSON value using the MessagePack serialization format.</p> <ol> <li>Reads from a compatible input.</li> <li>Reads from an iterator range.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/from_msgpack/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> a compatible iterator type"},{"location":"api/basic_json/from_msgpack/#parameters","title":"Parameters","text":"<code>i</code> (in) an input in MessagePack format convertible to an input adapter <code>first</code> (in) iterator to start of the input <code>last</code> (in) iterator to end of the input <code>strict</code> (in) whether to expect the input to be consumed until EOF (<code>true</code> by default) <code>allow_exceptions</code> (in) whether to throw exceptions in case of a parse error (optional, <code>true</code> by default)"},{"location":"api/basic_json/from_msgpack/#return-value","title":"Return value","text":"<p>deserialized JSON value; in case of a parse error and <code>allow_exceptions</code> set to <code>false</code>, the return value will be <code>value_t::discarded</code>. The latter can be checked with <code>is_discarded</code>.</p>"},{"location":"api/basic_json/from_msgpack/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/from_msgpack/#exceptions","title":"Exceptions","text":"<ul> <li>Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when <code>strict</code> was set to true</li> <li>Throws parse_error.112 if unsupported features from MessagePack were used in the given input or if the input is not valid MessagePack</li> <li>Throws parse_error.113 if a string was expected as map key, but not found</li> </ul>"},{"location":"api/basic_json/from_msgpack/#complexity","title":"Complexity","text":"<p>Linear in the size of the input.</p>"},{"location":"api/basic_json/from_msgpack/#examples","title":"Examples","text":"Example <p>The example shows the deserialization of a byte vector in MessagePack format to a JSON value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"api/basic_json/from_msgpack/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.9.</li> <li>Parameter <code>start_index</code> since version 2.1.1.</li> <li>Changed to consume input adapters, removed <code>start_index</code> parameter, and added <code>strict</code> parameter in version 3.0.0.</li> <li>Added <code>allow_exceptions</code> parameter in version 3.2.0.</li> </ul> <p>Deprecation</p> <ul> <li>Overload (2) replaces calls to <code>from_msgpack</code> with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_msgpack(ptr, len, ...);</code> with <code>from_msgpack(ptr, ptr+len, ...);</code>.</li> <li>Overload (2) replaces calls to <code>from_cbor</code> with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_msgpack({ptr, ptr+len}, ...);</code> with <code>from_msgpack(ptr, ptr+len, ...);</code>.</li> </ul> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/from_ubjson/","title":"nlohmann::basic_json::from_ubjson","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic basic_json from_ubjson(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_ubjson(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n</code></pre> <p>Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format.</p> <ol> <li>Reads from a compatible input.</li> <li>Reads from an iterator range.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/from_ubjson/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> a compatible iterator type"},{"location":"api/basic_json/from_ubjson/#parameters","title":"Parameters","text":"<code>i</code> (in) an input in UBJSON format convertible to an input adapter <code>first</code> (in) iterator to start of the input <code>last</code> (in) iterator to end of the input <code>strict</code> (in) whether to expect the input to be consumed until EOF (<code>true</code> by default) <code>allow_exceptions</code> (in) whether to throw exceptions in case of a parse error (optional, <code>true</code> by default)"},{"location":"api/basic_json/from_ubjson/#return-value","title":"Return value","text":"<p>deserialized JSON value; in case of a parse error and <code>allow_exceptions</code> set to <code>false</code>, the return value will be <code>value_t::discarded</code>. The latter can be checked with <code>is_discarded</code>.</p>"},{"location":"api/basic_json/from_ubjson/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/from_ubjson/#exceptions","title":"Exceptions","text":"<ul> <li>Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when <code>strict</code> was set to true</li> <li>Throws parse_error.112 if a parse error occurs</li> <li>Throws parse_error.113 if a string could not be parsed successfully</li> </ul>"},{"location":"api/basic_json/from_ubjson/#complexity","title":"Complexity","text":"<p>Linear in the size of the input.</p>"},{"location":"api/basic_json/from_ubjson/#examples","title":"Examples","text":"Example <p>The example shows the deserialization of a byte vector in UBJSON format to a JSON value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with UBJSON\n json j = json::from_ubjson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"api/basic_json/from_ubjson/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.1.0.</li> <li>Added <code>allow_exceptions</code> parameter in version 3.2.0.</li> </ul> <p>Deprecation</p> <ul> <li>Overload (2) replaces calls to <code>from_ubjson</code> with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_ubjson(ptr, len, ...);</code> with <code>from_ubjson(ptr, ptr+len, ...);</code>.</li> <li>Overload (2) replaces calls to <code>from_ubjson</code> with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>from_ubjson({ptr, ptr+len}, ...);</code> with <code>from_ubjson(ptr, ptr+len, ...);</code>.</li> </ul> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/front/","title":"nlohmann::basic_json::front","text":"<pre><code>reference front();\nconst_reference front() const;\n</code></pre> <p>Returns a reference to the first element in the container. For a JSON container <code>c</code>, the expression <code>c.front()</code> is equivalent to <code>*c.begin()</code>.</p>"},{"location":"api/basic_json/front/#return-value","title":"Return value","text":"<p>In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.</p>"},{"location":"api/basic_json/front/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/front/#exceptions","title":"Exceptions","text":"<p>If the JSON value is <code>null</code>, exception <code>invalid_iterator.214</code> is thrown.</p>"},{"location":"api/basic_json/front/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/front/#notes","title":"Notes","text":"<p>Precondition</p> <p>The array or object must not be empty. Calling <code>front</code> on an empty array or object yields undefined behavior.</p>"},{"location":"api/basic_json/front/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>front()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call front()\n //std::cout << j_null.front() << '\\n'; // would throw\n std::cout << j_boolean.front() << '\\n';\n std::cout << j_number_integer.front() << '\\n';\n std::cout << j_number_float.front() << '\\n';\n std::cout << j_object.front() << '\\n';\n //std::cout << j_object_empty.front() << '\\n'; // undefined behavior\n std::cout << j_array.front() << '\\n';\n //std::cout << j_array_empty.front() << '\\n'; // undefined behavior\n std::cout << j_string.front() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\n17\n23.42\n1\n1\n\"Hello, world\"\n</code></pre>"},{"location":"api/basic_json/front/#see-also","title":"See also","text":"<ul> <li>back to access the last element</li> </ul>"},{"location":"api/basic_json/front/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Adjusted code to return reference to binary values in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/get/","title":"nlohmann::basic_json::get","text":"<pre><code>// (1)\ntemplate<typename ValueType>\nValueType get() const noexcept(\n noexcept(JSONSerializer<ValueType>::from_json(\n std::declval<const basic_json_t&>(), std::declval<ValueType&>())));\n\n// (2)\ntemplate<typename BasicJsonType>\nBasicJsonType get() const;\n\n// (3)\ntemplate<typename PointerType>\nPointerType get_ptr();\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n</code></pre> <ol> <li> <p>Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the <code>json_serializer<ValueType></code> <code>from_json()</code> method.</p> <p>The function is equivalent to executing <pre><code>ValueType ret;\nJSONSerializer<ValueType>::from_json(*this, ret);\nreturn ret;\n</code></pre></p> <p>This overload is chosen if:</p> <ul> <li><code>ValueType</code> is not <code>basic_json</code>,</li> <li><code>json_serializer<ValueType></code> has a <code>from_json()</code> method of the form <code>void from_json(const basic_json&, ValueType&)</code>, and</li> <li><code>json_serializer<ValueType></code> does not have a <code>from_json()</code> method of the form <code>ValueType from_json(const basic_json&)</code></li> </ul> <p>If the type is not CopyConstructible and not DefaultConstructible, the value is converted by calling the <code>json_serializer<ValueType></code> <code>from_json()</code> method.</p> <p>The function is then equivalent to executing <pre><code>return JSONSerializer<ValueTypeCV>::from_json(*this);\n</code></pre></p> <p>This overload is chosen if:</p> <ul> <li><code>ValueType</code> is not <code>basic_json</code> and</li> <li><code>json_serializer<ValueType></code> has a <code>from_json()</code> method of the form <code>ValueType from_json(const basic_json&)</code></li> </ul> <p>If <code>json_serializer<ValueType></code> has both overloads of <code>from_json()</code>, the latter one is chosen.</p> </li> <li> <p>Overload for <code>basic_json</code> specializations. The function is equivalent to executing <pre><code>return *this;\n</code></pre></p> </li> <li> <p>Explicit pointer access to the internally stored JSON value. No copies are made.</p> </li> </ol>"},{"location":"api/basic_json/get/#template-parameters","title":"Template parameters","text":"<code>ValueType</code> the value type to return <code>BasicJsonType</code> a specialization of <code>basic_json</code> <code>PointerType</code> pointer type; must be a pointer to <code>array_t</code>, <code>object_t</code>, <code>string_t</code>, <code>boolean_t</code>, <code>number_integer_t</code>, or <code>number_unsigned_t</code>, <code>number_float_t</code>, or <code>binary_t</code>. Other types will not compile."},{"location":"api/basic_json/get/#return-value","title":"Return value","text":"<ol> <li>copy of the JSON value, converted to <code>ValueType</code></li> <li>a copy of <code>*this</code>, converted into <code>BasicJsonType</code></li> <li>pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; <code>nullptr</code> otherwise</li> </ol>"},{"location":"api/basic_json/get/#exceptions","title":"Exceptions","text":"<p>Depends on what <code>json_serializer<ValueType></code> <code>from_json()</code> method throws</p>"},{"location":"api/basic_json/get/#notes","title":"Notes","text":"<p>Undefined behavior</p> <p>Writing data to the pointee (overload 3) of the result yields an undefined state.</p>"},{"location":"api/basic_json/get/#examples","title":"Examples","text":"Example <p>The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard <code>std::vector<short></code>, (3) A JSON object can be converted to C++ associative containers such as <code>std::unordered_map<std::string, json></code>.</p> <pre><code>#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use explicit conversions\n auto v1 = json_types[\"boolean\"].template get<bool>();\n auto v2 = json_types[\"number\"][\"integer\"].template get<int>();\n auto v3 = json_types[\"number\"][\"integer\"].template get<short>();\n auto v4 = json_types[\"number\"][\"floating-point\"].template get<float>();\n auto v5 = json_types[\"number\"][\"floating-point\"].template get<int>();\n auto v6 = json_types[\"string\"].template get<std::string>();\n auto v7 = json_types[\"array\"].template get<std::vector<short>>();\n auto v8 = json_types.template get<std::unordered_map<std::string, json>>();\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n</code></pre> Example <p>The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a <code>#cpp nullptr</code> is returned if the value and the requested pointer type does not match.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting pointers\n auto p1 = value.template get<const json::number_integer_t*>();\n auto p2 = value.template get<json::number_integer_t*>();\n auto p3 = value.template get<json::number_integer_t* const>();\n auto p4 = value.template get<const json::number_integer_t* const>();\n auto p5 = value.template get<json::number_float_t*>();\n\n // print the pointees\n std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\\n';\n std::cout << std::boolalpha << (p5 == nullptr) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>17 17 17 17\ntrue\n</code></pre>"},{"location":"api/basic_json/get/#version-history","title":"Version history","text":"<ol> <li>Since version 2.1.0.</li> <li>Since version 2.1.0. Extended to work with other specializations of <code>basic_json</code> in version 3.2.0.</li> <li>Since version 1.0.0.</li> </ol>"},{"location":"api/basic_json/get_allocator/","title":"nlohmann::basic_json::get_allocator","text":"<pre><code>static allocator_type get_allocator();\n</code></pre> <p>Returns the allocator associated with the container.</p>"},{"location":"api/basic_json/get_allocator/#return-value","title":"Return value","text":"<p>associated allocator</p>"},{"location":"api/basic_json/get_allocator/#examples","title":"Examples","text":"Example <p>The example shows how <code>get_allocator()</code> is used to created <code>json</code> values.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n auto alloc = json::get_allocator();\n using traits_t = std::allocator_traits<decltype(alloc)>;\n\n json* j = traits_t::allocate(alloc, 1);\n traits_t::construct(alloc, j, \"Hello, world!\");\n\n std::cout << *j << std::endl;\n\n traits_t::destroy(alloc, j);\n traits_t::deallocate(alloc, j, 1);\n}\n</code></pre> <p>Output:</p> <pre><code>\"Hello, world!\"\n</code></pre>"},{"location":"api/basic_json/get_allocator/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/get_binary/","title":"nlohmann::basic_json::get_binary","text":"<pre><code>binary_t& get_binary();\n\nconst binary_t& get_binary() const;\n</code></pre> <p>Returns a reference to the stored binary value.</p>"},{"location":"api/basic_json/get_binary/#return-value","title":"Return value","text":"<p>Reference to binary value.</p>"},{"location":"api/basic_json/get_binary/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/get_binary/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.302</code> if the value is not binary</p>"},{"location":"api/basic_json/get_binary/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/get_binary/#examples","title":"Examples","text":"Example <p>The following code shows how to query a binary value.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary vector\n std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};\n\n // create a binary JSON value with subtype 42\n json j = json::binary(vec, 42);\n\n // output type and subtype\n std::cout << \"type: \" << j.type_name() << \", subtype: \" << j.get_binary().subtype() << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>type: binary, subtype: 42\n</code></pre>"},{"location":"api/basic_json/get_binary/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/get_ptr/","title":"nlohmann::basic_json::get_ptr","text":"<pre><code>template<typename PointerType>\nPointerType get_ptr() noexcept;\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n</code></pre> <p>Implicit pointer access to the internally stored JSON value. No copies are made.</p>"},{"location":"api/basic_json/get_ptr/#template-parameters","title":"Template parameters","text":"<code>PointerType</code> pointer type; must be a pointer to <code>array_t</code>, <code>object_t</code>, <code>string_t</code>, <code>boolean_t</code>, <code>number_integer_t</code>, or <code>number_unsigned_t</code>, <code>number_float_t</code>, or <code>binary_t</code>. Other types will not compile."},{"location":"api/basic_json/get_ptr/#return-value","title":"Return value","text":"<p>pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; <code>nullptr</code> otherwise</p>"},{"location":"api/basic_json/get_ptr/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/get_ptr/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/get_ptr/#notes","title":"Notes","text":"<p>Undefined behavior</p> <p>Writing data to the pointee of the result yields an undefined state.</p>"},{"location":"api/basic_json/get_ptr/#examples","title":"Examples","text":"Example <p>The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a <code>nullptr</code> is returned if the value and the requested pointer type does not match.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting pointers\n auto p1 = value.get_ptr<const json::number_integer_t*>();\n auto p2 = value.get_ptr<json::number_integer_t*>();\n auto p3 = value.get_ptr<json::number_integer_t* const>();\n auto p4 = value.get_ptr<const json::number_integer_t* const>();\n auto p5 = value.get_ptr<json::number_float_t*>();\n\n // print the pointees\n std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\\n';\n std::cout << std::boolalpha << (p5 == nullptr) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>17 17 17 17\ntrue\n</code></pre>"},{"location":"api/basic_json/get_ptr/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/get_ref/","title":"nlohmann::basic_json::get_ref","text":"<pre><code>template<typename ReferenceType>\nReferenceType get_ref();\n\ntemplate<typename ReferenceType>\nconst ReferenceType get_ref() const;\n</code></pre> <p>Implicit reference access to the internally stored JSON value. No copies are made.</p>"},{"location":"api/basic_json/get_ref/#template-parameters","title":"Template parameters","text":"<code>ReferenceType</code> reference type; must be a reference to <code>array_t</code>, <code>object_t</code>, <code>string_t</code>, <code>boolean_t</code>, <code>number_integer_t</code>, or <code>number_unsigned_t</code>, <code>number_float_t</code>, or <code>binary_t</code>. Enforced by a static assertion."},{"location":"api/basic_json/get_ref/#return-value","title":"Return value","text":"<p>reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws <code>type_error.303</code> otherwise</p>"},{"location":"api/basic_json/get_ref/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/get_ref/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.303</code> if the requested reference type does not match the stored JSON value type; example: <code>\"incompatible ReferenceType for get_ref, actual type is binary\"</code>.</p>"},{"location":"api/basic_json/get_ref/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/get_ref/#notes","title":"Notes","text":"<p>Undefined behavior</p> <p>Writing data to the referee of the result yields an undefined state.</p>"},{"location":"api/basic_json/get_ref/#examples","title":"Examples","text":"Example <p>The example shows several calls to <code>get_ref()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting references\n auto r1 = value.get_ref<const json::number_integer_t&>();\n auto r2 = value.get_ref<json::number_integer_t&>();\n\n // print the values\n std::cout << r1 << ' ' << r2 << '\\n';\n\n // incompatible type throws exception\n try\n {\n auto r3 = value.get_ref<json::number_float_t&>();\n }\n catch (const json::type_error& ex)\n {\n std::cout << ex.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>17 17\n[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\n</code></pre>"},{"location":"api/basic_json/get_ref/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.1.0.</li> <li>Extended to binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/get_to/","title":"nlohmann::basic_json::get_to","text":"<pre><code>template<typename ValueType>\nValueType& get_to(ValueType& v) const noexcept(\n noexcept(JSONSerializer<ValueType>::from_json(\n std::declval<const basic_json_t&>(), v)));\n</code></pre> <p>Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the <code>json_serializer<ValueType></code> <code>from_json()</code> method.</p> <p>The function is equivalent to executing <pre><code>ValueType v;\nJSONSerializer<ValueType>::from_json(*this, v);\n</code></pre></p> <p>This overload is chosen if:</p> <ul> <li><code>ValueType</code> is not <code>basic_json</code>,</li> <li><code>json_serializer<ValueType></code> has a <code>from_json()</code> method of the form <code>void from_json(const basic_json&, ValueType&)</code></li> </ul>"},{"location":"api/basic_json/get_to/#template-parameters","title":"Template parameters","text":"<code>ValueType</code> the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"<p>the input parameter, allowing chaining calls</p>"},{"location":"api/basic_json/get_to/#exceptions","title":"Exceptions","text":"<p>Depends on what <code>json_serializer<ValueType></code> <code>from_json()</code> method throws</p>"},{"location":"api/basic_json/get_to/#examples","title":"Examples","text":"Example <p>The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard <code>std::vector<short></code>, (3) A JSON object can be converted to C++ associative containers such as <code>#cpp std::unordered_map<std::string, json></code>.</p> <pre><code>#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n bool v1;\n int v2;\n short v3;\n float v4;\n int v5;\n std::string v6;\n std::vector<short> v7;\n std::unordered_map<std::string, json> v8;\n\n // use explicit conversions\n json_types[\"boolean\"].get_to(v1);\n json_types[\"number\"][\"integer\"].get_to(v2);\n json_types[\"number\"][\"integer\"].get_to(v3);\n json_types[\"number\"][\"floating-point\"].get_to(v4);\n json_types[\"number\"][\"floating-point\"].get_to(v5);\n json_types[\"string\"].get_to(v6);\n json_types[\"array\"].get_to(v7);\n json_types.get_to(v8);\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n</code></pre>"},{"location":"api/basic_json/get_to/#version-history","title":"Version history","text":"<ul> <li>Since version 3.3.0.</li> </ul>"},{"location":"api/basic_json/input_format_t/","title":"nlohmann::basic_json::input_format_t","text":"<pre><code>enum class input_format_t {\n json,\n cbor,\n msgpack,\n ubjson,\n bson,\n bjdata\n};\n</code></pre> <p>This enumeration is used in the <code>sax_parse</code> function to choose the input format to parse:</p> json JSON (JavaScript Object Notation) cbor CBOR (Concise Binary Object Representation) msgpack MessagePack ubjson UBJSON (Universal Binary JSON) bson BSON (Binary JSON) bjdata BJData (Binary JData)"},{"location":"api/basic_json/input_format_t/#examples","title":"Examples","text":"Example <p>The example below shows how an <code>input_format_t</code> enum value is passed to <code>sax_parse</code> to set the input format to CBOR.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // CBOR byte string\n std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse CBOR\n bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>binary(val=[...])\n\nresult: true\n</code></pre>"},{"location":"api/basic_json/input_format_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/basic_json/insert/","title":"nlohmann::basic_json::insert","text":"<pre><code>// (1)\niterator insert(const_iterator pos, const basic_json& val);\niterator insert(const_iterator pos, basic_json&& val);\n\n// (2)\niterator insert(const_iterator pos, size_type cnt, const basic_json& val);\n\n// (3)\niterator insert(const_iterator pos, const_iterator first, const_iterator last);\n\n// (4)\niterator insert(const_iterator pos, initializer_list_t ilist);\n\n// (5)\nvoid insert(const_iterator first, const_iterator last);\n</code></pre> <ol> <li>Inserts element <code>val</code> into array before iterator <code>pos</code>.</li> <li>Inserts <code>cnt</code> copies of <code>val</code> into array before iterator <code>pos</code>.</li> <li>Inserts elements from range <code>[first, last)</code> into array before iterator <code>pos</code>.</li> <li>Inserts elements from initializer list <code>ilist</code> into array before iterator <code>pos</code>.</li> <li>Inserts elements from range <code>[first, last)</code> into object.</li> </ol>"},{"location":"api/basic_json/insert/#parameters","title":"Parameters","text":"<code>pos</code> (in) iterator before which the content will be inserted; may be the <code>end()</code> iterator <code>val</code> (in) value to insert <code>cnt</code> (in) number of copies of <code>val</code> to insert <code>first</code> (in) begin of the range of elements to insert <code>last</code> (in) end of the range of elements to insert <code>ilist</code> (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"<ol> <li>iterator pointing to the inserted <code>val</code>.</li> <li>iterator pointing to the first element inserted, or <code>pos</code> if <code>cnt==0</code></li> <li>iterator pointing to the first element inserted, or <code>pos</code> if <code>first==last</code></li> <li>iterator pointing to the first element inserted, or <code>pos</code> if <code>ilist</code> is empty</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/insert/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/insert/#exceptions","title":"Exceptions","text":"<ol> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.309</code> if called on JSON values other than arrays; example: <code>\"cannot use insert() with string\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.309</code> if called on JSON values other than arrays; example: <code>\"cannot use insert() with string\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.309</code> if called on JSON values other than arrays; example: <code>\"cannot use insert() with string\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> <li>Throws <code>invalid_iterator.210</code> if <code>first</code> and <code>last</code> do not belong to the same JSON value; example: <code>\"iterators do not fit\"</code></li> <li>Throws <code>invalid_iterator.211</code> if <code>first</code> or <code>last</code> are iterators into container for which insert is called; example: <code>\"passed iterators may not belong to container\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.309</code> if called on JSON values other than arrays; example: <code>\"cannot use insert() with string\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.309</code> if called on JSON values other than objects; example: <code>\"cannot use insert() with string\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> <li>Throws <code>invalid_iterator.210</code> if <code>first</code> and <code>last</code> do not belong to the same JSON value; example: <code>\"iterators do not fit\"</code></li> </ul> </li> </ol>"},{"location":"api/basic_json/insert/#complexity","title":"Complexity","text":"<ol> <li>Constant plus linear in the distance between <code>pos</code> and end of the container.</li> <li>Linear in <code>cnt</code> plus linear in the distance between <code>pos</code> and end of the container.</li> <li>Linear in <code>std::distance(first, last)</code> plus linear in the distance between <code>pos</code> and end of the container.</li> <li>Linear in <code>ilist.size()</code> plus linear in the distance between <code>pos</code> and end of the container.</li> <li>Logarithmic: <code>O(N*log(size() + N))</code>, where <code>N</code> is the number of elements to insert.</li> </ol>"},{"location":"api/basic_json/insert/#examples","title":"Examples","text":"Example (1): insert element into array <p>The example shows how <code>insert()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 10 before number 3\n auto new_pos = v.insert(v.begin() + 2, 10);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>10\n[1,2,10,3,4]\n</code></pre> Example (2): insert copies of element into array <p>The example shows how <code>insert()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 7 copies of number 7 before number 3\n auto new_pos = v.insert(v.begin() + 2, 7, 7);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>7\n[1,2,7,7,7,7,7,7,7,3,4]\n</code></pre> Example (3): insert range of elements into array <p>The example shows how <code>insert()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // create a JSON array to copy values from\n json v2 = {\"one\", \"two\", \"three\", \"four\"};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), v2.begin(), v2.end());\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>\"one\"\n[1,2,3,4,\"one\",\"two\",\"three\",\"four\"]\n</code></pre> Example (4): insert elements from initializer list into array <p>The example shows how <code>insert()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), {7, 8, 9});\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>7\n[1,2,3,4,7,8,9]\n</code></pre> Example (5): insert range of elements into object <p>The example shows how <code>insert()</code> is used.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create two JSON objects\n json j1 = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n json j2 = {{\"eleven\", \"elf\"}, {\"seventeen\", \"siebzehn\"}};\n\n // output objects\n std::cout << j1 << '\\n';\n std::cout << j2 << '\\n';\n\n // insert range from j2 to j1\n j1.insert(j2.begin(), j2.end());\n\n // output result of insert call\n std::cout << j1 << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":\"eins\",\"two\":\"zwei\"}\n{\"eleven\":\"elf\",\"seventeen\":\"siebzehn\"}\n{\"eleven\":\"elf\",\"one\":\"eins\",\"seventeen\":\"siebzehn\",\"two\":\"zwei\"}\n</code></pre>"},{"location":"api/basic_json/insert/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0.</li> <li>Added in version 1.0.0.</li> <li>Added in version 1.0.0.</li> <li>Added in version 1.0.0.</li> <li>Added in version 3.0.0.</li> </ol>"},{"location":"api/basic_json/invalid_iterator/","title":"nlohmann::basic_json::invalid_iterator","text":"<pre><code>class invalid_iterator : public exception;\n</code></pre> <p>This exception is thrown if iterators passed to a library function do not match the expected semantics.</p> <p>Exceptions have ids 2xx (see list of iterator errors).</p> <p></p>"},{"location":"api/basic_json/invalid_iterator/#member-functions","title":"Member functions","text":"<ul> <li>what - returns explanatory string</li> </ul>"},{"location":"api/basic_json/invalid_iterator/#member-variables","title":"Member variables","text":"<ul> <li>id - the id of the exception</li> </ul>"},{"location":"api/basic_json/invalid_iterator/#examples","title":"Examples","text":"Example <p>The following code shows how a <code>invalid_iterator</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling iterator::key() on non-object iterator\n json j = \"string\";\n json::iterator it = j.begin();\n auto k = it.key();\n }\n catch (const json::invalid_iterator& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n</code></pre>"},{"location":"api/basic_json/invalid_iterator/#see-also","title":"See also","text":"<ul> <li>List of iterator errors</li> <li><code>parse_error</code> for exceptions indicating a parse error</li> <li><code>type_error</code> for exceptions indicating executing a member function with a wrong type</li> <li><code>out_of_range</code> for exceptions indicating access out of the defined range</li> <li><code>other_error</code> for exceptions indicating other library errors</li> </ul>"},{"location":"api/basic_json/invalid_iterator/#version-history","title":"Version history","text":"<ul> <li>Since version 3.0.0.</li> </ul>"},{"location":"api/basic_json/is_array/","title":"nlohmann::basic_json::is_array","text":"<pre><code>constexpr bool is_array() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is an array.</p>"},{"location":"api/basic_json/is_array/#return-value","title":"Return value","text":"<p><code>true</code> if type is an array, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_array/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_array/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_array/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_array()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_array()\n std::cout << std::boolalpha;\n std::cout << j_null.is_array() << '\\n';\n std::cout << j_boolean.is_array() << '\\n';\n std::cout << j_number_integer.is_array() << '\\n';\n std::cout << j_number_unsigned_integer.is_array() << '\\n';\n std::cout << j_number_float.is_array() << '\\n';\n std::cout << j_object.is_array() << '\\n';\n std::cout << j_array.is_array() << '\\n';\n std::cout << j_string.is_array() << '\\n';\n std::cout << j_binary.is_array() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_array/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_binary/","title":"nlohmann::basic_json::is_binary","text":"<pre><code>constexpr bool is_binary() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is binary array.</p>"},{"location":"api/basic_json/is_binary/#return-value","title":"Return value","text":"<p><code>true</code> if type is binary, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_binary/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_binary/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_binary/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_binary()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_binary()\n std::cout << std::boolalpha;\n std::cout << j_null.is_binary() << '\\n';\n std::cout << j_boolean.is_binary() << '\\n';\n std::cout << j_number_integer.is_binary() << '\\n';\n std::cout << j_number_unsigned_integer.is_binary() << '\\n';\n std::cout << j_number_float.is_binary() << '\\n';\n std::cout << j_object.is_binary() << '\\n';\n std::cout << j_array.is_binary() << '\\n';\n std::cout << j_string.is_binary() << '\\n';\n std::cout << j_binary.is_binary() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\n</code></pre>"},{"location":"api/basic_json/is_binary/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/is_boolean/","title":"nlohmann::basic_json::is_boolean","text":"<pre><code>constexpr bool is_boolean() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is <code>true</code> or <code>false</code>.</p>"},{"location":"api/basic_json/is_boolean/#return-value","title":"Return value","text":"<p><code>true</code> if type is boolean, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_boolean/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_boolean/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_boolean/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_boolean()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_boolean()\n std::cout << std::boolalpha;\n std::cout << j_null.is_boolean() << '\\n';\n std::cout << j_boolean.is_boolean() << '\\n';\n std::cout << j_number_integer.is_boolean() << '\\n';\n std::cout << j_number_unsigned_integer.is_boolean() << '\\n';\n std::cout << j_number_float.is_boolean() << '\\n';\n std::cout << j_object.is_boolean() << '\\n';\n std::cout << j_array.is_boolean() << '\\n';\n std::cout << j_string.is_boolean() << '\\n';\n std::cout << j_binary.is_boolean() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_boolean/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_discarded/","title":"nlohmann::basic_json::is_discarded","text":"<pre><code>constexpr bool is_discarded() const noexcept;\n</code></pre> <p>This function returns <code>true</code> for a JSON value if either:</p> <ul> <li>the value was discarded during parsing with a callback function (see <code>parser_callback_t</code>), or</li> <li>the value is the result of parsing invalid JSON with parameter <code>allow_exceptions</code> set to <code>false</code>; see <code>parse</code> for more information.</li> </ul>"},{"location":"api/basic_json/is_discarded/#return-value","title":"Return value","text":"<p><code>true</code> if type is discarded, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_discarded/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_discarded/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_discarded/#notes","title":"Notes","text":"<p>Comparisons</p> <p>Discarded values are never compared equal with <code>operator==</code>. That is, checking whether a JSON value <code>j</code> is discarded will only work via:</p> <pre><code>j.is_discarded()\n</code></pre> <p>because</p> <pre><code>j == json::value_t::discarded\n</code></pre> <p>will always be <code>false</code>.</p> <p>Removal during parsing with callback functions</p> <p>When a value is discarded by a callback function (see <code>parser_callback_t</code>) during parsing, then it is removed when it is part of a structured value. For instance, if the second value of an array is discarded, instead of <code>[null, discarded, false]</code>, the array <code>[null, false]</code> is returned. Only if the top-level value is discarded, the return value of the <code>parse</code> call is discarded.</p> <p>This function will always be <code>false</code> for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases.</p>"},{"location":"api/basic_json/is_discarded/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_discarded()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_discarded()\n std::cout << std::boolalpha;\n std::cout << j_null.is_discarded() << '\\n';\n std::cout << j_boolean.is_discarded() << '\\n';\n std::cout << j_number_integer.is_discarded() << '\\n';\n std::cout << j_number_unsigned_integer.is_discarded() << '\\n';\n std::cout << j_number_float.is_discarded() << '\\n';\n std::cout << j_object.is_discarded() << '\\n';\n std::cout << j_array.is_discarded() << '\\n';\n std::cout << j_string.is_discarded() << '\\n';\n std::cout << j_binary.is_discarded() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_discarded/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_null/","title":"nlohmann::basic_json::is_null","text":"<pre><code>constexpr bool is_null() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is <code>null</code>.</p>"},{"location":"api/basic_json/is_null/#return-value","title":"Return value","text":"<p><code>true</code> if type is <code>null</code>, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_null/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_null/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_null/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_null()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_null()\n std::cout << std::boolalpha;\n std::cout << j_null.is_null() << '\\n';\n std::cout << j_boolean.is_null() << '\\n';\n std::cout << j_number_integer.is_null() << '\\n';\n std::cout << j_number_unsigned_integer.is_null() << '\\n';\n std::cout << j_number_float.is_null() << '\\n';\n std::cout << j_object.is_null() << '\\n';\n std::cout << j_array.is_null() << '\\n';\n std::cout << j_string.is_null() << '\\n';\n std::cout << j_binary.is_null() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_null/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_number/","title":"nlohmann::basic_json::is_number","text":"<pre><code>constexpr bool is_number() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.</p>"},{"location":"api/basic_json/is_number/#return-value","title":"Return value","text":"<p><code>true</code> if type is number (regardless whether integer, unsigned integer or floating-type), <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_number/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_number/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_number/#possible-implementation","title":"Possible implementation","text":"<pre><code>constexpr bool is_number() const noexcept\n{\n return is_number_integer() || is_number_float();\n}\n</code></pre>"},{"location":"api/basic_json/is_number/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_number()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number() << '\\n';\n std::cout << j_boolean.is_number() << '\\n';\n std::cout << j_number_integer.is_number() << '\\n';\n std::cout << j_number_unsigned_integer.is_number() << '\\n';\n std::cout << j_number_float.is_number() << '\\n';\n std::cout << j_object.is_number() << '\\n';\n std::cout << j_array.is_number() << '\\n';\n std::cout << j_string.is_number() << '\\n';\n std::cout << j_binary.is_number() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_number/#see-also","title":"See also","text":"<ul> <li>is_number_integer() check if value is an integer or unsigned integer number</li> <li>is_number_unsigned() check if value is an unsigned integer number</li> <li>is_number_float() check if value is a floating-point number</li> </ul>"},{"location":"api/basic_json/is_number/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to also return <code>true</code> for unsigned integers in 2.0.0.</li> </ul>"},{"location":"api/basic_json/is_number_float/","title":"nlohmann::basic_json::is_number_float","text":"<pre><code>constexpr bool is_number_float() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.</p>"},{"location":"api/basic_json/is_number_float/#return-value","title":"Return value","text":"<p><code>true</code> if type is a floating-point number, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_number_float/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_number_float/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_number_float/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_number_float()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_float()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_float() << '\\n';\n std::cout << j_boolean.is_number_float() << '\\n';\n std::cout << j_number_integer.is_number_float() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_float() << '\\n';\n std::cout << j_number_float.is_number_float() << '\\n';\n std::cout << j_object.is_number_float() << '\\n';\n std::cout << j_array.is_number_float() << '\\n';\n std::cout << j_string.is_number_float() << '\\n';\n std::cout << j_binary.is_number_float() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_number_float/#see-also","title":"See also","text":"<ul> <li>is_number() check if value is a number</li> <li>is_number_integer() check if value is an integer or unsigned integer number</li> <li>is_number_unsigned() check if value is an unsigned integer number</li> </ul>"},{"location":"api/basic_json/is_number_float/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_number_integer/","title":"nlohmann::basic_json::is_number_integer","text":"<pre><code>constexpr bool is_number_integer() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.</p>"},{"location":"api/basic_json/is_number_integer/#return-value","title":"Return value","text":"<p><code>true</code> if type is an integer or unsigned integer number, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_number_integer/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_number_integer/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_number_integer/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_number_integer()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_integer()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_integer() << '\\n';\n std::cout << j_boolean.is_number_integer() << '\\n';\n std::cout << j_number_integer.is_number_integer() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_integer() << '\\n';\n std::cout << j_number_float.is_number_integer() << '\\n';\n std::cout << j_object.is_number_integer() << '\\n';\n std::cout << j_array.is_number_integer() << '\\n';\n std::cout << j_string.is_number_integer() << '\\n';\n std::cout << j_binary.is_number_integer() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_number_integer/#see-also","title":"See also","text":"<ul> <li>is_number() check if value is a number</li> <li>is_number_unsigned() check if value is an unsigned integer number</li> <li>is_number_float() check if value is a floating-point number</li> </ul>"},{"location":"api/basic_json/is_number_integer/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to also return <code>true</code> for unsigned integers in 2.0.0.</li> </ul>"},{"location":"api/basic_json/is_number_unsigned/","title":"nlohmann::basic_json::is_number_unsigned","text":"<pre><code>constexpr bool is_number_unsigned() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.</p>"},{"location":"api/basic_json/is_number_unsigned/#return-value","title":"Return value","text":"<p><code>true</code> if type is an unsigned integer number, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_number_unsigned/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_number_unsigned/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_number_unsigned/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_number_unsigned()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_unsigned()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_unsigned() << '\\n';\n std::cout << j_boolean.is_number_unsigned() << '\\n';\n std::cout << j_number_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_float.is_number_unsigned() << '\\n';\n std::cout << j_object.is_number_unsigned() << '\\n';\n std::cout << j_array.is_number_unsigned() << '\\n';\n std::cout << j_string.is_number_unsigned() << '\\n';\n std::cout << j_binary.is_number_unsigned() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_number_unsigned/#see-also","title":"See also","text":"<ul> <li>is_number() check if value is a number</li> <li>is_number_integer() check if value is an integer or unsigned integer number</li> <li>is_number_float() check if value is a floating-point number</li> </ul>"},{"location":"api/basic_json/is_number_unsigned/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> </ul>"},{"location":"api/basic_json/is_object/","title":"nlohmann::basic_json::is_object","text":"<pre><code>constexpr bool is_object() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is an object.</p>"},{"location":"api/basic_json/is_object/#return-value","title":"Return value","text":"<p><code>true</code> if type is an object, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_object/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_object/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_object/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_object()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_object()\n std::cout << std::boolalpha;\n std::cout << j_null.is_object() << '\\n';\n std::cout << j_boolean.is_object() << '\\n';\n std::cout << j_number_integer.is_object() << '\\n';\n std::cout << j_number_unsigned_integer.is_object() << '\\n';\n std::cout << j_number_float.is_object() << '\\n';\n std::cout << j_object.is_object() << '\\n';\n std::cout << j_array.is_object() << '\\n';\n std::cout << j_string.is_object() << '\\n';\n std::cout << j_binary.is_object() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_object/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_primitive/","title":"nlohmann::basic_json::is_primitive","text":"<pre><code>constexpr bool is_primitive() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON type is primitive (string, number, boolean, <code>null</code>, binary).</p>"},{"location":"api/basic_json/is_primitive/#return-value","title":"Return value","text":"<p><code>true</code> if type is primitive (string, number, boolean, <code>null</code>, or binary), <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_primitive/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_primitive/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_primitive/#possible-implementation","title":"Possible implementation","text":"<pre><code>constexpr bool is_primitive() const noexcept\n{\n return is_null() || is_string() || is_boolean() || is_number() || is_binary();\n}\n</code></pre>"},{"location":"api/basic_json/is_primitive/#notes","title":"Notes","text":"<p>The term primitive stems from RFC 8259:</p> <p>JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).</p> <p>This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, <code>is_primitive()</code> returns <code>true</code> for binary values.</p>"},{"location":"api/basic_json/is_primitive/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_primitive()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_primitive()\n std::cout << std::boolalpha;\n std::cout << j_null.is_primitive() << '\\n';\n std::cout << j_boolean.is_primitive() << '\\n';\n std::cout << j_number_integer.is_primitive() << '\\n';\n std::cout << j_number_unsigned_integer.is_primitive() << '\\n';\n std::cout << j_number_float.is_primitive() << '\\n';\n std::cout << j_object.is_primitive() << '\\n';\n std::cout << j_array.is_primitive() << '\\n';\n std::cout << j_string.is_primitive() << '\\n';\n std::cout << j_binary.is_primitive() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\ntrue\ntrue\ntrue\ntrue\nfalse\nfalse\ntrue\ntrue\n</code></pre>"},{"location":"api/basic_json/is_primitive/#see-also","title":"See also","text":"<ul> <li>is_structured() returns whether JSON value is structured</li> <li>is_null() returns whether JSON value is <code>null</code></li> <li>is_string() returns whether JSON value is a string</li> <li>is_boolean() returns whether JSON value is a boolean</li> <li>is_number() returns whether JSON value is a number</li> <li>is_binary() returns whether JSON value is a binary array</li> </ul>"},{"location":"api/basic_json/is_primitive/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to return <code>true</code> for binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/is_string/","title":"nlohmann::basic_json::is_string","text":"<pre><code>constexpr bool is_string() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON value is a string.</p>"},{"location":"api/basic_json/is_string/#return-value","title":"Return value","text":"<p><code>true</code> if type is a string, <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_string/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_string/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_string/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_string()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_string()\n std::cout << std::boolalpha;\n std::cout << j_null.is_string() << '\\n';\n std::cout << j_boolean.is_string() << '\\n';\n std::cout << j_number_integer.is_string() << '\\n';\n std::cout << j_number_unsigned_integer.is_string() << '\\n';\n std::cout << j_number_float.is_string() << '\\n';\n std::cout << j_object.is_string() << '\\n';\n std::cout << j_array.is_string() << '\\n';\n std::cout << j_string.is_string() << '\\n';\n std::cout << j_binary.is_string() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\n</code></pre>"},{"location":"api/basic_json/is_string/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/is_structured/","title":"nlohmann::basic_json::is_structured","text":"<pre><code>constexpr bool is_structured() const noexcept;\n</code></pre> <p>This function returns <code>true</code> if and only if the JSON type is structured (array or object).</p>"},{"location":"api/basic_json/is_structured/#return-value","title":"Return value","text":"<p><code>true</code> if type is structured (array or object), <code>false</code> otherwise.</p>"},{"location":"api/basic_json/is_structured/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/is_structured/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/is_structured/#possible-implementation","title":"Possible implementation","text":"<pre><code>constexpr bool is_primitive() const noexcept\n{\n return is_array() || is_object();\n}\n</code></pre>"},{"location":"api/basic_json/is_structured/#notes","title":"Notes","text":"<p>The term structured stems from RFC 8259:</p> <p>JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).</p> <p>Note that though strings are containers in C++, they are treated as primitive values in JSON.</p>"},{"location":"api/basic_json/is_structured/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>is_structured()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_structured()\n std::cout << std::boolalpha;\n std::cout << j_null.is_structured() << '\\n';\n std::cout << j_boolean.is_structured() << '\\n';\n std::cout << j_number_integer.is_structured() << '\\n';\n std::cout << j_number_unsigned_integer.is_structured() << '\\n';\n std::cout << j_number_float.is_structured() << '\\n';\n std::cout << j_object.is_structured() << '\\n';\n std::cout << j_array.is_structured() << '\\n';\n std::cout << j_string.is_structured() << '\\n';\n std::cout << j_binary.is_structured() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>false\nfalse\nfalse\nfalse\nfalse\ntrue\ntrue\nfalse\nfalse\n</code></pre>"},{"location":"api/basic_json/is_structured/#see-also","title":"See also","text":"<ul> <li>is_primitive() returns whether JSON value is primitive</li> <li>is_array() returns whether value is an array</li> <li>is_object() returns whether value is an object</li> </ul>"},{"location":"api/basic_json/is_structured/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/items/","title":"nlohmann::basic_json::items","text":"<pre><code>iteration_proxy<iterator> items() noexcept;\niteration_proxy<const_iterator> items() const noexcept;\n</code></pre> <p>This function allows accessing <code>iterator::key()</code> and <code>iterator::value()</code> during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.</p> <p>For loop without <code>items()</code> function:</p> <pre><code>for (auto it = j_object.begin(); it != j_object.end(); ++it)\n{\n std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n}\n</code></pre> <p>Range-based for loop without <code>items()</code> function:</p> <pre><code>for (auto it : j_object)\n{\n // \"it\" is of type json::reference and has no key() member\n std::cout << \"value: \" << it << '\\n';\n}\n</code></pre> <p>Range-based for loop with <code>items()</code> function:</p> <pre><code>for (auto& el : j_object.items())\n{\n std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n</code></pre> <p>The <code>items()</code> function also allows using structured bindings (C++17):</p> <pre><code>for (auto& [key, val] : j_object.items())\n{\n std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n</code></pre>"},{"location":"api/basic_json/items/#return-value","title":"Return value","text":"<p>iteration proxy object wrapping the current value with an interface to use in range-based for loops</p>"},{"location":"api/basic_json/items/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/items/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/items/#notes","title":"Notes","text":"<p>When iterating over an array, <code>key()</code> will return the index of the element as string (see example). For primitive types (e.g., numbers), <code>key()</code> returns an empty string.</p> <p>Lifetime issues</p> <p>Using <code>items()</code> on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.</p>"},{"location":"api/basic_json/items/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>items()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // example for an object\n for (auto& x : j_object.items())\n {\n std::cout << \"key: \" << x.key() << \", value: \" << x.value() << '\\n';\n }\n\n // example for an array\n for (auto& x : j_array.items())\n {\n std::cout << \"key: \" << x.key() << \", value: \" << x.value() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>key: one, value: 1\nkey: two, value: 2\nkey: 0, value: 1\nkey: 1, value: 2\nkey: 2, value: 4\nkey: 3, value: 8\nkey: 4, value: 16\n</code></pre>"},{"location":"api/basic_json/items/#version-history","title":"Version history","text":"<ul> <li>Added <code>iterator_wrapper</code> in version 3.0.0.</li> <li>Added <code>items</code> and deprecated <code>iterator_wrapper</code> in version 3.1.0.</li> <li>Added structured binding support in version 3.5.0.</li> </ul> <p>Deprecation</p> <p>This function replaces the static function <code>iterator_wrapper</code> which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function <code>iterator_wrapper</code> will be removed in version 4.0.0. Please replace all occurrences of <code>iterator_wrapper(j)</code> with <code>j.items()</code>.</p> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/json_base_class_t/","title":"nlohmann::basic_json::json_base_class_t","text":"<pre><code>using json_base_class_t = detail::json_base_class<CustomBaseClass>;\n</code></pre> <p>The base class used to inject custom functionality into each instance of <code>basic_json</code>. Examples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.</p>"},{"location":"api/basic_json/json_base_class_t/#template-parameters","title":"Template parameters","text":"<code>CustomBaseClass</code> the base class to be added to <code>basic_json</code>"},{"location":"api/basic_json/json_base_class_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_base_class_t/#default-type","title":"Default type","text":"<p>The default value for <code>CustomBaseClass</code> is <code>void</code>. In this case an empty base class is used and no additional functionality is injected.</p>"},{"location":"api/basic_json/json_base_class_t/#limitations","title":"Limitations","text":"<p>The type <code>CustomBaseClass</code> has to be a default-constructible class. <code>basic_json</code> only supports copy/move construction/assignment if <code>CustomBaseClass</code> does so as well.</p>"},{"location":"api/basic_json/json_base_class_t/#examples","title":"Examples","text":"Example <p>The following code shows how to inject custom data and methods for each node.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nclass visitor_adaptor_with_metadata\n{\n public:\n template <class Fnc>\n void visit(const Fnc& fnc) const;\n\n int metadata = 42;\n private:\n template <class Ptr, class Fnc>\n void do_visit(const Ptr& ptr, const Fnc& fnc) const;\n};\n\nusing json = nlohmann::basic_json <\n std::map,\n std::vector,\n std::string,\n bool,\n std::int64_t,\n std::uint64_t,\n double,\n std::allocator,\n nlohmann::adl_serializer,\n std::vector<std::uint8_t>,\n visitor_adaptor_with_metadata\n >;\n\ntemplate <class Fnc>\nvoid visitor_adaptor_with_metadata::visit(const Fnc& fnc) const\n{\n do_visit(json::json_pointer{}, fnc);\n}\n\ntemplate <class Ptr, class Fnc>\nvoid visitor_adaptor_with_metadata::do_visit(const Ptr& ptr, const Fnc& fnc) const\n{\n using value_t = nlohmann::detail::value_t;\n const json& j = *static_cast<const json*>(this);\n switch (j.type())\n {\n case value_t::object:\n fnc(ptr, j);\n for (const auto& entry : j.items())\n {\n entry.value().do_visit(ptr / entry.key(), fnc);\n }\n break;\n case value_t::array:\n fnc(ptr, j);\n for (std::size_t i = 0; i < j.size(); ++i)\n {\n j.at(i).do_visit(ptr / std::to_string(i), fnc);\n }\n break;\n case value_t::null:\n case value_t::string:\n case value_t::boolean:\n case value_t::number_integer:\n case value_t::number_unsigned:\n case value_t::number_float:\n case value_t::binary:\n fnc(ptr, j);\n break;\n case value_t::discarded:\n default:\n break;\n }\n}\n\nint main()\n{\n // create a json object\n json j;\n j[\"null\"];\n j[\"object\"][\"uint\"] = 1U;\n j[\"object\"].metadata = 21;\n\n // visit and output\n j.visit(\n [&](const json::json_pointer & p,\n const json & j)\n {\n std::cout << (p.empty() ? std::string{\"/\"} : p.to_string())\n << \" - metadata = \" << j.metadata << \" -> \" << j.dump() << '\\n';\n });\n}\n</code></pre> <p>Output:</p> <pre><code>/ - metadata = 42 -> {\"null\":null,\"object\":{\"uint\":1}}\n/null - metadata = 42 -> null\n/object - metadata = 21 -> {\"uint\":1}\n/object/uint - metadata = 42 -> 1\n</code></pre>"},{"location":"api/basic_json/json_base_class_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.12.0.</li> </ul>"},{"location":"api/basic_json/json_serializer/","title":"nlohmann::basic_json::json_serializer","text":"<pre><code>template<typename T, typename SFINAE>\nusing json_serializer = JSONSerializer<T, SFINAE>;\n</code></pre>"},{"location":"api/basic_json/json_serializer/#template-parameters","title":"Template parameters","text":"<code>T</code> type to convert; will be used in the <code>to_json</code>/<code>from_json</code> functions <code>SFINAE</code> type to add compile type checks via SFINAE; usually <code>void</code>"},{"location":"api/basic_json/json_serializer/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_serializer/#default-type","title":"Default type","text":"<p>The default values for <code>json_serializer</code> is <code>adl_serializer</code>.</p>"},{"location":"api/basic_json/json_serializer/#examples","title":"Examples","text":"Example <p>The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the <code>adl_serializer</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>Ned Flanders (60) lives in 744 Evergreen Terrace\n</code></pre>"},{"location":"api/basic_json/json_serializer/#version-history","title":"Version history","text":"<ul> <li>Since version 2.0.0.</li> </ul>"},{"location":"api/basic_json/max_size/","title":"nlohmann::basic_json::max_size","text":"<pre><code>size_type max_size() const noexcept;\n</code></pre> <p>Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. <code>std::distance(begin(), end())</code> for the JSON value.</p>"},{"location":"api/basic_json/max_size/#return-value","title":"Return value","text":"<p>The return value depends on the different types and is defined as follows:</p> Value type return value null <code>0</code> (same as <code>size()</code>) boolean <code>1</code> (same as <code>size()</code>) string <code>1</code> (same as <code>size()</code>) number <code>1</code> (same as <code>size()</code>) binary <code>1</code> (same as <code>size()</code>) object result of function <code>object_t::max_size()</code> array result of function <code>array_t::max_size()</code>"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/max_size/#complexity","title":"Complexity","text":"<p>Constant, as long as <code>array_t</code> and <code>object_t</code> satisfy the Container concept; that is, their <code>max_size()</code> functions have constant complexity.</p>"},{"location":"api/basic_json/max_size/#notes","title":"Notes","text":"<p>This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of string elements the JSON value can store which is <code>1</code>.</p>"},{"location":"api/basic_json/max_size/#examples","title":"Examples","text":"Example <p>The following code calls <code>max_size()</code> on the different value types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call max_size()\n std::cout << j_null.max_size() << '\\n';\n std::cout << j_boolean.max_size() << '\\n';\n std::cout << j_number_integer.max_size() << '\\n';\n std::cout << j_number_float.max_size() << '\\n';\n std::cout << j_object.max_size() << '\\n';\n std::cout << j_array.max_size() << '\\n';\n std::cout << j_string.max_size() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>0\n1\n1\n1\n115292150460684697\n576460752303423487\n1\n</code></pre> <p>Note the output is platform-dependent.</p>"},{"location":"api/basic_json/max_size/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to return <code>1</code> for binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/merge_patch/","title":"nlohmann::basic_json::merge_patch","text":"<pre><code>void merge_patch(const basic_json& apply_patch);\n</code></pre> <p>The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.</p> <p>The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):</p> <pre><code>define MergePatch(Target, Patch):\n if Patch is an Object:\n if Target is not an Object:\n Target = {} // Ignore the contents and set it to an empty Object\n for each Name/Value pair in Patch:\n if Value is null:\n if Name exists in Target:\n remove the Name/Value pair from Target\n else:\n Target[Name] = MergePatch(Target[Name], Value)\n return Target\n else:\n return Patch\n</code></pre> <p>Thereby, <code>Target</code> is the current object; that is, the patch is applied to the current value.</p>"},{"location":"api/basic_json/merge_patch/#parameters","title":"Parameters","text":"<code>apply_patch</code> (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"<p>Linear in the lengths of <code>apply_patch</code>.</p>"},{"location":"api/basic_json/merge_patch/#examples","title":"Examples","text":"Example <p>The following code shows how a JSON Merge Patch is applied to a JSON document.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n</code></pre>"},{"location":"api/basic_json/merge_patch/#see-also","title":"See also","text":"<ul> <li>RFC 7396 (JSON Merge Patch)</li> <li>patch apply a JSON patch</li> </ul>"},{"location":"api/basic_json/merge_patch/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.0.0.</li> </ul>"},{"location":"api/basic_json/meta/","title":"nlohmann::basic_json::meta","text":"<pre><code>static basic_json meta();\n</code></pre> <p>This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.</p>"},{"location":"api/basic_json/meta/#return-value","title":"Return value","text":"<p>JSON object holding version information</p> key description <code>compiler</code> Information on the used compiler. It is an object with the following keys: <code>c++</code> (the used C++ standard), <code>family</code> (the compiler family; possible values are <code>clang</code>, <code>icc</code>, <code>gcc</code>, <code>ilecpp</code>, <code>msvc</code>, <code>pgcpp</code>, <code>sunpro</code>, and <code>unknown</code>), and <code>version</code> (the compiler version). <code>copyright</code> The copyright line for the library as string. <code>name</code> The name of the library as string. <code>platform</code> The used platform as string. Possible values are <code>win32</code>, <code>linux</code>, <code>apple</code>, <code>unix</code>, and <code>unknown</code>. <code>url</code> The URL of the project as string. <code>version</code> The version of the library. It is an object with the following keys: <code>major</code>, <code>minor</code>, and <code>patch</code> as defined by Semantic Versioning, and <code>string</code> (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</p>"},{"location":"api/basic_json/meta/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/meta/#examples","title":"Examples","text":"Example <p>The following code shows an example output of the <code>meta()</code> function.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // call meta()\n std::cout << std::setw(4) << json::meta() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compiler\": {\n \"c++\": \"201103\",\n \"family\": \"gcc\",\n \"version\": \"12.3.0\"\n },\n \"copyright\": \"(C) 2013-2022 Niels Lohmann\",\n \"name\": \"JSON for Modern C++\",\n \"platform\": \"apple\",\n \"url\": \"https://github.com/nlohmann/json\",\n \"version\": {\n \"major\": 3,\n \"minor\": 11,\n \"patch\": 3,\n \"string\": \"3.11.3\"\n }\n}\n</code></pre> <p>Note the output is platform-dependent.</p>"},{"location":"api/basic_json/meta/#see-also","title":"See also","text":"<ul> <li>NLOHMANN_JSON_VERSION_MAJOR/NLOHMANN_JSON_VERSION_MINOR/NLOHMANN_JSON_VERSION_PATCH - library version information</li> </ul>"},{"location":"api/basic_json/meta/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.1.0.</li> </ul>"},{"location":"api/basic_json/number_float_t/","title":"nlohmann::basic_json::number_float_t","text":"<pre><code>using number_float_t = NumberFloatType;\n</code></pre> <p>The type used to store JSON numbers (floating-point).</p> <p>RFC 8259 describes numbers as follows:</p> <p>The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.</p> <p>This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, <code>number_integer_t</code>, <code>number_unsigned_t</code> and <code>number_float_t</code> are used.</p> <p>To store floating-point numbers in C++, a type is defined by the template parameter <code>NumberFloatType</code> which chooses the type to use.</p>"},{"location":"api/basic_json/number_float_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_float_t/#default-type","title":"Default type","text":"<p>With the default values for <code>NumberFloatType</code> (<code>double</code>), the default value for <code>number_float_t</code> is <code>double</code>.</p>"},{"location":"api/basic_json/number_float_t/#default-behavior","title":"Default behavior","text":"<ul> <li>The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal <code>01.2</code> will be serialized to <code>1.2</code>. During deserialization, leading zeros yield an error.</li> <li>Not-a-number (NaN) values will be serialized to <code>null</code>.</li> </ul>"},{"location":"api/basic_json/number_float_t/#limits","title":"Limits","text":"<p>RFC 8259 states:</p> <p>This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.</p> <p>This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than <code>-1.79769313486232e+308</code> and values greater than <code>1.79769313486232e+308</code> will be stored as NaN internally and be serialized to <code>null</code>.</p>"},{"location":"api/basic_json/number_float_t/#storage","title":"Storage","text":"<p>Floating-point number values are stored directly inside a <code>basic_json</code> type.</p>"},{"location":"api/basic_json/number_float_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>number_float_t</code> is by default, a typedef to <code>double</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<double, json::number_float_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/number_float_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/number_integer_t/","title":"nlohmann::basic_json::number_integer_t","text":"<pre><code>using number_integer_t = NumberIntegerType;\n</code></pre> <p>The type used to store JSON numbers (integers).</p> <p>RFC 8259 describes numbers as follows:</p> <p>The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.</p> <p>This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, <code>number_integer_t</code>, <code>number_unsigned_t</code> and <code>number_float_t</code> are used.</p> <p>To store integer numbers in C++, a type is defined by the template parameter <code>NumberIntegerType</code> which chooses the type to use.</p>"},{"location":"api/basic_json/number_integer_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_integer_t/#default-type","title":"Default type","text":"<p>With the default values for <code>NumberIntegerType</code> (<code>std::int64_t</code>), the default value for <code>number_integer_t</code> is <code>std::int64_t</code>.</p>"},{"location":"api/basic_json/number_integer_t/#default-behavior","title":"Default behavior","text":"<ul> <li>The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal <code>010</code> will be serialized to <code>8</code>. During deserialization, leading zeros yield an error.</li> <li>Not-a-number (NaN) values will be serialized to <code>null</code>.</li> </ul>"},{"location":"api/basic_json/number_integer_t/#limits","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the range and precision of numbers.</p> <p>When the default type is used, the maximal integer number that can be stored is <code>9223372036854775807</code> (INT64_MAX) and the minimal integer number that can be stored is <code>-9223372036854775808</code> (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as <code>number_unsigned_t</code> or <code>number_float_t</code>.</p> <p>RFC 8259 further states:</p> <p>Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.</p> <p>As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.</p>"},{"location":"api/basic_json/number_integer_t/#storage","title":"Storage","text":"<p>Integer number values are stored directly inside a <code>basic_json</code> type.</p>"},{"location":"api/basic_json/number_integer_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>number_integer_t</code> is by default, a typedef to <code>std::int64_t</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::int64_t, json::number_integer_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/number_integer_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/number_unsigned_t/","title":"nlohmann::basic_json::number_unsigned_t","text":"<pre><code>using number_unsigned_t = NumberUnsignedType;\n</code></pre> <p>The type used to store JSON numbers (unsigned).</p> <p>RFC 8259 describes numbers as follows:</p> <p>The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.</p> <p>This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, <code>number_integer_t</code>, <code>number_unsigned_t</code> and <code>number_float_t</code> are used.</p> <p>To store unsigned integer numbers in C++, a type is defined by the template parameter <code>NumberUnsignedType</code> which chooses the type to use.</p>"},{"location":"api/basic_json/number_unsigned_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_unsigned_t/#default-type","title":"Default type","text":"<p>With the default values for <code>NumberUnsignedType</code> (<code>std::uint64_t</code>), the default value for <code>number_unsigned_t</code> is <code>std::uint64_t</code>.</p>"},{"location":"api/basic_json/number_unsigned_t/#default-behavior","title":"Default behavior","text":"<ul> <li>The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal <code>010</code> will be serialized to <code>8</code>. During deserialization, leading zeros yield an error.</li> <li>Not-a-number (NaN) values will be serialized to <code>null</code>.</li> </ul>"},{"location":"api/basic_json/number_unsigned_t/#limits","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the range and precision of numbers.</p> <p>When the default type is used, the maximal integer number that can be stored is <code>18446744073709551615</code> (UINT64_MAX) and the minimal integer number that can be stored is <code>0</code>. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as <code>number_integer_t</code> or <code>number_float_t</code>.</p> <p>RFC 8259 further states:</p> <p>Note that when such software is used, numbers that are integers and are in the range \\f[-2^{53}+1, 2^{53}-1]\\f are interoperable in the sense that implementations will agree exactly on their numeric values.</p> <p>As this range is a subrange (when considered in conjunction with the <code>number_integer_t</code> type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.</p>"},{"location":"api/basic_json/number_unsigned_t/#storage","title":"Storage","text":"<p>Integer number values are stored directly inside a <code>basic_json</code> type.</p>"},{"location":"api/basic_json/number_unsigned_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>number_unsigned_t</code> is by default, a typedef to <code>std::uint64_t</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::uint64_t, json::number_unsigned_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/number_unsigned_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> </ul>"},{"location":"api/basic_json/object/","title":"nlohmann::basic_json::object","text":"<pre><code>static basic_json object(initializer_list_t init = {});\n</code></pre> <p>Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object <code>{}</code> is created.</p>"},{"location":"api/basic_json/object/#parameters","title":"Parameters","text":"<code>init</code> (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"<p>JSON object value</p>"},{"location":"api/basic_json/object/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/object/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.301</code> if <code>init</code> is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to <code>basic_json(initializer_list_t, bool, value_t)</code>, an array would have been created from the passed initializer list <code>init</code>. See example below.</p>"},{"location":"api/basic_json/object/#complexity","title":"Complexity","text":"<p>Linear in the size of <code>init</code>.</p>"},{"location":"api/basic_json/object/#notes","title":"Notes","text":"<p>This function is only added for symmetry reasons. In contrast to the related function <code>array(initializer_list_t)</code>, there are no cases which can only be expressed by this function. That is, any initializer list <code>init</code> can also be passed to the initializer list constructor <code>basic_json(initializer_list_t, bool, value_t)</code>.</p>"},{"location":"api/basic_json/object/#examples","title":"Examples","text":"Example <p>The following code shows an example for the <code>object</code> function.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON objects\n json j_no_init_list = json::object();\n json j_empty_init_list = json::object({});\n json j_list_of_pairs = json::object({ {\"one\", 1}, {\"two\", 2} });\n\n // serialize the JSON objects\n std::cout << j_no_init_list << '\\n';\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_list_of_pairs << '\\n';\n\n // example for an exception\n try\n {\n // can only create an object from a list of pairs\n json j_invalid_object = json::object({{ \"one\", 1, 2 }});\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>{}\n{}\n{\"one\":1,\"two\":2}\n[json.exception.type_error.301] cannot create object from initializer list\n</code></pre>"},{"location":"api/basic_json/object/#see-also","title":"See also","text":"<ul> <li><code>basic_json(initializer_list_t)</code> - create a JSON value from an initializer list</li> <li><code>array</code> - create a JSON array value from an initializer list</li> </ul>"},{"location":"api/basic_json/object/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/object_comparator_t/","title":"nlohmann::basic_json::object_comparator_t","text":"<pre><code>using object_comparator_t = typename object_t::key_compare;\n// or\nusing object_comparator_t = default_object_comparator_t;\n</code></pre> <p>The comparator used by <code>object_t</code>. Defined as <code>typename object_t::key_compare</code> if available, and <code>default_object_comparator_t</code> otherwise.</p>"},{"location":"api/basic_json/object_comparator_t/#examples","title":"Examples","text":"Example <p>The example below demonstrates the used object comparator.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha\n << \"json::object_comparator_t(\\\"one\\\", \\\"two\\\") = \" << json::object_comparator_t{}(\"one\", \"two\") << \"\\n\"\n << \"json::object_comparator_t(\\\"three\\\", \\\"four\\\") = \" << json::object_comparator_t{}(\"three\", \"four\") << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>json::object_comparator_t(\"one\", \"two\") = true\njson::object_comparator_t(\"three\", \"four\") = false\n</code></pre>"},{"location":"api/basic_json/object_comparator_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.0.0.</li> <li>Changed to be conditionally defined as <code>typename object_t::key_compare</code> or <code>default_object_comparator_t</code> in version 3.11.0.</li> </ul>"},{"location":"api/basic_json/object_t/","title":"nlohmann::basic_json::object_t","text":"<pre><code>using object_t = ObjectType<StringType,\n basic_json,\n default_object_comparator_t,\n AllocatorType<std::pair<const StringType, basic_json>>>;\n</code></pre> <p>The type used to store JSON objects.</p> <p>RFC 8259 describes JSON objects as follows:</p> <p>An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.</p> <p>To store objects in C++, a type is defined by the template parameters described below.</p>"},{"location":"api/basic_json/object_t/#template-parameters","title":"Template parameters","text":"<code>ObjectType</code> the container to store objects (e.g., <code>std::map</code> or <code>std::unordered_map</code>) <code>StringType</code> the type of the keys or names (e.g., <code>std::string</code>). The comparison function <code>std::less<StringType></code> is used to order elements inside the container. <code>AllocatorType</code> the allocator to use for objects (e.g., <code>std::allocator</code>)"},{"location":"api/basic_json/object_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/object_t/#default-type","title":"Default type","text":"<p>With the default values for <code>ObjectType</code> (<code>std::map</code>), <code>StringType</code> (<code>std::string</code>), and <code>AllocatorType</code> (<code>std::allocator</code>), the default value for <code>object_t</code> is:</p> <pre><code>// until C++14\nstd::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<std::string>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n\n// since C++14\nstd::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n</code></pre> <p>See <code>default_object_comparator_t</code> for more information.</p>"},{"location":"api/basic_json/object_t/#behavior","title":"Behavior","text":"<p>The choice of <code>object_t</code> influences the behavior of the JSON class. With the default type, objects have the following behavior:</p> <ul> <li>When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.</li> <li>When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, <code>{\"key\": 2, \"key\": 1}</code> could be equal to either <code>{\"key\": 1}</code> or <code>{\"key\": 2}</code>.</li> <li>Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see <code>dump</code>) in this order. For instance, <code>{\"b\": 1, \"a\": 2}</code> and <code>{\"a\": 2, \"b\": 1}</code> will be stored and serialized as <code>{\"a\": 2, \"b\": 1}</code>.</li> <li>When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, <code>{\"b\": 1, \"a\": 2}</code> and <code>{\"a\": 2, \"b\": 1}</code> will be treated as equal.</li> </ul>"},{"location":"api/basic_json/object_t/#limits","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the maximum depth of nesting.</p> <p>In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the <code>max_size</code> function of a JSON object.</p>"},{"location":"api/basic_json/object_t/#storage","title":"Storage","text":"<p>Objects are stored as pointers in a <code>basic_json</code> type. That is, for any access to object values, a pointer of type <code>object_t*</code> must be dereferenced.</p>"},{"location":"api/basic_json/object_t/#object-key-order","title":"Object key order","text":"<p>The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as <code>std::map</code> with <code>std::less</code> is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.</p>"},{"location":"api/basic_json/object_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>object_t</code> is by default, a typedef to <code>std::map<json::string_t, json></code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::map<json::string_t, json>, json::object_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/object_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/operator%2B%3D/","title":"nlohmann::basic_json::operator+=","text":"<pre><code>// (1)\nreference operator+=(basic_json&& val);\nreference operator+=(const basic_json& val);\n\n// (2)\nreference operator+=(const typename object_t::value_type& val);\n\n// (3)\nreference operator+=(initializer_list_t init);\n</code></pre> <ol> <li> <p>Appends the given element <code>val</code> to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending <code>val</code>.</p> </li> <li> <p>Inserts the given element <code>val</code> to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting <code>val</code>.</p> </li> <li> <p>This function allows using <code>operator+=</code> with an initializer list. In case</p> <ol> <li>the current value is an object,</li> <li>the initializer list <code>init</code> contains only two elements, and</li> <li>the first element of <code>init</code> is a string,</li> </ol> <p><code>init</code> is converted into an object element and added using <code>operator+=(const typename object_t::value_type&)</code>. Otherwise, <code>init</code> is converted to a JSON value and added using <code>operator+=(basic_json&&)</code>.</p> </li> </ol>"},{"location":"api/basic_json/operator%2B%3D/#parameters","title":"Parameters","text":"<code>val</code> (in) the value to add to the JSON array/object <code>init</code> (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"<p><code>*this</code></p>"},{"location":"api/basic_json/operator%2B%3D/#exceptions","title":"Exceptions","text":"<p>All functions can throw the following exception: - Throws <code>type_error.308</code> when called on a type other than JSON array or null; example: <code>\"cannot use operator+=() with number\"</code></p>"},{"location":"api/basic_json/operator%2B%3D/#complexity","title":"Complexity","text":"<ol> <li>Amortized constant.</li> <li>Logarithmic in the size of the container, O(log(<code>size()</code>)).</li> <li>Linear in the size of the initializer list <code>init</code>.</li> </ol>"},{"location":"api/basic_json/operator%2B%3D/#notes","title":"Notes","text":"<p>(3) This function is required to resolve an ambiguous overload error, because pairs like <code>{\"key\", \"value\"}</code> can be both interpreted as <code>object_t::value_type</code> or <code>std::initializer_list<basic_json></code>, see #235 for more information.</p>"},{"location":"api/basic_json/operator%2B%3D/#examples","title":"Examples","text":"Example: (1) add element to array <p>The example shows how <code>push_back()</code> and <code>+=</code> can be used to add elements to a JSON array. Note how the <code>null</code> value was silently converted to a JSON array.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n</code></pre> Example: (2) add element to object <p>The example shows how <code>push_back()</code> and <code>+=</code> can be used to add elements to a JSON object. Note how the <code>null</code> value was silently converted to a JSON object.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n object.push_back(json::object_t::value_type(\"three\", 3));\n object += json::object_t::value_type(\"four\", 4);\n null += json::object_t::value_type(\"A\", \"a\");\n null += json::object_t::value_type(\"B\", \"b\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n</code></pre> Example: (3) add to object from initializer list <p>The example shows how initializer lists are treated as objects when possible.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values:\n object.push_back({\"three\", 3}); // object is extended\n object += {\"four\", 4}; // object is extended\n null.push_back({\"five\", 5}); // null is converted to array\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // would throw:\n //object.push_back({1, 2, 3});\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n</code></pre>"},{"location":"api/basic_json/operator%2B%3D/#version-history","title":"Version history","text":"<ol> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 2.0.0.</li> </ol>"},{"location":"api/basic_json/operator%3D/","title":"nlohmann::basic_json::operator=","text":"<pre><code>basic_json& operator=(basic_json other) noexcept (\n std::is_nothrow_move_constructible<value_t>::value &&\n std::is_nothrow_move_assignable<value_t>::value &&\n std::is_nothrow_move_constructible<json_value>::value &&\n std::is_nothrow_move_assignable<json_value>::value\n);\n</code></pre> <p>Copy assignment operator. Copies a JSON value via the \"copy and swap\" strategy: It is expressed in terms of the copy constructor, destructor, and the <code>swap()</code> member function.</p>"},{"location":"api/basic_json/operator%3D/#parameters","title":"Parameters","text":"<code>other</code> (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator%3D/#examples","title":"Examples","text":"Example <p>The code below shows and example for the copy assignment. It creates a copy of value <code>a</code> which is then swapped with <code>b</code>. Finally, the copy of <code>a</code> (which is the null value after the swap) is destroyed.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json a = 23;\n json b = 42;\n\n // copy-assign a to b\n b = a;\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>23\n23\n</code></pre>"},{"location":"api/basic_json/operator%3D/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/operator%5B%5D/","title":"nlohmann::basic_json::operator[]","text":"<pre><code>// (1)\nreference operator[](size_type idx);\nconst_reference operator[](size_type idx) const;\n\n// (2)\nreference operator[](typename object_t::key_type key);\nconst_reference operator[](const typename object_t::key_type& key) const;\n\n// (3)\ntemplate<typename KeyType>\nreference operator[](KeyType&& key);\ntemplate<typename KeyType>\nconst_reference operator[](KeyType&& key) const;\n\n// (4)\nreference operator[](const json_pointer& ptr);\nconst_reference operator[](const json_pointer& ptr) const;\n</code></pre> <ol> <li>Returns a reference to the array element at specified location <code>idx</code>.</li> <li>Returns a reference to the object element with specified key <code>key</code>. The non-const qualified overload takes the key by value.</li> <li>See 2. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</li> <li>Returns a reference to the element with specified JSON pointer <code>ptr</code>.</li> </ol>"},{"location":"api/basic_json/operator%5B%5D/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#parameters","title":"Parameters","text":"<code>idx</code> (in) index of the element to access <code>key</code> (in) object key of the element to access <code>ptr</code> (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"<ol> <li>(const) reference to the element at index <code>idx</code></li> <li>(const) reference to the element at key <code>key</code></li> <li>(const) reference to the element at key <code>key</code></li> <li>(const) reference to the element pointed to by <code>ptr</code></li> </ol>"},{"location":"api/basic_json/operator%5B%5D/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/operator%5B%5D/#exceptions","title":"Exceptions","text":"<ol> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.305</code> if the JSON value is not an array or null; in that case, using the <code>[]</code> operator with an index makes no sense.</li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.305</code> if the JSON value is not an object or null; in that case, using the <code>[]</code> operator with a key makes no sense.</li> </ul> </li> <li>See 2.</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>parse_error.106</code> if an array index in the passed JSON pointer <code>ptr</code> begins with '0'.</li> <li>Throws <code>parse_error.109</code> if an array index in the passed JSON pointer <code>ptr</code> is not a number.</li> <li>Throws <code>out_of_range.402</code> if the array index '-' is used in the passed JSON pointer <code>ptr</code> for the const version.</li> <li>Throws <code>out_of_range.404</code> if the JSON pointer <code>ptr</code> can not be resolved.</li> </ul> </li> </ol>"},{"location":"api/basic_json/operator%5B%5D/#complexity","title":"Complexity","text":"<ol> <li>Constant if <code>idx</code> is in the range of the array. Otherwise, linear in <code>idx - size()</code>.</li> <li>Logarithmic in the size of the container.</li> <li>Logarithmic in the size of the container.</li> <li>Logarithmic in the size of the container.</li> </ol>"},{"location":"api/basic_json/operator%5B%5D/#notes","title":"Notes","text":"<p>Undefined behavior and runtime assertions</p> <ol> <li>If the element with key <code>idx</code> does not exist, the behavior is undefined.</li> <li>If the element with key <code>key</code> does not exist, the behavior is undefined and is guarded by a runtime assertion!</li> </ol> <ol> <li> <p>The non-const version may add values: If <code>idx</code> is beyond the range of the array (i.e., <code>idx >= size()</code>), then the array is silently filled up with <code>null</code> values to make <code>idx</code> a valid reference to the last stored element. In case the value was <code>null</code> before, it is converted to an array.</p> </li> <li> <p>If <code>key</code> is not found in the object, then it is silently added to the object and filled with a <code>null</code> value to make <code>key</code> a valid reference. In case the value was <code>null</code> before, it is converted to an object.</p> </li> <li> <p>See 2.</p> </li> <li> <p><code>null</code> values are created in arrays and objects if necessary.</p> <p>In particular:</p> <ul> <li>If the JSON pointer points to an object key that does not exist, it is created and filled with a <code>null</code> value before a reference to it is returned.</li> <li>If the JSON pointer points to an array index that does not exist, it is created and filled with a <code>null</code> value before a reference to it is returned. All indices between the current maximum and the given index are also filled with <code>null</code>.</li> <li>The special value <code>-</code> is treated as a synonym for the index past the end.</li> </ul> </li> </ol>"},{"location":"api/basic_json/operator%5B%5D/#examples","title":"Examples","text":"Example: (1) access specified array element <p>The example below shows how array elements can be read and written using <code>[]</code> operator. Note the addition of <code>null</code> values.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json array = {1, 2, 3, 4, 5};\n\n // output element at index 3 (fourth element)\n std::cout << array[3] << '\\n';\n\n // change last element to 6\n array[array.size() - 1] = 6;\n\n // output changed array\n std::cout << array << '\\n';\n\n // write beyond array limit\n array[10] = 11;\n\n // output changed array\n std::cout << array << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>4\n[1,2,3,4,6]\n[1,2,3,4,6,null,null,null,null,null,11]\n</code></pre> Example: (1) access specified array element (const) <p>The example below shows how array elements can be read using the <code>[]</code> operator.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>\"third\"\n</code></pre> Example: (2) access specified object element <p>The example below shows how object elements can be read and written using the <code>[]</code> operator.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"] << \"\\n\\n\";\n\n // change element with key \"three\"\n object[\"three\"] = 3;\n\n // output changed array\n std::cout << std::setw(4) << object << \"\\n\\n\";\n\n // mention nonexisting key\n object[\"four\"];\n\n // write to nonexisting key\n object[\"five\"][\"really\"][\"nested\"] = true;\n\n // output changed object\n std::cout << std::setw(4) << object << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>2\n\n{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n\n{\n \"five\": {\n \"really\": {\n \"nested\": true\n }\n },\n \"four\": null,\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n</code></pre> Example: (2) access specified object element (const) <p>The example below shows how object elements can be read using the <code>[]</code> operator.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n const json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"] << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>2\n</code></pre> Example: (3) access specified object element using string_view <p>The example below shows how object elements can be read using the <code>[]</code> operator.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"sv] << \"\\n\\n\";\n\n // change element with key \"three\"\n object[\"three\"sv] = 3;\n\n // output changed array\n std::cout << std::setw(4) << object << \"\\n\\n\";\n\n // mention nonexisting key\n object[\"four\"sv];\n\n // write to nonexisting key\n object[\"five\"sv][\"really\"sv][\"nested\"sv] = true;\n\n // output changed object\n std::cout << std::setw(4) << object << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>2\n\n{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n\n{\n \"five\": {\n \"really\": {\n \"nested\": true\n }\n },\n \"four\": null,\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n</code></pre> Example: (3) access specified object element using string_view (const) <p>The example below shows how object elements can be read using the <code>[]</code> operator.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n const json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"sv] << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>2\n</code></pre> Example: (4) access specified element via JSON Pointer <p>The example below shows how values can be read and written using JSON Pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j[\"/number\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j[\"/string\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j[\"/array\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j[\"/array/1\"_json_pointer] << '\\n';\n\n // writing access\n\n // change the string\n j[\"/string\"_json_pointer] = \"bar\";\n // output the changed string\n std::cout << j[\"string\"] << '\\n';\n\n // \"change\" a nonexisting object entry\n j[\"/boolean\"_json_pointer] = true;\n // output the changed object\n std::cout << j << '\\n';\n\n // change an array element\n j[\"/array/1\"_json_pointer] = 21;\n // \"change\" an array element with nonexisting index\n j[\"/array/4\"_json_pointer] = 44;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n\n // \"change\" the array element past the end\n j[\"/array/-\"_json_pointer] = 55;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>1\n\"foo\"\n[1,2]\n2\n\"bar\"\n{\"array\":[1,2],\"boolean\":true,\"number\":1,\"string\":\"bar\"}\n[1,21,null,null,44]\n[1,21,null,null,44,55]\n</code></pre> Example: (4) access specified element via JSON Pointer (const) <p>The example below shows how values can be read using JSON Pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n const json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j[\"/number\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j[\"/string\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j[\"/array\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j[\"/array/1\"_json_pointer] << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>1\n\"foo\"\n[1,2]\n2\n</code></pre>"},{"location":"api/basic_json/operator%5B%5D/#see-also","title":"See also","text":"<ul> <li>documentation on unchecked access</li> <li>documentation on runtime assertions</li> <li>see <code>at</code> for access by reference with range checking</li> <li>see <code>value</code> for access with default value</li> </ul>"},{"location":"api/basic_json/operator%5B%5D/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0.</li> <li>Added in version 1.0.0. Added overloads for <code>T* key</code> in version 1.1.0. Removed overloads for <code>T* key</code> (replaced by 3) in version 3.11.0.</li> <li>Added in version 3.11.0.</li> <li>Added in version 2.0.0.</li> </ol>"},{"location":"api/basic_json/operator_ValueType/","title":"nlohmann::basic_json::operator ValueType","text":"<pre><code>template<typename ValueType>\nJSON_EXPLICIT operator ValueType() const;\n</code></pre> <p>Implicit type conversion between the JSON value and a compatible value. The call is realized by calling <code>get()</code>. See Notes for the meaning of <code>JSON_EXPLICIT</code>.</p>"},{"location":"api/basic_json/operator_ValueType/#template-parameters","title":"Template parameters","text":"<code>ValueType</code> the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"<p>copy of the JSON value, converted to <code>ValueType</code></p>"},{"location":"api/basic_json/operator_ValueType/#exceptions","title":"Exceptions","text":"<p>Depends on what <code>json_serializer<ValueType></code> <code>from_json()</code> method throws</p>"},{"location":"api/basic_json/operator_ValueType/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value.</p>"},{"location":"api/basic_json/operator_ValueType/#notes","title":"Notes","text":"<p>Definition of <code>JSON_EXPLICIT</code></p> <p>By default <code>JSON_EXPLICIT</code> is defined to the empty string, so the signature is:</p> <pre><code>template<typename ValueType>\noperator ValueType() const;\n</code></pre> <p>If <code>JSON_USE_IMPLICIT_CONVERSIONS</code> is set to <code>0</code>, <code>JSON_EXPLICIT</code> is defined to <code>explicit</code>:</p> <pre><code>template<typename ValueType>\nexplicit operator ValueType() const;\n</code></pre> <p>That is, implicit conversions can be switched off by defining <code>JSON_USE_IMPLICIT_CONVERSIONS</code> to <code>0</code>.</p> <p>Future behavior change</p> <p>Implicit conversions will be switched off by default in the next major release of the library. That is, <code>JSON_EXPLICIT</code> will be set to <code>explicit</code> by default.</p> <p>You can prepare existing code by already defining <code>JSON_USE_IMPLICIT_CONVERSIONS</code> to <code>0</code> and replace any implicit conversions with calls to <code>get</code>.</p>"},{"location":"api/basic_json/operator_ValueType/#examples","title":"Examples","text":"Example <p>The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard <code>std::vector<short></code>, (3) A JSON object can be converted to C++ associative containers such as <code>std::unordered_map<std::string, json></code>.</p> <pre><code>#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use implicit conversions\n bool v1 = json_types[\"boolean\"];\n int v2 = json_types[\"number\"][\"integer\"];\n short v3 = json_types[\"number\"][\"integer\"];\n float v4 = json_types[\"number\"][\"floating-point\"];\n int v5 = json_types[\"number\"][\"floating-point\"];\n std::string v6 = json_types[\"string\"];\n std::vector<short> v7 = json_types[\"array\"];\n std::unordered_map<std::string, json> v8 = json_types;\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n\n // example for an exception\n try\n {\n bool v1 = json_types[\"string\"];\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n[json.exception.type_error.302] type must be boolean, but is string\n</code></pre>"},{"location":"api/basic_json/operator_ValueType/#version-history","title":"Version history","text":"<ul> <li>Since version 1.0.0.</li> <li>Macros <code>JSON_EXPLICIT</code>/<code>JSON_USE_IMPLICIT_CONVERSIONS</code> added in version 3.9.0.</li> </ul>"},{"location":"api/basic_json/operator_eq/","title":"nlohmann::basic_json::operator==","text":"<pre><code>// until C++20\nbool operator==(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator==(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator==(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n\n// since C++20\nclass basic_json {\n bool operator==(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n bool operator==(ScalarType rhs) const noexcept; // (2)\n};\n</code></pre> <ol> <li> <p>Compares two JSON values for equality according to the following rules:</p> <ul> <li>Two JSON values are equal if (1) neither value is discarded, or (2) they are of the same type and their stored values are the same according to their respective <code>operator==</code>.</li> <li>Integer and floating-point numbers are automatically converted before comparison.</li> </ul> </li> <li> <p>Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the scalar to a JSON value and comparing both JSON values according to 1.</p> </li> </ol>"},{"location":"api/basic_json/operator_eq/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"<p>whether the values <code>lhs</code>/<code>*this</code> and <code>rhs</code> are equal</p>"},{"location":"api/basic_json/operator_eq/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_eq/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_eq/#notes","title":"Notes","text":"<p>Comparing special values</p> <ul> <li><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>false</code>:<ol> <li>Comparing a <code>NaN</code> with itself.</li> <li>Comparing a <code>NaN</code> with another <code>NaN</code>.</li> <li>Comparing a <code>NaN</code> and any other number.</li> </ol> </li> <li>JSON <code>null</code> values are all equal.</li> <li>Discarded values never compare equal to themselves.</li> </ul> <p>Comparing floating-point numbers</p> <p>Floating-point numbers inside JSON values numbers are compared with <code>json::number_float_t::operator==</code> which is <code>double::operator==</code> by default. To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance</p> <pre><code>template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\ninline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n{\n return std::abs(a - b) <= epsilon;\n}\n</code></pre> <p>Or you can self-defined operator equal function like this:</p> <pre><code>bool my_equal(const_reference lhs, const_reference rhs)\n{\n const auto lhs_type lhs.type();\n const auto rhs_type rhs.type();\n if (lhs_type == rhs_type)\n {\n switch(lhs_type)\n // self_defined case\n case value_t::number_float:\n return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();\n // other cases remain the same with the original\n ...\n }\n...\n}\n</code></pre> <p>Comparing different <code>basic_json</code> specializations</p> <p>Comparing different <code>basic_json</code> specializations can have surprising effects. For instance, the result of comparing the JSON objects</p> <pre><code>{\n \"version\": 1,\n \"type\": \"integer\"\n}\n</code></pre> <p>and</p> <pre><code>{\n \"type\": \"integer\",\n \"version\": 1\n}\n</code></pre> <p>depends on whether <code>nlohmann::json</code> or <code>nlohmann::ordered_json</code> is used:</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n nlohmann::json uj1 = {{\"version\", 1}, {\"type\", \"integer\"}};\n nlohmann::json uj2 = {{\"type\", \"integer\"}, {\"version\", 1}};\n\n nlohmann::ordered_json oj1 = {{\"version\", 1}, {\"type\", \"integer\"}};\n nlohmann::ordered_json oj2 = {{\"type\", \"integer\"}, {\"version\", 1}};\n\n std::cout << std::boolalpha << (uj1 == uj2) << '\\n' << (oj1 == oj2) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\nfalse\n</code></pre>"},{"location":"api/basic_json/operator_eq/#examples","title":"Examples","text":"Example <p>The example demonstrates comparing several JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.000000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 == array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 == object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 == number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 == string_2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] == [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} == {\"A\":\"a\",\"B\":\"b\"} true\n17 == 17.0 true\n\"foo\" == \"bar\" false\n</code></pre> Example <p>The example demonstrates comparing several JSON types against the null pointer (JSON <code>null</code>).</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array = {1, 2, 3};\n json object = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json number = 17;\n json string = \"foo\";\n json null;\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array << \" == nullptr \" << (array == nullptr) << '\\n';\n std::cout << object << \" == nullptr \" << (object == nullptr) << '\\n';\n std::cout << number << \" == nullptr \" << (number == nullptr) << '\\n';\n std::cout << string << \" == nullptr \" << (string == nullptr) << '\\n';\n std::cout << null << \" == nullptr \" << (null == nullptr) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] == nullptr false\n{\"A\":\"a\",\"B\":\"b\"} == nullptr false\n17 == nullptr false\n\"foo\" == nullptr false\nnull == nullptr true\n</code></pre>"},{"location":"api/basic_json/operator_eq/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Added C++20 member functions in version 3.11.0.</li> <li>Added in version 1.0.0. Added C++20 member functions in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_ge/","title":"nlohmann::basic_json::operator>=","text":"<pre><code>// until C++20\nbool operator>=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator>=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator>=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n</code></pre> <ol> <li> <p>Compares whether one JSON value <code>lhs</code> is greater than or equal to another JSON value <code>rhs</code> according to the following rules:</p> <ul> <li>The comparison always yields <code>false</code> if (1) either operand is discarded, or (2) either operand is <code>NaN</code> and the other operand is either <code>NaN</code> or any other number.</li> <li>Otherwise, returns the result of <code>!(lhs < rhs)</code> (see operator<).</li> </ul> </li> <li> <p>Compares whether a JSON value is greater than or equal to a scalar or a scalar is greater than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.</p> </li> </ol>"},{"location":"api/basic_json/operator_ge/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"<p>whether <code>lhs</code> is less than or equal to <code>rhs</code></p>"},{"location":"api/basic_json/operator_ge/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_ge/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_ge/#notes","title":"Notes","text":"<p>Comparing <code>NaN</code></p> <p><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>false</code>: 1. Comparing a <code>NaN</code> with itself. 2. Comparing a <code>NaN</code> with another <code>NaN</code>. 3. Comparing a <code>NaN</code> and any other number.</p> <p>Operator overload resolution</p> <p>Since C++20 overload resolution will consider the rewritten candidate generated from <code>operator<=></code>.</p>"},{"location":"api/basic_json/operator_ge/#examples","title":"Examples","text":"Example <p>The example demonstrates comparing several JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" >= \" << array_2 << \" \" << (array_1 >= array_2) << '\\n';\n std::cout << object_1 << \" >= \" << object_2 << \" \" << (object_1 >= object_2) << '\\n';\n std::cout << number_1 << \" >= \" << number_2 << \" \" << (number_1 >= number_2) << '\\n';\n std::cout << string_1 << \" >= \" << string_2 << \" \" << (string_1 >= string_2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] >= [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} >= {\"A\":\"a\",\"B\":\"b\"} true\n17 >= 17.0000000000001 false\n\"foo\" >= \"bar\" true\n</code></pre>"},{"location":"api/basic_json/operator_ge/#see-also","title":"See also","text":"<ul> <li>operator<=> comparison: 3-way</li> </ul>"},{"location":"api/basic_json/operator_ge/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_gt/","title":"nlohmann::basic_json::operator>","text":"<pre><code>// until C++20\nbool operator>(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator>(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator>(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n</code></pre> <ol> <li> <p>Compares whether one JSON value <code>lhs</code> is greater than another JSON value <code>rhs</code> according to the following rules:</p> <ul> <li>The comparison always yields <code>false</code> if (1) either operand is discarded, or (2) either operand is <code>NaN</code> and the other operand is either <code>NaN</code> or any other number.</li> <li>Otherwise, returns the result of <code>!(lhs <= rhs)</code> (see operator<=).</li> </ul> </li> <li> <p>Compares wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.</p> </li> </ol>"},{"location":"api/basic_json/operator_gt/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"<p>whether <code>lhs</code> is greater than <code>rhs</code></p>"},{"location":"api/basic_json/operator_gt/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_gt/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_gt/#notes","title":"Notes","text":"<p>Comparing <code>NaN</code></p> <p><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>false</code>: 1. Comparing a <code>NaN</code> with itself. 2. Comparing a <code>NaN</code> with another <code>NaN</code>. 3. Comparing a <code>NaN</code> and any other number.</p> <p>Operator overload resolution</p> <p>Since C++20 overload resolution will consider the rewritten candidate generated from <code>operator<=></code>.</p>"},{"location":"api/basic_json/operator_gt/#examples","title":"Examples","text":"Example <p>The example demonstrates comparing several JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" > \" << array_2 << \" \" << (array_1 > array_2) << '\\n';\n std::cout << object_1 << \" > \" << object_2 << \" \" << (object_1 > object_2) << '\\n';\n std::cout << number_1 << \" > \" << number_2 << \" \" << (number_1 > number_2) << '\\n';\n std::cout << string_1 << \" > \" << string_2 << \" \" << (string_1 > string_2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] > [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} > {\"A\":\"a\",\"B\":\"b\"} false\n17 > 17.0000000000001 false\n\"foo\" > \"bar\" true\n</code></pre>"},{"location":"api/basic_json/operator_gt/#see-also","title":"See also","text":"<ul> <li>operator<=> comparison: 3-way</li> </ul>"},{"location":"api/basic_json/operator_gt/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_le/","title":"nlohmann::basic_json::operator<=","text":"<pre><code>// until C++20\nbool operator<=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator<=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator<=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n</code></pre> <ol> <li> <p>Compares whether one JSON value <code>lhs</code> is less than or equal to another JSON value <code>rhs</code> according to the following rules:</p> <ul> <li>The comparison always yields <code>false</code> if (1) either operand is discarded, or (2) either operand is <code>NaN</code> and the other operand is either <code>NaN</code> or any other number.</li> <li>Otherwise, returns the result of <code>!(rhs < lhs)</code> (see operator<).</li> </ul> </li> <li> <p>Compares wether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.</p> </li> </ol>"},{"location":"api/basic_json/operator_le/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"<p>whether <code>lhs</code> is less than or equal to <code>rhs</code></p>"},{"location":"api/basic_json/operator_le/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_le/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_le/#notes","title":"Notes","text":"<p>Comparing <code>NaN</code></p> <p><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>false</code>: 1. Comparing a <code>NaN</code> with itself. 2. Comparing a <code>NaN</code> with another <code>NaN</code>. 3. Comparing a <code>NaN</code> and any other number.</p> <p>Operator overload resolution</p> <p>Since C++20 overload resolution will consider the rewritten candidate generated from <code>operator<=></code>.</p>"},{"location":"api/basic_json/operator_le/#examples","title":"Examples","text":"Example <p>The example demonstrates comparing several JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" <= \" << array_2 << \" \" << (array_1 <= array_2) << '\\n';\n std::cout << object_1 << \" <= \" << object_2 << \" \" << (object_1 <= object_2) << '\\n';\n std::cout << number_1 << \" <= \" << number_2 << \" \" << (number_1 <= number_2) << '\\n';\n std::cout << string_1 << \" <= \" << string_2 << \" \" << (string_1 <= string_2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] <= [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} <= {\"A\":\"a\",\"B\":\"b\"} true\n17 <= 17.0000000000001 true\n\"foo\" <= \"bar\" false\n</code></pre>"},{"location":"api/basic_json/operator_le/#see-also","title":"See also","text":"<ul> <li>operator<=> comparison: 3-way</li> </ul>"},{"location":"api/basic_json/operator_le/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_lt/","title":"nlohmann::basic_json::operator<","text":"<pre><code>// until C++20\nbool operator<(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator<(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator<(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n</code></pre> <ol> <li> <p>Compares whether one JSON value <code>lhs</code> is less than another JSON value <code>rhs</code> according to the following rules:</p> <ul> <li>If either operand is discarded, the comparison yields <code>false</code>.</li> <li>If both operands have the same type, the values are compared using their respective <code>operator<</code>.</li> <li>Integer and floating-point numbers are automatically converted before comparison.</li> <li>In case <code>lhs</code> and <code>rhs</code> have different types, the values are ignored and the order of the types is considered, which is:<ol> <li>null</li> <li>boolean</li> <li>number (all types)</li> <li>object</li> <li>array</li> <li>string</li> <li>binary For instance, any boolean value is considered less than any string.</li> </ol> </li> </ul> </li> <li> <p>Compares wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.</p> </li> </ol>"},{"location":"api/basic_json/operator_lt/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"<p>whether <code>lhs</code> is less than <code>rhs</code></p>"},{"location":"api/basic_json/operator_lt/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_lt/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_lt/#notes","title":"Notes","text":"<p>Comparing <code>NaN</code></p> <p><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>false</code>: 1. Comparing a <code>NaN</code> with itself. 2. Comparing a <code>NaN</code> with another <code>NaN</code>. 3. Comparing a <code>NaN</code> and any other number.</p> <p>Operator overload resolution</p> <p>Since C++20 overload resolution will consider the rewritten candidate generated from <code>operator<=></code>.</p>"},{"location":"api/basic_json/operator_lt/#examples","title":"Examples","text":"Example <p>The example demonstrates comparing several JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 < array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 < object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 < number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 < string_2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] == [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} == {\"A\":\"a\",\"B\":\"b\"} false\n17 == 17.0000000000001 true\n\"foo\" == \"bar\" false\n</code></pre>"},{"location":"api/basic_json/operator_lt/#see-also","title":"See also","text":"<ul> <li>operator<=> comparison: 3-way</li> </ul>"},{"location":"api/basic_json/operator_lt/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> <li>Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_ne/","title":"nlohmann::basic_json::operator!=","text":"<pre><code>// until C++20\nbool operator!=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator!=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator!=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n\n// since C++20\nclass basic_json {\n bool operator!=(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n bool operator!=(ScalarType rhs) const noexcept; // (2)\n};\n</code></pre> <ol> <li> <p>Compares two JSON values for inequality according to the following rules:</p> <ul> <li>The comparison always yields <code>false</code> if (1) either operand is discarded, or (2) either operand is <code>NaN</code> and the other operand is either <code>NaN</code> or any other number.</li> <li>Otherwise, returns the result of <code>!(lhs == rhs)</code> (until C++20) or <code>!(*this == rhs)</code> (since C++20).</li> </ul> </li> <li> <p>Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1.</p> </li> </ol>"},{"location":"api/basic_json/operator_ne/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"<p>whether the values <code>lhs</code>/<code>*this</code> and <code>rhs</code> are not equal</p>"},{"location":"api/basic_json/operator_ne/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_ne/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_ne/#notes","title":"Notes","text":"<p>Comparing <code>NaN</code></p> <p><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>false</code>: 1. Comparing a <code>NaN</code> with itself. 2. Comparing a <code>NaN</code> with another <code>NaN</code>. 3. Comparing a <code>NaN</code> and any other number.</p>"},{"location":"api/basic_json/operator_ne/#examples","title":"Examples","text":"Example <p>The example demonstrates comparing several JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.000000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" != \" << array_2 << \" \" << (array_1 != array_2) << '\\n';\n std::cout << object_1 << \" != \" << object_2 << \" \" << (object_1 != object_2) << '\\n';\n std::cout << number_1 << \" != \" << number_2 << \" \" << (number_1 != number_2) << '\\n';\n std::cout << string_1 << \" != \" << string_2 << \" \" << (string_1 != string_2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] != [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} != {\"A\":\"a\",\"B\":\"b\"} false\n17 != 17.0 false\n\"foo\" != \"bar\" true\n</code></pre> Example <p>The example demonstrates comparing several JSON types against the null pointer (JSON <code>null</code>).</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array = {1, 2, 3};\n json object = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json number = 17;\n json string = \"foo\";\n json null;\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array << \" != nullptr \" << (array != nullptr) << '\\n';\n std::cout << object << \" != nullptr \" << (object != nullptr) << '\\n';\n std::cout << number << \" != nullptr \" << (number != nullptr) << '\\n';\n std::cout << string << \" != nullptr \" << (string != nullptr) << '\\n';\n std::cout << null << \" != nullptr \" << (null != nullptr) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] != nullptr true\n{\"A\":\"a\",\"B\":\"b\"} != nullptr true\n17 != nullptr true\n\"foo\" != nullptr true\nnull != nullptr false\n</code></pre>"},{"location":"api/basic_json/operator_ne/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Added C++20 member functions in version 3.11.0.</li> <li>Added in version 1.0.0. Added C++20 member functions in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_spaceship/","title":"nlohmann::basic_json::operator<=>","text":"<pre><code>// since C++20\nclass basic_json {\n std::partial_ordering operator<=>(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n std::partial_ordering operator<=>(const ScalarType rhs) const noexcept; // (2)\n};\n</code></pre> <ol> <li> <p>3-way compares two JSON values producing a result of type <code>std::partial_ordering</code> according to the following rules:</p> <ul> <li>Two JSON values compare with a result of <code>std::partial_ordering::unordered</code> if either value is discarded.</li> <li>If both JSON values are of the same type, the result is produced by 3-way comparing their stored values using their respective <code>operator<=></code>.</li> <li>Integer and floating-point numbers are converted to their common type and then 3-way compared using their respective <code>operator<=></code>. For instance, comparing an integer and a floating-point value will 3-way compare the first value converted to floating-point with the second value.</li> <li>Otherwise, yields a result by comparing the type (see <code>value_t</code>).</li> </ul> </li> <li> <p>3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way comparing both JSON values (see 1).</p> </li> </ol>"},{"location":"api/basic_json/operator_spaceship/#template-parameters","title":"Template parameters","text":"<code>ScalarType</code> a scalar type according to <code>std::is_scalar<ScalarType>::value</code>"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"<code>rhs</code> (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"<p>the <code>std::partial_ordering</code> of the 3-way comparison of <code>*this</code> and <code>rhs</code></p>"},{"location":"api/basic_json/operator_spaceship/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/operator_spaceship/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/operator_spaceship/#notes","title":"Notes","text":"<p>Comparing <code>NaN</code></p> <ul> <li><code>NaN</code> values are unordered within the domain of numbers. The following comparisons all yield <code>std::partial_ordering::unordered</code>:<ol> <li>Comparing a <code>NaN</code> with itself.</li> <li>Comparing a <code>NaN</code> with another <code>NaN</code>.</li> <li>Comparing a <code>NaN</code> and any other number.</li> </ol> </li> </ul>"},{"location":"api/basic_json/operator_spaceship/#examples","title":"Examples","text":"Example: (1) comparing JSON values <p>The example demonstrates comparing several JSON values.</p> <pre><code>#include <compare>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nconst char* to_string(const std::partial_ordering& po)\n{\n if (std::is_lt(po))\n {\n return \"less\";\n }\n else if (std::is_gt(po))\n {\n return \"greater\";\n }\n else if (std::is_eq(po))\n {\n return \"equivalent\";\n }\n return \"unordered\";\n}\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number = 17;\n json string = \"foo\";\n json discarded = json(json::value_t::discarded);\n\n // output values and comparisons\n std::cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string(array_1 <=> array_2) << '\\n'; // *NOPAD*\n std::cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string(object_1 <=> object_2) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << number << \" := \" << to_string(string <=> number) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << discarded << \" := \" << to_string(string <=> discarded) << '\\n'; // *NOPAD*\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3] <=> [1,2,4] := less\n{\"A\":\"a\",\"B\":\"b\"} <=> {\"A\":\"a\",\"B\":\"b\"} := equivalent\n\"foo\" <=> 17 := greater\n\"foo\" <=> <discarded> := unordered\n</code></pre> Example: (2) comparing JSON values and scalars <p>The example demonstrates comparing several JSON values and scalars.</p> <pre><code>#include <compare>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nconst char* to_string(const std::partial_ordering& po)\n{\n if (std::is_lt(po))\n {\n return \"less\";\n }\n else if (std::is_gt(po))\n {\n return \"greater\";\n }\n else if (std::is_eq(po))\n {\n return \"equivalent\";\n }\n return \"unordered\";\n}\n\nint main()\n{\n using float_limits = std::numeric_limits<json::number_float_t>;\n constexpr auto nan = float_limits::quiet_NaN();\n\n // create several JSON values\n json boolean = false;\n json number = 17;\n json string = \"17\";\n\n // output values and comparisons\n std::cout << std::boolalpha << std::fixed;\n std::cout << boolean << \" <=> \" << true << \" := \" << to_string(boolean <=> true) << '\\n'; // *NOPAD*\n std::cout << number << \" <=> \" << 17.0 << \" := \" << to_string(number <=> 17.0) << '\\n'; // *NOPAD*\n std::cout << number << \" <=> \" << nan << \" := \" << to_string(number <=> nan) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << 17 << \" := \" << to_string(string <=> 17) << '\\n'; // *NOPAD*\n}\n</code></pre> <p>Output:</p> <pre><code>false <=> true := less\n17 <=> 17.000000 := equivalent\n17 <=> nan := unordered\n\"17\" <=> 17 := greater\n</code></pre>"},{"location":"api/basic_json/operator_spaceship/#see-also","title":"See also","text":"<ul> <li>operator== - comparison: equal</li> <li>operator!= - comparison: not equal</li> <li>operator< - comparison: less than</li> <li>operator<= - comparison: less than or equal</li> <li>operator> - comparison: greater than</li> <li>operator>= - comparison: greater than or equal</li> </ul>"},{"location":"api/basic_json/operator_spaceship/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.11.0.</li> <li>Added in version 3.11.0.</li> </ol>"},{"location":"api/basic_json/operator_value_t/","title":"nlohmann::basic_json::operator value_t","text":"<pre><code>constexpr operator value_t() const noexcept;\n</code></pre> <p>Return the type of the JSON value as a value from the <code>value_t</code> enumeration.</p>"},{"location":"api/basic_json/operator_value_t/#return-value","title":"Return value","text":"<p>the type of the JSON value</p> Value type return value <code>null</code> <code>value_t::null</code> boolean <code>value_t::boolean</code> string <code>value_t::string</code> number (integer) <code>value_t::number_integer</code> number (unsigned integer) <code>value_t::number_unsigned</code> number (floating-point) <code>value_t::number_float</code> object <code>value_t::object</code> array <code>value_t::array</code> binary <code>value_t::binary</code> discarded <code>value_t::discarded</code>"},{"location":"api/basic_json/operator_value_t/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/operator_value_t/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/operator_value_t/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>operator value_t()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call operator value_t()\n json::value_t t_null = j_null;\n json::value_t t_boolean = j_boolean;\n json::value_t t_number_integer = j_number_integer;\n json::value_t t_number_unsigned = j_number_unsigned;\n json::value_t t_number_float = j_number_float;\n json::value_t t_object = j_object;\n json::value_t t_array = j_array;\n json::value_t t_string = j_string;\n\n // print types\n std::cout << std::boolalpha;\n std::cout << (t_null == json::value_t::null) << '\\n';\n std::cout << (t_boolean == json::value_t::boolean) << '\\n';\n std::cout << (t_number_integer == json::value_t::number_integer) << '\\n';\n std::cout << (t_number_unsigned == json::value_t::number_unsigned) << '\\n';\n std::cout << (t_number_float == json::value_t::number_float) << '\\n';\n std::cout << (t_object == json::value_t::object) << '\\n';\n std::cout << (t_array == json::value_t::array) << '\\n';\n std::cout << (t_string == json::value_t::string) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n</code></pre>"},{"location":"api/basic_json/operator_value_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Added unsigned integer type in version 2.0.0.</li> <li>Added binary type in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/other_error/","title":"nlohmann::basic_json::other_error","text":"<pre><code>class other_error : public exception;\n</code></pre> <p>This exception is thrown in case of errors that cannot be classified with the other exception types.</p> <p>Exceptions have ids 5xx (see list of other errors).</p> <p></p>"},{"location":"api/basic_json/other_error/#member-functions","title":"Member functions","text":"<ul> <li>what - returns explanatory string</li> </ul>"},{"location":"api/basic_json/other_error/#member-variables","title":"Member variables","text":"<ul> <li>id - the id of the exception</li> </ul>"},{"location":"api/basic_json/other_error/#examples","title":"Examples","text":"Example <p>The following code shows how a <code>other_error</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n try\n {\n // executing a failing JSON Patch operation\n json value = R\"({\n \"best_biscuit\": {\n \"name\": \"Oreo\"\n }\n })\"_json;\n json patch = R\"([{\n \"op\": \"test\",\n \"path\": \"/best_biscuit/name\",\n \"value\": \"Choco Leibniz\"\n }])\"_json;\n value.patch(patch);\n }\n catch (const json::other_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n</code></pre>"},{"location":"api/basic_json/other_error/#see-also","title":"See also","text":"<ul> <li>List of other errors</li> <li><code>parse_error</code> for exceptions indicating a parse error</li> <li><code>invalid_iterator</code> for exceptions indicating errors with iterators</li> <li><code>type_error</code> for exceptions indicating executing a member function with a wrong type</li> <li><code>out_of_range</code> for exceptions indicating access out of the defined range</li> </ul>"},{"location":"api/basic_json/other_error/#version-history","title":"Version history","text":"<ul> <li>Since version 3.0.0.</li> </ul>"},{"location":"api/basic_json/out_of_range/","title":"nlohmann::basic_json::out_of_range","text":"<pre><code>class out_of_range : public exception;\n</code></pre> <p>This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.</p> <p>Exceptions have ids 4xx (see list of out-of-range errors).</p> <p></p>"},{"location":"api/basic_json/out_of_range/#member-functions","title":"Member functions","text":"<ul> <li>what - returns explanatory string</li> </ul>"},{"location":"api/basic_json/out_of_range/#member-variables","title":"Member variables","text":"<ul> <li>id - the id of the exception</li> </ul>"},{"location":"api/basic_json/out_of_range/#examples","title":"Examples","text":"Example <p>The following code shows how a <code>out_of_range</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for an invalid index\n json j = {1, 2, 3, 4};\n j.at(4) = 10;\n }\n catch (const json::out_of_range& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n</code></pre>"},{"location":"api/basic_json/out_of_range/#see-also","title":"See also","text":"<ul> <li>List of out-of-range errors</li> <li><code>parse_error</code> for exceptions indicating a parse error</li> <li><code>invalid_iterator</code> for exceptions indicating errors with iterators</li> <li><code>type_error</code> for exceptions indicating executing a member function with a wrong type</li> <li><code>other_error</code> for exceptions indicating other library errors</li> </ul>"},{"location":"api/basic_json/out_of_range/#version-history","title":"Version history","text":"<ul> <li>Since version 3.0.0.</li> </ul>"},{"location":"api/basic_json/parse/","title":"nlohmann::basic_json::parse","text":"<pre><code>// (1)\ntemplate<typename InputType>\nstatic basic_json parse(InputType&& i,\n const parser_callback_t cb = nullptr,\n const bool allow_exceptions = true,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json parse(IteratorType first, IteratorType last,\n const parser_callback_t cb = nullptr,\n const bool allow_exceptions = true,\n const bool ignore_comments = false);\n</code></pre> <ol> <li>Deserialize from a compatible input.</li> <li> <p>Deserialize from a pair of character iterators</p> <p>The <code>value_type</code> of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.</p> </li> </ol>"},{"location":"api/basic_json/parse/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer (must not be null)</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>a <code>std::string</code></li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> <p>a compatible iterator type, for instance.</p> <ul> <li>a pair of <code>std::string::iterator</code> or <code>std::vector<std::uint8_t>::iterator</code></li> <li>a pair of pointers such as <code>ptr</code> and <code>ptr + len</code></li> </ul>"},{"location":"api/basic_json/parse/#parameters","title":"Parameters","text":"<code>i</code> (in) Input to parse from. <code>cb</code> (in) a parser callback function of type <code>parser_callback_t</code> which is used to control the deserialization by filtering unwanted values (optional) <code>allow_exceptions</code> (in) whether to throw exceptions in case of a parse error (optional, <code>true</code> by default) <code>ignore_comments</code> (in) whether comments should be ignored and treated like whitespace (<code>true</code>) or yield a parse error (<code>false</code>); (optional, <code>false</code> by default) <code>first</code> (in) iterator to start of character range <code>last</code> (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"<p>Deserialized JSON value; in case of a parse error and <code>allow_exceptions</code> set to <code>false</code>, the return value will be <code>value_t::discarded</code>. The latter can be checked with <code>is_discarded</code>.</p>"},{"location":"api/basic_json/parse/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/parse/#exceptions","title":"Exceptions","text":"<ul> <li>Throws <code>parse_error.101</code> in case of an unexpected token.</li> <li>Throws <code>parse_error.102</code> if to_unicode fails or surrogate error.</li> <li>Throws <code>parse_error.103</code> if to_unicode fails.</li> </ul>"},{"location":"api/basic_json/parse/#complexity","title":"Complexity","text":"<p>Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function <code>cb</code> or reading from (1) the input <code>i</code> or (2) the iterator range [<code>first</code>, <code>last</code>] has a super-linear complexity.</p>"},{"location":"api/basic_json/parse/#notes","title":"Notes","text":"<p>(1) A UTF-8 byte order mark is silently ignored.</p> <p>Runtime assertion</p> <p>The precondition that a passed <code>FILE</code> pointer must not be null is enforced with a runtime assertion.</p>"},{"location":"api/basic_json/parse/#examples","title":"Examples","text":"Parsing from a character array <p>The example below demonstrates the <code>parse()</code> function reading from an array.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n char text[] = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n</code></pre> Parsing from a string <p>The example below demonstrates the <code>parse()</code> function with and without callback function.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n</code></pre> Parsing from an input stream <p>The example below demonstrates the <code>parse()</code> function with and without callback function.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // fill a stream with JSON text\n std::stringstream ss;\n ss << text;\n\n // parse and serialize JSON\n json j_complete = json::parse(ss);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // fill a stream with JSON text\n ss.clear();\n ss << text;\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(ss, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n</code></pre> Parsing from a contiguous container <p>The example below demonstrates the <code>parse()</code> function reading from a contiguous container.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given as std::vector\n std::vector<std::uint8_t> text = {'[', '1', ',', '2', ',', '3', ']', '\\0'};\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>[\n 1,\n 2,\n 3\n]\n</code></pre> Parsing from a non null-terminated string <p>The example below demonstrates the <code>parse()</code> function reading from a string that is not null-terminated.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given as string that is not null-terminated\n const char* ptr = \"[1,2,3]another value\";\n\n // parse and serialize JSON\n json j_complete = json::parse(ptr, ptr + 7);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>[\n 1,\n 2,\n 3\n]\n</code></pre> Parsing from an iterator pair <p>The example below demonstrates the <code>parse()</code> function reading from an iterator pair.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given an input with other values\n std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'};\n\n // parse and serialize JSON\n json j_complete = json::parse(input.begin(), input.begin() + 7);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>[\n 1,\n 2,\n 3\n]\n</code></pre> Effect of <code>allow_exceptions</code> parameter <p>The example below demonstrates the effect of the <code>allow_exceptions</code> parameter in the \u00b4parse()` function.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // an invalid JSON text\n std::string text = R\"(\n {\n \"key\": \"value without closing quotes\n }\n )\";\n\n // parse with exceptions\n try\n {\n json j = json::parse(text);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n // parse without exceptions\n json j = json::parse(text, nullptr, false);\n\n if (j.is_discarded())\n {\n std::cout << \"the input is invalid JSON\" << std::endl;\n }\n else\n {\n std::cout << \"the input is valid JSON: \" << j << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.parse_error.101] parse error at line 4, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n; last read: '\"value without closing quotes<U+000A>'\nthe input is invalid JSON\n</code></pre>"},{"location":"api/basic_json/parse/#see-also","title":"See also","text":"<ul> <li>accept - check if the input is valid JSON</li> <li>operator>> - deserialize from stream</li> </ul>"},{"location":"api/basic_json/parse/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Overload for contiguous containers (1) added in version 2.0.3.</li> <li>Ignoring comments via <code>ignore_comments</code> added in version 3.9.0.</li> </ul> <p>Deprecation</p> <p>Overload (2) replaces calls to <code>parse</code> with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>parse({ptr, ptr+len}, ...);</code> with <code>parse(ptr, ptr+len, ...);</code>.</p> <p>You should be warned by your compiler with a <code>-Wdeprecated-declarations</code> warning if you are using a deprecated function.</p>"},{"location":"api/basic_json/parse_error/","title":"nlohmann::basic_json::parse_error","text":"<pre><code>class parse_error : public exception;\n</code></pre> <p>This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, BSON, CBOR, MessagePack, UBJSON, as well as when using JSON Patch.</p> <p>Member <code>byte</code> holds the byte index of the last read character in the input file (see note below).</p> <p>Exceptions have ids 1xx (see list of parse errors).</p> <p></p>"},{"location":"api/basic_json/parse_error/#member-functions","title":"Member functions","text":"<ul> <li>what - returns explanatory string</li> </ul>"},{"location":"api/basic_json/parse_error/#member-variables","title":"Member variables","text":"<ul> <li>id - the id of the exception</li> <li>byte - byte index of the parse error</li> </ul>"},{"location":"api/basic_json/parse_error/#notes","title":"Notes","text":"<p>For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector for binary formats.</p>"},{"location":"api/basic_json/parse_error/#examples","title":"Examples","text":"Example <p>The following code shows how a <code>parse_error</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // parsing input with a syntax error\n json::parse(\"[1,2,3,]\");\n }\n catch (const json::parse_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << '\\n'\n << \"byte position of error: \" << e.byte << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nexception id: 101\nbyte position of error: 8\n</code></pre>"},{"location":"api/basic_json/parse_error/#see-also","title":"See also","text":"<ul> <li>List of parse errors</li> <li><code>invalid_iterator</code> for exceptions indicating errors with iterators</li> <li><code>type_error</code> for exceptions indicating executing a member function with a wrong type</li> <li><code>out_of_range</code> for exceptions indicating access out of the defined range</li> <li><code>other_error</code> for exceptions indicating other library errors</li> </ul>"},{"location":"api/basic_json/parse_error/#version-history","title":"Version history","text":"<ul> <li>Since version 3.0.0.</li> </ul>"},{"location":"api/basic_json/parse_event_t/","title":"nlohmann::basic_json::parse_event_t","text":"<pre><code>enum class parse_event_t : std::uint8_t {\n object_start,\n object_end,\n array_start,\n array_end,\n key,\n value\n};\n</code></pre> <p>The parser callback distinguishes the following events:</p> <ul> <li><code>object_start</code>: the parser read <code>{</code> and started to process a JSON object</li> <li><code>key</code>: the parser read a key of a value in an object</li> <li><code>object_end</code>: the parser read <code>}</code> and finished processing a JSON object</li> <li><code>array_start</code>: the parser read <code>[</code> and started to process a JSON array</li> <li><code>array_end</code>: the parser read <code>]</code> and finished processing a JSON array</li> <li><code>value</code>: the parser finished reading a JSON value</li> </ul>"},{"location":"api/basic_json/parse_event_t/#examples","title":"Examples","text":""},{"location":"api/basic_json/parse_event_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/parser_callback_t/","title":"nlohmann::basic_json::parser_callback_t","text":"<pre><code>template<typename BasicJsonType>\nusing parser_callback_t =\n std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n</code></pre> <p>With a parser callback function, the result of parsing a JSON text can be influenced. When passed to <code>parse</code>, it is called on certain events (passed as <code>parse_event_t</code> via parameter <code>event</code>) with a set recursion depth <code>depth</code> and context JSON value <code>parsed</code>. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.</p> <p>We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters <code>depth</code>, <code>event</code>, and <code>parsed</code>.</p> parameter <code>event</code> description parameter <code>depth</code> parameter <code>parsed</code> <code>parse_event_t::object_start</code> the parser read <code>{</code> and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded <code>parse_event_t::key</code> the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key <code>parse_event_t::object_end</code> the parser read <code>}</code> and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object <code>parse_event_t::array_start</code> the parser read <code>[</code> and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded <code>parse_event_t::array_end</code> the parser read <code>]</code> and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array <code>parse_event_t::value</code> the parser finished reading a JSON value depth of the value the parsed JSON value <p></p> <p>Discarding a value (i.e., returning <code>false</code>) has different effects depending on the context in which function was called:</p> <ul> <li>Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read.</li> <li>In case a value outside a structured type is skipped, it is replaced with <code>null</code>. This case happens if the top-level element is skipped.</li> </ul>"},{"location":"api/basic_json/parser_callback_t/#parameters","title":"Parameters","text":"<code>depth</code> (in) the depth of the recursion during parsing <code>event</code> (in) an event of type <code>parse_event_t</code> indicating the context in the callback function has been called <code>parsed</code> (in, out) the current intermediate parse result; note that writing to this value has no effect for <code>parse_event_t::key</code> events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"<p>Whether the JSON value which called the function during parsing should be kept (<code>true</code>) or not (<code>false</code>). In the latter case, it is either skipped completely or replaced by an empty discarded object.</p>"},{"location":"api/basic_json/parser_callback_t/#examples","title":"Examples","text":"Example <p>The example below demonstrates the <code>parse()</code> function with and without callback function.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n</code></pre>"},{"location":"api/basic_json/parser_callback_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/patch/","title":"nlohmann::basic_json::patch","text":"<pre><code>basic_json patch(const basic_json& json_patch) const;\n</code></pre> <p>JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.</p>"},{"location":"api/basic_json/patch/#parameters","title":"Parameters","text":"<code>json_patch</code> (in) JSON patch document"},{"location":"api/basic_json/patch/#return-value","title":"Return value","text":"<p>patched document</p>"},{"location":"api/basic_json/patch/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/patch/#exceptions","title":"Exceptions","text":"<ul> <li>Throws <code>parse_error.104</code> if the JSON patch does not consist of an array of objects.</li> <li>Throws <code>parse_error.105</code> if the JSON patch is malformed (e.g., mandatory attributes are missing); example: <code>\"operation add must have member path\"</code>.</li> <li>Throws <code>out_of_range.401</code> if an array index is out of range.</li> <li>Throws <code>out_of_range.403</code> if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: <code>\"key baz not found\"</code>.</li> <li>Throws <code>out_of_range.405</code> if JSON pointer has no parent (\"add\", \"remove\", \"move\")</li> <li>Throws <code>out_of_range.501</code> if \"test\" operation was unsuccessful.</li> </ul>"},{"location":"api/basic_json/patch/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.</p>"},{"location":"api/basic_json/patch/#notes","title":"Notes","text":"<p>The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value.</p>"},{"location":"api/basic_json/patch/#examples","title":"Examples","text":"Example <p>The following code shows how a JSON patch is applied to a value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // apply the patch\n json patched_doc = doc.patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << doc << \"\\n\\n\"\n << std::setw(4) << patched_doc << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n</code></pre>"},{"location":"api/basic_json/patch/#see-also","title":"See also","text":"<ul> <li>RFC 6902 (JSON Patch)</li> <li>RFC 6901 (JSON Pointer)</li> <li>patch_inplace applies a JSON Patch without creating a copy of the document</li> <li>merge_patch applies a JSON Merge Patch</li> </ul>"},{"location":"api/basic_json/patch/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> </ul>"},{"location":"api/basic_json/patch_inplace/","title":"nlohmann::basic_json::patch_inplace","text":"<pre><code>void patch_inplace(const basic_json& json_patch) const;\n</code></pre> <p>JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. This function applies a JSON patch in place and returns void.</p>"},{"location":"api/basic_json/patch_inplace/#parameters","title":"Parameters","text":"<code>json_patch</code> (in) JSON patch document"},{"location":"api/basic_json/patch_inplace/#exception-safety","title":"Exception safety","text":"<p>No guarantees, value may be corrupted by an unsuccessful patch operation.</p>"},{"location":"api/basic_json/patch_inplace/#exceptions","title":"Exceptions","text":"<ul> <li>Throws <code>parse_error.104</code> if the JSON patch does not consist of an array of objects.</li> <li>Throws <code>parse_error.105</code> if the JSON patch is malformed (e.g., mandatory attributes are missing); example: <code>\"operation add must have member path\"</code>.</li> <li>Throws <code>out_of_range.401</code> if an array index is out of range.</li> <li>Throws <code>out_of_range.403</code> if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: <code>\"key baz not found\"</code>.</li> <li>Throws <code>out_of_range.405</code> if JSON pointer has no parent (\"add\", \"remove\", \"move\")</li> <li>Throws <code>out_of_range.501</code> if \"test\" operation was unsuccessful.</li> </ul>"},{"location":"api/basic_json/patch_inplace/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.</p>"},{"location":"api/basic_json/patch_inplace/#notes","title":"Notes","text":"<p>Unlike <code>patch</code>, <code>patch_inplace</code> applies the operation \"in place\" and no copy of the JSON value is created. That makes it faster for large documents by avoiding the copy. However, the JSON value might be corrupted if the function throws an exception.</p>"},{"location":"api/basic_json/patch_inplace/#examples","title":"Examples","text":"Example <p>The following code shows how a JSON patch is applied to a value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // output original document\n std::cout << \"Before\\n\" << std::setw(4) << doc << std::endl;\n\n // apply the patch\n doc.patch_inplace(patch);\n\n // output patched document\n std::cout << \"\\nAfter\\n\" << std::setw(4) << doc << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>Before\n{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\nAfter\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n</code></pre>"},{"location":"api/basic_json/patch_inplace/#see-also","title":"See also","text":"<ul> <li>RFC 6902 (JSON Patch)</li> <li>RFC 6901 (JSON Pointer)</li> <li>patch applies a JSON Merge Patch</li> <li>merge_patch applies a JSON Merge Patch</li> </ul>"},{"location":"api/basic_json/patch_inplace/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/basic_json/push_back/","title":"nlohmann::basic_json::push_back","text":"<pre><code>// (1)\nvoid push_back(basic_json&& val);\nvoid push_back(const basic_json& val);\n\n// (2)\nvoid push_back(const typename object_t::value_type& val);\n\n// (3)\nvoid push_back(initializer_list_t init);\n</code></pre> <ol> <li> <p>Appends the given element <code>val</code> to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending <code>val</code>.</p> </li> <li> <p>Inserts the given element <code>val</code> to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting <code>val</code>.</p> </li> <li> <p>This function allows using <code>push_back</code> with an initializer list. In case</p> <ol> <li>the current value is an object,</li> <li>the initializer list <code>init</code> contains only two elements, and</li> <li>the first element of <code>init</code> is a string,</li> </ol> <p><code>init</code> is converted into an object element and added using <code>push_back(const typename object_t::value_type&)</code>. Otherwise, <code>init</code> is converted to a JSON value and added using <code>push_back(basic_json&&)</code>.</p> </li> </ol>"},{"location":"api/basic_json/push_back/#parameters","title":"Parameters","text":"<code>val</code> (in) the value to add to the JSON array/object <code>init</code> (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"<p>All functions can throw the following exception: - Throws <code>type_error.308</code> when called on a type other than JSON array or null; example: <code>\"cannot use push_back() with number\"</code></p>"},{"location":"api/basic_json/push_back/#complexity","title":"Complexity","text":"<ol> <li>Amortized constant.</li> <li>Logarithmic in the size of the container, O(log(<code>size()</code>)).</li> <li>Linear in the size of the initializer list <code>init</code>.</li> </ol>"},{"location":"api/basic_json/push_back/#notes","title":"Notes","text":"<p>(3) This function is required to resolve an ambiguous overload error, because pairs like <code>{\"key\", \"value\"}</code> can be both interpreted as <code>object_t::value_type</code> or <code>std::initializer_list<basic_json></code>, see #235 for more information.</p>"},{"location":"api/basic_json/push_back/#examples","title":"Examples","text":"Example: (1) add element to array <p>The example shows how <code>push_back()</code> and <code>+=</code> can be used to add elements to a JSON array. Note how the <code>null</code> value was silently converted to a JSON array.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n</code></pre> Example: (2) add element to object <p>The example shows how <code>push_back()</code> and <code>+=</code> can be used to add elements to a JSON object. Note how the <code>null</code> value was silently converted to a JSON object.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n object.push_back(json::object_t::value_type(\"three\", 3));\n object += json::object_t::value_type(\"four\", 4);\n null += json::object_t::value_type(\"A\", \"a\");\n null += json::object_t::value_type(\"B\", \"b\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n</code></pre> Example: (3) add to object from initializer list <p>The example shows how initializer lists are treated as objects when possible.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values:\n object.push_back({\"three\", 3}); // object is extended\n object += {\"four\", 4}; // object is extended\n null.push_back({\"five\", 5}); // null is converted to array\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // would throw:\n //object.push_back({1, 2, 3});\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n</code></pre>"},{"location":"api/basic_json/push_back/#version-history","title":"Version history","text":"<ol> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 2.0.0.</li> </ol>"},{"location":"api/basic_json/rbegin/","title":"nlohmann::basic_json::rbegin","text":"<pre><code>reverse_iterator rbegin() noexcept;\nconst_reverse_iterator rbegin() const noexcept;\n</code></pre> <p>Returns an iterator to the reverse-beginning; that is, the last element.</p> <p></p>"},{"location":"api/basic_json/rbegin/#return-value","title":"Return value","text":"<p>reverse iterator to the first element</p>"},{"location":"api/basic_json/rbegin/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/rbegin/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/rbegin/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>rbegin()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-beginning\n json::reverse_iterator it = array.rbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>5\n</code></pre>"},{"location":"api/basic_json/rbegin/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/rend/","title":"nlohmann::basic_json::rend","text":"<pre><code>reverse_iterator rend() noexcept;\nconst_reverse_iterator rend() const noexcept;\n</code></pre> <p>Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.</p> <p></p>"},{"location":"api/basic_json/rend/#return-value","title":"Return value","text":"<p>reverse iterator to the element following the last element</p>"},{"location":"api/basic_json/rend/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/rend/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/rend/#examples","title":"Examples","text":"Example <p>The following code shows an example for <code>eend()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-end\n json::reverse_iterator it = array.rend();\n\n // increment the iterator to point to the first element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>1\n</code></pre>"},{"location":"api/basic_json/rend/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/sax_parse/","title":"nlohmann::basic_json::sax_parse","text":"<pre><code>// (1)\ntemplate <typename InputType, typename SAX>\nstatic bool sax_parse(InputType&& i,\n SAX* sax,\n input_format_t format = input_format_t::json,\n const bool strict = true,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<class IteratorType, class SAX>\nstatic bool sax_parse(IteratorType first, IteratorType last,\n SAX* sax,\n input_format_t format = input_format_t::json,\n const bool strict = true,\n const bool ignore_comments = false);\n</code></pre> <p>Read from input and generate SAX events</p> <ol> <li>Read from a compatible input.</li> <li> <p>Read from a pair of character iterators</p> <p>The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.</p> </li> </ol> <p>The SAX event lister must follow the interface of <code>json_sax</code>.</p>"},{"location":"api/basic_json/sax_parse/#template-parameters","title":"Template parameters","text":"<code>InputType</code> <p>A compatible input, for instance:</p> <ul> <li>an <code>std::istream</code> object</li> <li>a <code>FILE</code> pointer</li> <li>a C-style array of characters</li> <li>a pointer to a null-terminated string of single byte characters</li> <li>an object <code>obj</code> for which <code>begin(obj)</code> and <code>end(obj)</code> produces a valid pair of iterators.</li> </ul> <code>IteratorType</code> Description <code>SAX</code> Description"},{"location":"api/basic_json/sax_parse/#parameters","title":"Parameters","text":"<code>i</code> (in) Input to parse from. <code>sax</code> (in) SAX event listener <code>format</code> (in) the format to parse (JSON, CBOR, MessagePack, or UBJSON) (optional, <code>input_format_t::json</code> by default), see <code>input_format_t</code> for more information <code>strict</code> (in) whether the input has to be consumed completely (optional, <code>true</code> by default) <code>ignore_comments</code> (in) whether comments should be ignored and treated like whitespace (<code>true</code>) or yield a parse error (<code>false</code>); (optional, <code>false</code> by default) <code>first</code> (in) iterator to start of character range <code>last</code> (in) iterator to end of character range"},{"location":"api/basic_json/sax_parse/#return-value","title":"Return value","text":"<p>return value of the last processed SAX event</p>"},{"location":"api/basic_json/sax_parse/#exception-safety","title":"Exception safety","text":""},{"location":"api/basic_json/sax_parse/#complexity","title":"Complexity","text":"<p>Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer <code>sax</code> has a super-linear complexity.</p>"},{"location":"api/basic_json/sax_parse/#notes","title":"Notes","text":"<p>A UTF-8 byte order mark is silently ignored.</p>"},{"location":"api/basic_json/sax_parse/#examples","title":"Examples","text":"Example <p>The example below demonstrates the <code>sax_parse()</code> function reading from string and processing the events with a user-defined SAX event consumer.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/basic_json/sax_parse/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> <li>Ignoring comments via <code>ignore_comments</code> added in version 3.9.0.</li> </ul> <p>Deprecation</p> <p>Overload (2) replaces calls to <code>sax_parse</code> with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like <code>sax_parse({ptr, ptr+len});</code> with <code>sax_parse(ptr, ptr+len);</code>.</p>"},{"location":"api/basic_json/size/","title":"nlohmann::basic_json::size","text":"<pre><code>size_type size() const noexcept;\n</code></pre> <p>Returns the number of elements in a JSON value.</p>"},{"location":"api/basic_json/size/#return-value","title":"Return value","text":"<p>The return value depends on the different types and is defined as follows:</p> Value type return value null <code>0</code> boolean <code>1</code> string <code>1</code> number <code>1</code> binary <code>1</code> object result of function object_t::size() array result of function array_t::size()"},{"location":"api/basic_json/size/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/basic_json/size/#complexity","title":"Complexity","text":"<p>Constant, as long as <code>array_t</code> and <code>object_t</code> satisfy the Container concept; that is, their <code>size()</code> functions have constant complexity.</p>"},{"location":"api/basic_json/size/#notes","title":"Notes","text":"<p>This function does not return the length of a string stored as JSON value -- it returns the number of elements in the JSON value which is <code>1</code> in the case of a string.</p>"},{"location":"api/basic_json/size/#examples","title":"Examples","text":"Example <p>The following code calls <code>size()</code> on the different value types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call size()\n std::cout << j_null.size() << '\\n';\n std::cout << j_boolean.size() << '\\n';\n std::cout << j_number_integer.size() << '\\n';\n std::cout << j_number_float.size() << '\\n';\n std::cout << j_object.size() << '\\n';\n std::cout << j_object_empty.size() << '\\n';\n std::cout << j_array.size() << '\\n';\n std::cout << j_array_empty.size() << '\\n';\n std::cout << j_string.size() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>0\n1\n1\n1\n2\n0\n5\n0\n1\n</code></pre>"},{"location":"api/basic_json/size/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended to return <code>1</code> for binary types in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/std_hash/","title":"std::hash<nlohmann::basic_json>","text":"<pre><code>namespace std {\n struct hash<nlohmann::basic_json>;\n}\n</code></pre> <p>Return a hash value for a JSON object. The hash function tries to rely on <code>std::hash</code> where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for <code>null</code>, <code>0</code>, <code>0U</code>, and <code>false</code>, etc.</p>"},{"location":"api/basic_json/std_hash/#examples","title":"Examples","text":"Example <p>The example shows how to calculate hash values for different JSON values.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n std::cout << \"hash(null) = \" << std::hash<json> {}(json(nullptr)) << '\\n'\n << \"hash(false) = \" << std::hash<json> {}(json(false)) << '\\n'\n << \"hash(0) = \" << std::hash<json> {}(json(0)) << '\\n'\n << \"hash(0U) = \" << std::hash<json> {}(json(0U)) << '\\n'\n << \"hash(\\\"\\\") = \" << std::hash<json> {}(json(\"\")) << '\\n'\n << \"hash({}) = \" << std::hash<json> {}(json::object()) << '\\n'\n << \"hash([]) = \" << std::hash<json> {}(json::array()) << '\\n'\n << \"hash({\\\"hello\\\": \\\"world\\\"}) = \" << std::hash<json> {}(\"{\\\"hello\\\": \\\"world\\\"}\"_json)\n << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>hash(null) = 2654435769\nhash(false) = 2654436030\nhash(0) = 2654436095\nhash(0U) = 2654436156\nhash(\"\") = 6142509191626859748\nhash({}) = 2654435832\nhash([]) = 2654435899\nhash({\"hello\": \"world\"}) = 4469488738203676328\n</code></pre> <p>Note the output is platform-dependent.</p>"},{"location":"api/basic_json/std_hash/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended for arbitrary basic_json types in version 3.10.5.</li> </ul>"},{"location":"api/basic_json/std_swap/","title":"std::swap<basic_json>","text":"<pre><code>namespace std {\n void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2);\n}\n</code></pre> <p>Exchanges the values of two JSON objects.</p>"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"<code>j1</code> (in, out) value to be replaced by <code>j2</code> <code>j2</code> (in, out) value to be replaced by <code>j1</code>"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"<pre><code>void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2)\n{\n j1.swap(j2);\n}\n</code></pre>"},{"location":"api/basic_json/std_swap/#examples","title":"Examples","text":"Example <p>The following code shows how two values are swapped with <code>std::swap</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j1 = {{\"one\", 1}, {\"two\", 2}};\n json j2 = {1, 2, 4, 8, 16};\n\n std::cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n';\n\n // swap values\n std::swap(j1, j2);\n\n std::cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>j1 = {\"one\":1,\"two\":2} | j2 = [1,2,4,8,16]\nj1 = [1,2,4,8,16] | j2 = {\"one\":1,\"two\":2}\n</code></pre>"},{"location":"api/basic_json/std_swap/#see-also","title":"See also","text":"<ul> <li>swap</li> </ul>"},{"location":"api/basic_json/std_swap/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Extended for arbitrary basic_json types in version 3.10.5.</li> </ul>"},{"location":"api/basic_json/string_t/","title":"nlohmann::basic_json::string_t","text":"<pre><code>using string_t = StringType;\n</code></pre> <p>The type used to store JSON strings.</p> <p>RFC 8259 describes JSON strings as follows:</p> <p>A string is a sequence of zero or more Unicode characters.</p> <p>To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.</p>"},{"location":"api/basic_json/string_t/#template-parameters","title":"Template parameters","text":"<code>StringType</code> the container to store strings (e.g., <code>std::string</code>). Note this container is used for keys/names in objects, see object_t."},{"location":"api/basic_json/string_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/string_t/#default-type","title":"Default type","text":"<p>With the default values for <code>StringType</code> (<code>std::string</code>), the default value for <code>string_t</code> is <code>std::string</code>.</p>"},{"location":"api/basic_json/string_t/#encoding","title":"Encoding","text":"<p>Strings are stored in UTF-8 encoding. Therefore, functions like <code>std::string::size()</code> or <code>std::string::length()</code> return the number of bytes in the string rather than the number of characters or glyphs.</p>"},{"location":"api/basic_json/string_t/#string-comparison","title":"String comparison","text":"<p>RFC 8259 states:</p> <p>Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that <code>\"a\\\\b\"</code> and <code>\"a\\u005Cb\"</code> are not equal.</p> <p>This implementation is interoperable as it does compare strings code unit by code unit.</p>"},{"location":"api/basic_json/string_t/#storage","title":"Storage","text":"<p>String values are stored as pointers in a <code>basic_json</code> type. That is, for any access to string values, a pointer of type <code>string_t*</code> must be dereferenced.</p>"},{"location":"api/basic_json/string_t/#examples","title":"Examples","text":"Example <p>The following code shows that <code>string_t</code> is by default, a typedef to <code>std::string</code>.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::string, json::string_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>true\n</code></pre>"},{"location":"api/basic_json/string_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/basic_json/swap/","title":"nlohmann::basic_json::swap","text":"<pre><code>// (1)\nvoid swap(reference other) noexcept;\n\n// (2)\nvoid swap(reference left, reference right) noexcept;\n\n// (3)\nvoid swap(array_t& other);\n\n// (4)\nvoid swap(object_t& other);\n\n// (5)\nvoid swap(string_t& other);\n\n// (6)\nvoid swap(binary_t& other);\n\n// (7)\nvoid swap(typename binary_t::container_type& other);\n</code></pre> <ol> <li>Exchanges the contents of the JSON value with those of <code>other</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. </li> <li>Exchanges the contents of the JSON value from <code>left</code> with those of <code>right</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Implemented as a friend function callable via ADL.</li> <li>Exchanges the contents of a JSON array with those of <code>other</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. </li> <li>Exchanges the contents of a JSON object with those of <code>other</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.</li> <li>Exchanges the contents of a JSON string with those of <code>other</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.</li> <li>Exchanges the contents of a binary value with those of <code>other</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.</li> <li>Exchanges the contents of a binary value with those of <code>other</code>. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike version (6), no binary subtype is involved.</li> </ol>"},{"location":"api/basic_json/swap/#parameters","title":"Parameters","text":"<code>other</code> (in, out) value to exchange the contents with <code>left</code> (in, out) value to exchange the contents with <code>right</code> (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"<ol> <li>No-throw guarantee: this function never throws exceptions.</li> <li>No-throw guarantee: this function never throws exceptions.</li> <li>Throws <code>type_error.310</code> if called on JSON values other than arrays; example: <code>\"cannot use swap() with boolean\"</code></li> <li>Throws <code>type_error.310</code> if called on JSON values other than objects; example: <code>\"cannot use swap() with boolean\"</code></li> <li>Throws <code>type_error.310</code> if called on JSON values other than strings; example: <code>\"cannot use swap() with boolean\"</code></li> <li>Throws <code>type_error.310</code> if called on JSON values other than binaries; example: <code>\"cannot use swap() with boolean\"</code></li> <li>Throws <code>type_error.310</code> if called on JSON values other than binaries; example: <code>\"cannot use swap() with boolean\"</code></li> </ol>"},{"location":"api/basic_json/swap/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/swap/#examples","title":"Examples","text":"Example: Swap JSON value (1, 2) <p>The example below shows how JSON values can be swapped with <code>swap()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create two JSON values\n json j1 = {1, 2, 3, 4, 5};\n json j2 = {{\"pi\", 3.141592653589793}, {\"e\", 2.718281828459045}};\n\n // swap the values\n j1.swap(j2);\n\n // output the values\n std::cout << \"j1 = \" << j1 << '\\n';\n std::cout << \"j2 = \" << j2 << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>j1 = {\"e\":2.718281828459045,\"pi\":3.141592653589793}\nj2 = [1,2,3,4,5]\n</code></pre> Example: Swap array (3) <p>The example below shows how arrays can be swapped with <code>swap()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = {{\"array\", {1, 2, 3, 4}}};\n\n // create an array_t\n json::array_t array = {\"Snap\", \"Crackle\", \"Pop\"};\n\n // swap the array stored in the JSON value\n value[\"array\"].swap(array);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"array = \" << array << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>value = {\"array\":[\"Snap\",\"Crackle\",\"Pop\"]}\narray = [1,2,3,4]\n</code></pre> Example: Swap object (4) <p>The example below shows how objects can be swapped with <code>swap()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { {\"translation\", {{\"one\", \"eins\"}, {\"two\", \"zwei\"}}} };\n\n // create an object_t\n json::object_t object = {{\"cow\", \"Kuh\"}, {\"dog\", \"Hund\"}};\n\n // swap the object stored in the JSON value\n value[\"translation\"].swap(object);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"object = \" << object << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>value = {\"translation\":{\"cow\":\"Kuh\",\"dog\":\"Hund\"}}\nobject = {\"one\":\"eins\",\"two\":\"zwei\"}\n</code></pre> Example: Swap string (5) <p>The example below shows how strings can be swapped with <code>swap()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { \"the good\", \"the bad\", \"the ugly\" };\n\n // create string_t\n json::string_t string = \"the fast\";\n\n // swap the object stored in the JSON value\n value[1].swap(string);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"string = \" << string << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>value = [\"the good\",\"the fast\",\"the ugly\"]\nstring = the bad\n</code></pre> Example: Swap string (6) <p>The example below shows how binary values can be swapped with <code>swap()</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary value\n json value = json::binary({1, 2, 3});\n\n // create a binary_t\n json::binary_t binary = {{4, 5, 6}};\n\n // swap the object stored in the JSON value\n value.swap(binary);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"binary = \" << json(binary) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>value = {\"bytes\":[4,5,6],\"subtype\":null}\nbinary = {\"bytes\":[1,2,3],\"subtype\":null}\n</code></pre>"},{"location":"api/basic_json/swap/#see-also","title":"See also","text":"<ul> <li>std::swap<basic_json></li> </ul>"},{"location":"api/basic_json/swap/#version-history","title":"Version history","text":"<ol> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 1.0.0.</li> <li>Since version 3.8.0.</li> <li>Since version 3.8.0.</li> </ol>"},{"location":"api/basic_json/to_bjdata/","title":"nlohmann::basic_json::to_bjdata","text":"<pre><code>// (1)\nstatic std::vector<std::uint8_t> to_bjdata(const basic_json& j,\n const bool use_size = false,\n const bool use_type = false);\n\n// (2)\nstatic void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,\n const bool use_size = false, const bool use_type = false);\nstatic void to_bjdata(const basic_json& j, detail::output_adapter<char> o,\n const bool use_size = false, const bool use_type = false);\n</code></pre> <p>Serializes a given JSON value <code>j</code> to a byte vector using the BJData (Binary JData) serialization format. BJData aims to be more compact than JSON itself, yet more efficient to parse.</p> <ol> <li>Returns a byte vector containing the BJData serialization.</li> <li>Writes the BJData serialization to an output adapter.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON value to serialize <code>o</code> (in) output adapter to write serialization to <code>use_size</code> (in) whether to add size annotations to container types; optional, <code>false</code> by default. <code>use_type</code> (in) whether to add type annotations to container types (must be combined with <code>use_size = true</code>); optional, <code>false</code> by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"<ol> <li>BJData serialization as byte vector</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/to_bjdata/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/to_bjdata/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value <code>j</code>.</p>"},{"location":"api/basic_json/to_bjdata/#examples","title":"Examples","text":"Example <p>The example shows the serialization of a JSON value to a byte vector in BJData format.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print BJData's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to BJData\n std::vector<std::uint8_t> v = json::to_bjdata(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to BJData using default representation\n std::vector<std::uint8_t> v_array = json::to_bjdata(array);\n // serialize it to BJData using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);\n // serialize it to BJData using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n</code></pre>"},{"location":"api/basic_json/to_bjdata/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/basic_json/to_bson/","title":"nlohmann::basic_json::to_bson","text":"<pre><code>// (1)\nstatic std::vector<std::uint8_t> to_bson(const basic_json& j);\n\n// (2)\nstatic void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_bson(const basic_json& j, detail::output_adapter<char> o);\n</code></pre> <p>BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document).</p> <ol> <li>Returns a byte vector containing the BSON serialization.</li> <li>Writes the BSON serialization to an output adapter.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON value to serialize <code>o</code> (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"<ol> <li>BSON serialization as byte vector</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/to_bson/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/to_bson/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value <code>j</code>.</p>"},{"location":"api/basic_json/to_bson/#examples","title":"Examples","text":"Example <p>The example shows the serialization of a JSON value to a byte vector in BSON format.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector<std::uint8_t> v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 \n</code></pre>"},{"location":"api/basic_json/to_bson/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.4.0.</li> </ul>"},{"location":"api/basic_json/to_cbor/","title":"nlohmann::basic_json::to_cbor","text":"<pre><code>// (1)\nstatic std::vector<std::uint8_t> to_cbor(const basic_json& j);\n\n// (2)\nstatic void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_cbor(const basic_json& j, detail::output_adapter<char> o);\n</code></pre> <p>Serializes a given JSON value <code>j</code> to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.</p> <ol> <li>Returns a byte vector containing the CBOR serialization.</li> <li>Writes the CBOR serialization to an output adapter.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON value to serialize <code>o</code> (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"<ol> <li>CBOR serialization as byte vector</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/to_cbor/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/to_cbor/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value <code>j</code>.</p>"},{"location":"api/basic_json/to_cbor/#examples","title":"Examples","text":"Example <p>The example shows the serialization of a JSON value to a byte vector in CBOR format.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to CBOR\n std::vector<std::uint8_t> v = json::to_cbor(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n</code></pre>"},{"location":"api/basic_json/to_cbor/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.9.</li> <li>Compact representation of floating-point numbers added in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/to_msgpack/","title":"nlohmann::basic_json::to_msgpack","text":"<pre><code>// (1)\nstatic std::vector<std::uint8_t> to_msgpack(const basic_json& j);\n\n// (2)\nstatic void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_msgpack(const basic_json& j, detail::output_adapter<char> o);\n</code></pre> <p>Serializes a given JSON value <code>j</code> to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.</p> <ol> <li>Returns a byte vector containing the MessagePack serialization.</li> <li>Writes the MessagePack serialization to an output adapter.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON value to serialize <code>o</code> (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"<ol> <li>MessagePack serialization as byte vector</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/to_msgpack/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/to_msgpack/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value <code>j</code>.</p>"},{"location":"api/basic_json/to_msgpack/#examples","title":"Examples","text":"Example <p>The example shows the serialization of a JSON value to a byte vector in MessagePack format.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n</code></pre>"},{"location":"api/basic_json/to_msgpack/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.9.</li> </ul>"},{"location":"api/basic_json/to_string/","title":"to_string(basic_json)","text":"<pre><code>template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j);\n</code></pre> <p>This function implements a user-defined to_string for JSON objects.</p>"},{"location":"api/basic_json/to_string/#template-parameters","title":"Template parameters","text":"<code>BasicJsonType</code> a specialization of <code>basic_json</code>"},{"location":"api/basic_json/to_string/#return-value","title":"Return value","text":"<p>string containing the serialization of the JSON value</p>"},{"location":"api/basic_json/to_string/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</p>"},{"location":"api/basic_json/to_string/#exceptions","title":"Exceptions","text":"<p>Throws <code>type_error.316</code> if a string stored inside the JSON value is not UTF-8 encoded</p>"},{"location":"api/basic_json/to_string/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/to_string/#possible-implementation","title":"Possible implementation","text":"<pre><code>template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j)\n{\n return j.dump();\n}\n</code></pre>"},{"location":"api/basic_json/to_string/#examples","title":"Examples","text":"Example <p>The following code shows how the library's <code>to_string()</code> function integrates with others, allowing argument-dependent lookup.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing std::to_string;\n\nint main()\n{\n // create values\n json j = {{\"one\", 1}, {\"two\", 2}};\n int i = 42;\n\n // use ADL to select best to_string function\n auto j_str = to_string(j); // calling nlohmann::to_string\n auto i_str = to_string(i); // calling std::to_string\n\n // serialize without indentation\n std::cout << j_str << \"\\n\\n\"\n << i_str << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\"one\":1,\"two\":2}\n\n42\n</code></pre>"},{"location":"api/basic_json/to_string/#see-also","title":"See also","text":"<ul> <li>dump</li> </ul>"},{"location":"api/basic_json/to_string/#version-history","title":"Version history","text":"<p>Added in version 3.7.0.</p>"},{"location":"api/basic_json/to_ubjson/","title":"nlohmann::basic_json::to_ubjson","text":"<pre><code>// (1)\nstatic std::vector<std::uint8_t> to_ubjson(const basic_json& j,\n const bool use_size = false,\n const bool use_type = false);\n\n// (2)\nstatic void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,\n const bool use_size = false, const bool use_type = false);\nstatic void to_ubjson(const basic_json& j, detail::output_adapter<char> o,\n const bool use_size = false, const bool use_type = false);\n</code></pre> <p>Serializes a given JSON value <code>j</code> to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse.</p> <ol> <li>Returns a byte vector containing the UBJSON serialization.</li> <li>Writes the UBJSON serialization to an output adapter.</li> </ol> <p>The exact mapping and its limitations is described on a dedicated page.</p>"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON value to serialize <code>o</code> (in) output adapter to write serialization to <code>use_size</code> (in) whether to add size annotations to container types; optional, <code>false</code> by default. <code>use_type</code> (in) whether to add type annotations to container types (must be combined with <code>use_size = true</code>); optional, <code>false</code> by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"<ol> <li>UBJSON serialization as byte vector</li> <li>(none)</li> </ol>"},{"location":"api/basic_json/to_ubjson/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes in the JSON value.</p>"},{"location":"api/basic_json/to_ubjson/#complexity","title":"Complexity","text":"<p>Linear in the size of the JSON value <code>j</code>.</p>"},{"location":"api/basic_json/to_ubjson/#examples","title":"Examples","text":"Example <p>The example shows the serialization of a JSON value to a byte vector in UBJSON format.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print UBJSON's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to UBJSON\n std::vector<std::uint8_t> v = json::to_ubjson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to UBJSON using default representation\n std::vector<std::uint8_t> v_array = json::to_ubjson(array);\n // serialize it to UBJSON using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);\n // serialize it to UBJSON using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n</code></pre>"},{"location":"api/basic_json/to_ubjson/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.1.0.</li> </ul>"},{"location":"api/basic_json/type/","title":"nlohmann::basic_json::type","text":"<pre><code>constexpr value_t type() const noexcept;\n</code></pre> <p>Return the type of the JSON value as a value from the <code>value_t</code> enumeration.</p>"},{"location":"api/basic_json/type/#return-value","title":"Return value","text":"<p>the type of the JSON value</p> Value type return value <code>null</code> <code>value_t::null</code> boolean <code>value_t::boolean</code> string <code>value_t::string</code> number (integer) <code>value_t::number_integer</code> number (unsigned integer) <code>value_t::number_unsigned</code> number (floating-point) <code>value_t::number_float</code> object <code>value_t::object</code> array <code>value_t::array</code> binary <code>value_t::binary</code> discarded <code>value_t::discarded</code>"},{"location":"api/basic_json/type/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/type/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/type/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>type()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type()\n std::cout << std::boolalpha;\n std::cout << (j_null.type() == json::value_t::null) << '\\n';\n std::cout << (j_boolean.type() == json::value_t::boolean) << '\\n';\n std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\\n';\n std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\\n';\n std::cout << (j_number_float.type() == json::value_t::number_float) << '\\n';\n std::cout << (j_object.type() == json::value_t::object) << '\\n';\n std::cout << (j_array.type() == json::value_t::array) << '\\n';\n std::cout << (j_string.type() == json::value_t::string) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n</code></pre>"},{"location":"api/basic_json/type/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Added unsigned integer type in version 2.0.0.</li> <li>Added binary type in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/type_error/","title":"nlohmann::basic_json::type_error","text":"<pre><code>class type_error : public exception;\n</code></pre> <p>This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.</p> <p>Exceptions have ids 3xx (see list of type errors).</p> <p></p>"},{"location":"api/basic_json/type_error/#member-functions","title":"Member functions","text":"<ul> <li>what - returns explanatory string</li> </ul>"},{"location":"api/basic_json/type_error/#member-variables","title":"Member variables","text":"<ul> <li>id - the id of the exception</li> </ul>"},{"location":"api/basic_json/type_error/#examples","title":"Examples","text":"Example <p>The following code shows how a <code>type_error</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling push_back() on a string value\n json j = \"string\";\n j.push_back(\"another string\");\n }\n catch (const json::type_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n</code></pre>"},{"location":"api/basic_json/type_error/#see-also","title":"See also","text":"<ul> <li>List of type errors</li> <li><code>parse_error</code> for exceptions indicating a parse error</li> <li><code>invalid_iterator</code> for exceptions indicating errors with iterators</li> <li><code>out_of_range</code> for exceptions indicating access out of the defined range</li> <li><code>other_error</code> for exceptions indicating other library errors</li> </ul>"},{"location":"api/basic_json/type_error/#version-history","title":"Version history","text":"<ul> <li>Since version 3.0.0.</li> </ul>"},{"location":"api/basic_json/type_name/","title":"nlohmann::basic_json::type_name","text":"<pre><code>const char* type_name() const noexcept;\n</code></pre> <p>Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type.</p>"},{"location":"api/basic_json/type_name/#return-value","title":"Return value","text":"<p>a string representation of the type (<code>value_t</code>):</p> Value type return value <code>null</code> <code>\"null\"</code> boolean <code>\"boolean\"</code> string <code>\"string\"</code> number (integer, unsigned integer, floating-point) <code>\"number\"</code> object <code>\"object\"</code> array <code>\"array\"</code> binary <code>\"binary\"</code> discarded <code>\"discarded\"</code>"},{"location":"api/basic_json/type_name/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/type_name/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/basic_json/type_name/#examples","title":"Examples","text":"Example <p>The following code exemplifies <code>type_name()</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type_name()\n std::cout << j_null << \" is a \" << j_null.type_name() << '\\n';\n std::cout << j_boolean << \" is a \" << j_boolean.type_name() << '\\n';\n std::cout << j_number_integer << \" is a \" << j_number_integer.type_name() << '\\n';\n std::cout << j_number_unsigned << \" is a \" << j_number_unsigned.type_name() << '\\n';\n std::cout << j_number_float << \" is a \" << j_number_float.type_name() << '\\n';\n std::cout << j_object << \" is an \" << j_object.type_name() << '\\n';\n std::cout << j_array << \" is an \" << j_array.type_name() << '\\n';\n std::cout << j_string << \" is a \" << j_string.type_name() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>null is a null\ntrue is a boolean\n-17 is a number\n42 is a number\n23.42 is a number\n{\"one\":1,\"two\":2} is an object\n[1,2,4,8,16] is an array\n\"Hello, world\" is a string\n</code></pre>"},{"location":"api/basic_json/type_name/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Part of the public API version since 2.1.0.</li> <li>Changed return value to <code>const char*</code> and added <code>noexcept</code> in version 3.0.0.</li> <li>Added support for binary type in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/unflatten/","title":"nlohmann::basic_json::unflatten","text":"<pre><code>basic_json unflatten() const;\n</code></pre> <p>The function restores the arbitrary nesting of a JSON value that has been flattened before using the <code>flatten()</code> function. The JSON value must meet certain constraints:</p> <ol> <li>The value must be an object.</li> <li>The keys must be JSON pointers (see RFC 6901)</li> <li>The mapped values must be primitive JSON types.</li> </ol>"},{"location":"api/basic_json/unflatten/#return-value","title":"Return value","text":"<p>the original JSON from a flattened version</p>"},{"location":"api/basic_json/unflatten/#exception-safety","title":"Exception safety","text":"<p>Strong exception safety: if an exception occurs, the original value stays intact.</p>"},{"location":"api/basic_json/unflatten/#exceptions","title":"Exceptions","text":"<p>The function can throw the following exceptions:</p> <ul> <li>Throws <code>type_error.314</code> if value is not an object</li> <li>Throws <code>type_error.315</code> if object values are not primitive</li> </ul>"},{"location":"api/basic_json/unflatten/#complexity","title":"Complexity","text":"<p>Linear in the size the JSON value.</p>"},{"location":"api/basic_json/unflatten/#notes","title":"Notes","text":"<p>Empty objects and arrays are flattened by <code>flatten()</code> to <code>null</code> values and can not unflattened to their original type. Apart from this example, for a JSON value <code>j</code>, the following is always true: <code>j == j.flatten().unflatten()</code>.</p>"},{"location":"api/basic_json/unflatten/#examples","title":"Examples","text":"Example <p>The following code shows how a flattened JSON object is unflattened into the original nested JSON object.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value\n json j_flattened =\n {\n {\"/answer/everything\", 42},\n {\"/happy\", true},\n {\"/list/0\", 1},\n {\"/list/1\", 0},\n {\"/list/2\", 2},\n {\"/name\", \"Niels\"},\n {\"/nothing\", nullptr},\n {\"/object/currency\", \"USD\"},\n {\"/object/value\", 42.99},\n {\"/pi\", 3.141}\n };\n\n // call unflatten()\n std::cout << std::setw(4) << j_flattened.unflatten() << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"answer\": {\n \"everything\": 42\n },\n \"happy\": true,\n \"list\": [\n 1,\n 0,\n 2\n ],\n \"name\": \"Niels\",\n \"nothing\": null,\n \"object\": {\n \"currency\": \"USD\",\n \"value\": 42.99\n },\n \"pi\": 3.141\n}\n</code></pre>"},{"location":"api/basic_json/unflatten/#see-also","title":"See also","text":"<ul> <li>flatten the reverse function</li> </ul>"},{"location":"api/basic_json/unflatten/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> </ul>"},{"location":"api/basic_json/update/","title":"nlohmann::basic_json::update","text":"<pre><code>// (1)\nvoid update(const_reference j, bool merge_objects = false);\n\n// (2)\nvoid update(const_iterator first, const_iterator last, bool merge_objects = false);\n</code></pre> <ol> <li>Inserts all values from JSON object <code>j</code>.</li> <li>Inserts all values from range <code>[first, last)</code></li> </ol> <p>When <code>merge_objects</code> is <code>false</code> (default), existing keys are overwritten. When <code>merge_objects</code> is <code>true</code>, recursively merges objects with common keys.</p> <p>The function is motivated by Python's dict.update function.</p>"},{"location":"api/basic_json/update/#parameters","title":"Parameters","text":"<code>j</code> (in) JSON object to read values from <code>merge_objects</code> (in) when <code>true</code>, existing keys are not overwritten, but contents of objects are merged recursively (default: <code>false</code>) <code>first</code> (in) begin of the range of elements to insert <code>last</code> (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"<ol> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.312</code> if called on JSON values other than objects; example: <code>\"cannot use update() with string\"</code></li> </ul> </li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.312</code> if called on JSON values other than objects; example: <code>\"cannot use update() with string\"</code></li> <li>Throws <code>invalid_iterator.202</code> if called on an iterator which does not belong to the current JSON value; example: <code>\"iterator does not fit current value\"</code></li> <li>Throws <code>invalid_iterator.210</code> if <code>first</code> and <code>last</code> do not belong to the same JSON value; example: <code>\"iterators do not fit\"</code></li> </ul> </li> </ol>"},{"location":"api/basic_json/update/#complexity","title":"Complexity","text":"<ol> <li>O(N*log(size() + N)), where N is the number of elements to insert.</li> <li>O(N*log(size() + N)), where N is the number of elements to insert.</li> </ol>"},{"location":"api/basic_json/update/#examples","title":"Examples","text":"Example <p>The example shows how <code>update()</code> is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create two JSON objects\n json o1 = R\"( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} )\"_json;\n json o2 = R\"( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} )\"_json;\n json o3 = o1;\n\n // add all keys from o2 to o1 (updating \"color\", replacing \"names\")\n o1.update(o2);\n\n // add all keys from o2 to o1 (updating \"color\", merging \"names\")\n o3.update(o2, true);\n\n // output updated object o1 and o3\n std::cout << std::setw(2) << o1 << '\\n';\n std::cout << std::setw(2) << o3 << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"color\": \"blue\",\n \"names\": {\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n{\n \"color\": \"blue\",\n \"names\": {\n \"de\": \"Flugzeug\",\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n</code></pre> Example <p>The example shows how <code>update()</code> is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create two JSON objects\n json o1 = R\"( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} )\"_json;\n json o2 = R\"( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} )\"_json;\n json o3 = o1;\n\n // add all keys from o2 to o1 (updating \"color\", replacing \"names\")\n o1.update(o2.begin(), o2.end());\n\n // add all keys from o2 to o1 (updating \"color\", merging \"names\")\n o3.update(o2.begin(), o2.end(), true);\n\n // output updated object o1 and o3\n std::cout << std::setw(2) << o1 << '\\n';\n std::cout << std::setw(2) << o3 << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"color\": \"blue\",\n \"names\": {\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n{\n \"color\": \"blue\",\n \"names\": {\n \"de\": \"Flugzeug\",\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n</code></pre> Example <p>One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects:</p> <pre><code>{\n \"color\": \"red\",\n \"active\": true,\n \"name\": {\"de\": \"Maus\", \"en\": \"mouse\"}\n}\n</code></pre> <p>The user may override the default settings selectively:</p> <pre><code>{\n \"color\": \"blue\",\n \"name\": {\"es\": \"rat\u00f3n\"},\n}\n</code></pre> <p>Then <code>update</code> manages the merging of default settings and user settings:</p> <pre><code>auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings);\n</code></pre> <p>Now <code>effective_settings</code> contains the default settings, but those keys set by the user are overwritten:</p> <pre><code>{\n \"color\": \"blue\",\n \"active\": true,\n \"name\": {\"es\": \"rat\u00f3n\"}\n}\n</code></pre> <p>Note existing keys were just overwritten. To merge objects, <code>merge_objects</code> setting should be set to <code>true</code>:</p> <pre><code>auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings, true);\n</code></pre> <pre><code>{\n \"color\": \"blue\",\n \"active\": true,\n \"name\": {\"de\": \"Maus\", \"en\": \"mouse\", \"es\": \"rat\u00f3n\"}\n}\n</code></pre>"},{"location":"api/basic_json/update/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.0.0.</li> <li>Added <code>merge_objects</code> parameter in 3.10.5.</li> </ul>"},{"location":"api/basic_json/value/","title":"nlohmann::basic_json::value","text":"<pre><code>// (1)\ntemplate<class ValueType>\nValueType value(const typename object_t::key_type& key,\n ValueType&& default_value) const;\n\n// (2)\ntemplate<class ValueType, class KeyType>\nValueType value(KeyType&& key,\n ValueType&& default_value) const;\n\n// (3)\ntemplate<class ValueType>\nValueType value(const json_pointer& ptr,\n const ValueType& default_value) const;\n</code></pre> <ol> <li> <p>Returns either a copy of an object's element at the specified key <code>key</code> or a given default value if no element with key <code>key</code> exists.</p> <p>The function is basically equivalent to executing <pre><code>try {\n return at(key);\n} catch(out_of_range) {\n return default_value;\n}\n</code></pre></p> </li> <li> <p>See 1. This overload is only available if <code>KeyType</code> is comparable with <code>typename object_t::key_type</code> and <code>typename object_comparator_t::is_transparent</code> denotes a type.</p> </li> <li> <p>Returns either a copy of an object's element at the specified JSON pointer <code>ptr</code> or a given default value if no value at <code>ptr</code> exists.</p> <p>The function is basically equivalent to executing <pre><code>try {\n return at(ptr);\n} catch(out_of_range) {\n return default_value;\n}\n</code></pre></p> </li> </ol> <p>Differences to <code>at</code> and <code>operator[]</code></p> <ul> <li>Unlike <code>at</code>, this function does not throw if the given <code>key</code>/<code>ptr</code> was not found.</li> <li>Unlike <code>operator[]</code>, this function does not implicitly add an element to the position defined by <code>key</code>/<code>ptr</code> key. This function is furthermore also applicable to const objects.</li> </ul>"},{"location":"api/basic_json/value/#template-parameters","title":"Template parameters","text":"<code>KeyType</code> A type for an object key other than <code>json_pointer</code> that is comparable with <code>string_t</code> using <code>object_comparator_t</code>. This can also be a string view (C++17). <code>ValueType</code> type compatible to JSON values, for instance <code>int</code> for JSON integer numbers, <code>bool</code> for JSON booleans, or <code>std::vector</code> types for JSON arrays. Note the type of the expected value at <code>key</code>/<code>ptr</code> and the default value <code>default_value</code> must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"<code>key</code> (in) key of the element to access <code>default_value</code> (in) the value to return if <code>key</code>/<code>ptr</code> found no value <code>ptr</code> (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"<ol> <li>copy of the element at key <code>key</code> or <code>default_value</code> if <code>key</code> is not found</li> <li>copy of the element at key <code>key</code> or <code>default_value</code> if <code>key</code> is not found</li> <li>copy of the element at JSON Pointer <code>ptr</code> or <code>default_value</code> if no value for <code>ptr</code> is found</li> </ol>"},{"location":"api/basic_json/value/#exception-safety","title":"Exception safety","text":"<p>Strong guarantee: if an exception is thrown, there are no changes to any JSON value.</p>"},{"location":"api/basic_json/value/#exceptions","title":"Exceptions","text":"<ol> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.302</code> if <code>default_value</code> does not match the type of the value at <code>key</code></li> <li>Throws <code>type_error.306</code> if the JSON value is not an object; in that case, using <code>value()</code> with a key makes no sense.</li> </ul> </li> <li>See 1.</li> <li>The function can throw the following exceptions:<ul> <li>Throws <code>type_error.302</code> if <code>default_value</code> does not match the type of the value at <code>ptr</code></li> <li>Throws <code>type_error.306</code> if the JSON value is not an object; in that case, using <code>value()</code> with a key makes no sense.</li> </ul> </li> </ol>"},{"location":"api/basic_json/value/#complexity","title":"Complexity","text":"<ol> <li>Logarithmic in the size of the container.</li> <li>Logarithmic in the size of the container.</li> <li>Logarithmic in the size of the container.</li> </ol>"},{"location":"api/basic_json/value/#examples","title":"Examples","text":"Example: (1) access specified object element with default value <p>The example below shows how object elements can be queried with a default value.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"integer\", 0);\n double v_floating = j.value(\"floating\", 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"nonexisting\", \"oops\");\n bool v_boolean = j.value(\"nonexisting\", false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>1 42.23 oops false\n</code></pre> Example: (2) access specified object element using string_view with default value <p>The example below shows how object elements can be queried with a default value.</p> <pre><code>#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"integer\"sv, 0);\n double v_floating = j.value(\"floating\"sv, 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"nonexisting\"sv, \"oops\");\n bool v_boolean = j.value(\"nonexisting\"sv, false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>1 42.23 oops false\n</code></pre> Example: (3) access specified object element via JSON Pointer with default value <p>The example below shows how object elements can be queried with a default value.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"/integer\"_json_pointer, 0);\n double v_floating = j.value(\"/floating\"_json_pointer, 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"/nonexisting\"_json_pointer, \"oops\");\n bool v_boolean = j.value(\"/nonexisting\"_json_pointer, false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>1 42.23 oops false\n</code></pre>"},{"location":"api/basic_json/value/#see-also","title":"See also","text":"<ul> <li>see <code>at</code> for access by reference with range checking</li> <li>see <code>operator[]</code> for unchecked access by reference</li> </ul>"},{"location":"api/basic_json/value/#version-history","title":"Version history","text":"<ol> <li>Added in version 1.0.0. Changed parameter <code>default_value</code> type from <code>const ValueType&</code> to <code>ValueType&&</code> in version 3.11.0.</li> <li>Added in version 3.11.0. Made <code>ValueType</code> the first template parameter in version 3.11.2.</li> <li>Added in version 2.0.2.</li> </ol>"},{"location":"api/basic_json/value_t/","title":"nlohmann::basic_json::value_t","text":"<pre><code>enum class value_t : std::uint8_t {\n null,\n object,\n array,\n string,\n boolean,\n number_integer,\n number_unsigned,\n number_float,\n binary,\n discarded\n};\n</code></pre> <p>This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions <code>is_null</code>, <code>is_object</code>, <code>is_array</code>, <code>is_string</code>, <code>is_boolean</code>, <code>is_number</code> (with <code>is_number_integer</code>, <code>is_number_unsigned</code>, and <code>is_number_float</code>), <code>is_discarded</code>, <code>is_binary</code>, <code>is_primitive</code>, and <code>is_structured</code> rely on it.</p>"},{"location":"api/basic_json/value_t/#notes","title":"Notes","text":"<p>Ordering</p> <p>The order of types is as follows:</p> <ol> <li><code>null</code></li> <li><code>boolean</code></li> <li><code>number_integer</code>, <code>number_unsigned</code>, <code>number_float</code></li> <li><code>object</code></li> <li><code>array</code></li> <li><code>string</code></li> <li><code>binary</code></li> </ol> <p><code>discarded</code> is unordered.</p> <p>Types of numbers</p> <p>There are three enumerators for numbers (<code>number_integer</code>, <code>number_unsigned</code>, and <code>number_float</code>) to distinguish between different types of numbers:</p> <ul> <li><code>number_unsigned_t</code> for unsigned integers</li> <li><code>number_integer_t</code> for signed integers</li> <li><code>number_float_t</code> for floating-point numbers or to approximate integers which do not fit into the limits of their respective type</li> </ul> <p>Comparison operators</p> <p><code>operator<</code> and <code>operator<=></code> (since C++20) are overloaded and compare according to the ordering described above. Until C++20 all other relational and equality operators yield results according to the integer value of each enumerator. Since C++20 some compilers consider the rewritten candidates generated from <code>operator<=></code> during overload resolution, while others do not. For predictable and portable behavior use:</p> <ul> <li><code>operator<</code> or <code>operator<=></code> when wanting to compare according to the order described above</li> <li><code>operator==</code> or <code>operator!=</code> when wanting to compare according to each enumerators integer value</li> </ul>"},{"location":"api/basic_json/value_t/#examples","title":"Examples","text":"Example <p>The following code how <code>type()</code> queries the <code>value_t</code> for all JSON types.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type()\n std::cout << std::boolalpha;\n std::cout << (j_null.type() == json::value_t::null) << '\\n';\n std::cout << (j_boolean.type() == json::value_t::boolean) << '\\n';\n std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\\n';\n std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\\n';\n std::cout << (j_number_float.type() == json::value_t::number_float) << '\\n';\n std::cout << (j_object.type() == json::value_t::object) << '\\n';\n std::cout << (j_array.type() == json::value_t::array) << '\\n';\n std::cout << (j_string.type() == json::value_t::string) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n</code></pre>"},{"location":"api/basic_json/value_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> <li>Added unsigned integer type in version 2.0.0.</li> <li>Added binary type in version 3.8.0.</li> </ul>"},{"location":"api/basic_json/~basic_json/","title":"nlohmann::basic_json::~basic_json","text":"<pre><code>~basic_json() noexcept;\n</code></pre> <p>Destroys the JSON value and frees all allocated memory.</p>"},{"location":"api/basic_json/~basic_json/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this member function never throws exceptions.</p>"},{"location":"api/basic_json/~basic_json/#complexity","title":"Complexity","text":"<p>Linear.</p>"},{"location":"api/basic_json/~basic_json/#version-history","title":"Version history","text":"<ul> <li>Added in version 1.0.0.</li> </ul>"},{"location":"api/byte_container_with_subtype/","title":"nlohmann::byte_container_with_subtype","text":"<pre><code>template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n</code></pre> <p>This type extends the template parameter <code>BinaryType</code> provided to <code>basic_json</code> with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type.</p>"},{"location":"api/byte_container_with_subtype/#template-parameters","title":"Template parameters","text":"<code>BinaryType</code> container to store bytes (<code>std::vector<std::uint8_t></code> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":"<ul> <li>container_type - the type of the underlying container (<code>BinaryType</code>)</li> <li>subtype_type - the type of the subtype (<code>std::uint64_t</code>)</li> </ul>"},{"location":"api/byte_container_with_subtype/#member-functions","title":"Member functions","text":"<ul> <li>(constructor)</li> <li>operator== - comparison: equal</li> <li>operator!= - comparison: not equal</li> <li>set_subtype - sets the binary subtype</li> <li>subtype - return the binary subtype</li> <li>has_subtype - return whether the value has a subtype</li> <li>clear_subtype - clears the binary subtype</li> </ul>"},{"location":"api/byte_container_with_subtype/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0.</li> <li>Changed type of subtypes to <code>std::uint64_t</code> in 3.10.0.</li> </ul>"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/","title":"nlohmann::byte_container_with_subtype::byte_container_with_subtype","text":"<pre><code>// (1)\nbyte_container_with_subtype();\n\n// (2)\nbyte_container_with_subtype(const container_type& container);\nbyte_container_with_subtype(container_type&& container);\n\n// (3)\nbyte_container_with_subtype(const container_type& container, subtype_type subtype);\nbyte_container_with_subtype(container_type&& container, subtype_type subtype);\n</code></pre> <ol> <li>Create empty binary container without subtype.</li> <li>Create binary container without subtype.</li> <li>Create binary container with subtype.</li> </ol>"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#parameters","title":"Parameters","text":"<code>container</code> (in) binary container <code>subtype</code> (in) subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","title":"Examples","text":"Example <p>The example below demonstrates how byte containers can be created.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n // (1) create empty container\n auto c1 = byte_container_with_subtype();\n\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // (2) create container\n auto c2 = byte_container_with_subtype(bytes);\n\n // (3) create container with subtype\n auto c3 = byte_container_with_subtype(bytes, 42);\n\n std::cout << json(c1) << \"\\n\" << json(c2) << \"\\n\" << json(c3) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\"bytes\":[],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":42}\n</code></pre>"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","title":"Version history","text":"<p>Since version 3.8.0.</p>"},{"location":"api/byte_container_with_subtype/clear_subtype/","title":"nlohmann::byte_container_with_subtype::clear_subtype","text":"<pre><code>void clear_subtype() noexcept;\n</code></pre> <p>Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for instance MessagePack will prefer the bin family over the ext family.</p>"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","title":"Examples","text":"Example <p>The example below demonstrates how <code>clear_subtype</code> can remove subtypes.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container with subtype\n auto c1 = byte_container_with_subtype(bytes, 42);\n\n std::cout << \"before calling clear_subtype(): \" << json(c1) << '\\n';\n\n c1.clear_subtype();\n\n std::cout << \"after calling clear_subtype(): \" << json(c1) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>before calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":42}\nafter calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":null}\n</code></pre>"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","title":"Version history","text":"<p>Since version 3.8.0.</p>"},{"location":"api/byte_container_with_subtype/has_subtype/","title":"nlohmann::byte_container_with_subtype::has_subtype","text":"<pre><code>constexpr bool has_subtype() const noexcept;\n</code></pre> <p>Returns whether the value has a subtype.</p>"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","title":"Return value","text":"<p>whether the value has a subtype</p>"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","title":"Examples","text":"Example <p>The example below demonstrates how <code>has_subtype</code> can check whether a subtype was set.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container\n auto c1 = byte_container_with_subtype(bytes);\n\n // create container with subtype\n auto c2 = byte_container_with_subtype(bytes, 42);\n\n std::cout << std::boolalpha << \"c1.has_subtype() = \" << c1.has_subtype()\n << \"\\nc2.has_subtype() = \" << c2.has_subtype() << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>c1.has_subtype() = false\nc2.has_subtype() = true\n</code></pre>"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","title":"Version history","text":"<p>Since version 3.8.0.</p>"},{"location":"api/byte_container_with_subtype/set_subtype/","title":"nlohmann::byte_container_with_subtype::set_subtype","text":"<pre><code>void set_subtype(subtype_type subtype) noexcept;\n</code></pre> <p>Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.</p>"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","title":"Parameters","text":"<code>subtype</code> (in) subtype to set"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","title":"Examples","text":"Example <p>The example below demonstrates how a subtype can be set with <code>set_subtype</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container without subtype\n auto c = byte_container_with_subtype(bytes);\n\n std::cout << \"before calling set_subtype(42): \" << json(c) << '\\n';\n\n // set the subtype\n c.set_subtype(42);\n\n std::cout << \"after calling set_subtype(42): \" << json(c) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>before calling set_subtype(42): {\"bytes\":[202,254,186,190],\"subtype\":null}\nafter calling set_subtype(42): {\"bytes\":[202,254,186,190],\"subtype\":42}\n</code></pre>"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","title":"Version history","text":"<p>Since version 3.8.0.</p>"},{"location":"api/byte_container_with_subtype/subtype/","title":"nlohmann::byte_container_with_subtype::subtype","text":"<pre><code>constexpr subtype_type subtype() const noexcept;\n</code></pre> <p>Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return <code>subtype_type(-1)</code> as a sentinel value.</p>"},{"location":"api/byte_container_with_subtype/subtype/#return-value","title":"Return value","text":"<p>the numerical subtype of the binary value, or <code>subtype_type(-1)</code> if no subtype is set</p>"},{"location":"api/byte_container_with_subtype/subtype/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/byte_container_with_subtype/subtype/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/byte_container_with_subtype/subtype/#examples","title":"Examples","text":"Example <p>The example below demonstrates how the subtype can be retrieved with <code>subtype</code>. Note how <code>subtype_type(-1)</code> is returned for container <code>c1</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container\n auto c1 = byte_container_with_subtype(bytes);\n\n // create container with subtype\n auto c2 = byte_container_with_subtype(bytes, 42);\n\n std::cout << \"c1.subtype() = \" << c1.subtype()\n << \"\\nc2.subtype() = \" << c2.subtype() << std::endl;\n\n // in case no subtype is set, return special value\n assert(c1.subtype() == static_cast<byte_container_with_subtype::subtype_type>(-1));\n}\n</code></pre> <p>Output:</p> <pre><code>c1.subtype() = 18446744073709551615\nc2.subtype() = 42\n</code></pre>"},{"location":"api/byte_container_with_subtype/subtype/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0</li> <li>Fixed return value to properly return <code>subtype_type(-1)</code> as documented in version 3.10.0.</li> </ul>"},{"location":"api/json_pointer/","title":"nlohmann::json_pointer","text":"<pre><code>template<typename RefStringType>\nclass json_pointer;\n</code></pre> <p>A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions <code>at</code> and <code>operator[]</code>. Furthermore, JSON pointers are the base for JSON patches.</p>"},{"location":"api/json_pointer/#template-parameters","title":"Template parameters","text":"<code>RefStringType</code> the string type used for the reference tokens making up the JSON pointer <p>Deprecation</p> <p>For backwards compatibility <code>RefStringType</code> may also be a specialization of <code>basic_json</code> in which case <code>string_t</code> will be deduced as <code>basic_json::string_t</code>. This feature is deprecated and may be removed in a future major version.</p>"},{"location":"api/json_pointer/#member-types","title":"Member types","text":"<ul> <li>string_t - the string type used for the reference tokens</li> </ul>"},{"location":"api/json_pointer/#member-functions","title":"Member functions","text":"<ul> <li>(constructor)</li> <li>to_string - return a string representation of the JSON pointer</li> <li>operator string_t - return a string representation of the JSON pointer</li> <li>operator== - compare: equal</li> <li>operator!= - compare: not equal</li> <li>operator/= - append to the end of the JSON pointer</li> <li>operator/ - create JSON Pointer by appending</li> <li>parent_pointer - returns the parent of this JSON pointer</li> <li>pop_back - remove last reference token</li> <li>back - return last reference token</li> <li>push_back - append an unescaped token at the end of the pointer</li> <li>empty - return whether pointer points to the root document</li> </ul>"},{"location":"api/json_pointer/#literals","title":"Literals","text":"<ul> <li>operator\"\"_json_pointer - user-defined string literal for JSON pointers</li> </ul>"},{"location":"api/json_pointer/#see-also","title":"See also","text":"<ul> <li>RFC 6901</li> </ul>"},{"location":"api/json_pointer/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> <li>Changed template parameter from <code>basic_json</code> to string type in version 3.11.0.</li> </ul>"},{"location":"api/json_pointer/back/","title":"nlohmann::json_pointer::back","text":"<pre><code>const string_t& back() const;\n</code></pre> <p>Return last reference token.</p>"},{"location":"api/json_pointer/back/#return-value","title":"Return value","text":"<p>Last reference token.</p>"},{"location":"api/json_pointer/back/#exceptions","title":"Exceptions","text":"<p>Throws out_of_range.405 if JSON pointer has no parent.</p>"},{"location":"api/json_pointer/back/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/json_pointer/back/#examples","title":"Examples","text":"Example <p>The example shows the usage of <code>back</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo\");\n json::json_pointer ptr2(\"/foo/0\");\n\n // call empty()\n std::cout << \"last reference token of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.back() << \"\\\"\\n\"\n << \"last reference token of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.back() << \"\\\"\" << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>last reference token of \"/foo\" is \"foo\"\nlast reference token of \"/foo/0\" is \"0\"\n</code></pre>"},{"location":"api/json_pointer/back/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.6.0.</li> <li>Changed return type to <code>string_t</code> in version 3.11.0.</li> </ul>"},{"location":"api/json_pointer/empty/","title":"nlohmann::json_pointer::empty","text":"<pre><code>bool empty() const noexcept;\n</code></pre> <p>Return whether pointer points to the root document.</p>"},{"location":"api/json_pointer/empty/#return-value","title":"Return value","text":"<p><code>true</code> iff the JSON pointer points to the root document.</p>"},{"location":"api/json_pointer/empty/#exception-safety","title":"Exception safety","text":"<p>No-throw guarantee: this function never throws exceptions.</p>"},{"location":"api/json_pointer/empty/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/json_pointer/empty/#examples","title":"Examples","text":"Example <p>The example shows the result of <code>empty</code> for different JSON Pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n\n // call empty()\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\": \" << ptr0.empty() << '\\n'\n << \"\\\"\" << ptr1 << \"\\\": \" << ptr1.empty() << '\\n'\n << \"\\\"\" << ptr2 << \"\\\": \" << ptr2.empty() << '\\n'\n << \"\\\"\" << ptr3 << \"\\\": \" << ptr3.empty() << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"\": true\n\"\": true\n\"/foo\": false\n\"/foo/0\": false\n</code></pre>"},{"location":"api/json_pointer/empty/#version-history","title":"Version history","text":"<p>Added in version 3.6.0.</p>"},{"location":"api/json_pointer/json_pointer/","title":"nlohmann::json_pointer::json_pointer","text":"<pre><code>explicit json_pointer(const string_t& s = \"\");\n</code></pre> <p>Create a JSON pointer according to the syntax described in Section 3 of RFC6901.</p>"},{"location":"api/json_pointer/json_pointer/#parameters","title":"Parameters","text":"<code>s</code> (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value"},{"location":"api/json_pointer/json_pointer/#exceptions","title":"Exceptions","text":"<ul> <li>Throws parse_error.107 if the given JSON pointer <code>s</code> is nonempty and does not begin with a slash (<code>/</code>); see example below.</li> <li>Throws parse_error.108 if a tilde (<code>~</code>) in the given JSON pointer <code>s</code> is not followed by <code>0</code> (representing <code>~</code>) or <code>1</code> (representing <code>/</code>); see example below.</li> </ul>"},{"location":"api/json_pointer/json_pointer/#examples","title":"Examples","text":"Example <p>The example shows the construction several valid JSON pointers as well as the exceptional behavior.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // correct JSON pointers\n json::json_pointer p1;\n json::json_pointer p2(\"\");\n json::json_pointer p3(\"/\");\n json::json_pointer p4(\"//\");\n json::json_pointer p5(\"/foo/bar\");\n json::json_pointer p6(\"/foo/bar/-\");\n json::json_pointer p7(\"/foo/~0\");\n json::json_pointer p8(\"/foo/~1\");\n\n // error: JSON pointer does not begin with a slash\n try\n {\n json::json_pointer p9(\"foo\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // error: JSON pointer uses escape symbol ~ not followed by 0 or 1\n try\n {\n json::json_pointer p10(\"/foo/~\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // error: JSON pointer uses escape symbol ~ not followed by 0 or 1\n try\n {\n json::json_pointer p11(\"/foo/~3\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n</code></pre>"},{"location":"api/json_pointer/json_pointer/#version-history","title":"Version history","text":"<ul> <li>Added in version 2.0.0.</li> <li>Changed type of <code>s</code> to <code>string_t</code> in version 3.11.0.</li> </ul>"},{"location":"api/json_pointer/operator_eq/","title":"nlohmann::json_pointer::operator==","text":"<pre><code>// until C++20\ntemplate<typename RefStringTypeLhs, typename RefStringTypeRhs>\nbool operator==(\n const json_pointer<RefStringTypeLhs>& lhs,\n const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)\n\ntemplate<typename RefStringTypeLhs, typename StringType>\nbool operator==(\n const json_pointer<RefStringTypeLhs>& lhs,\n const StringType& rhs); // (2)\n\ntemplate<typename RefStringTypeRhs, typename StringType>\nbool operator==(\n const StringType& lhs,\n const json_pointer<RefStringTypeRhs>& rhs); // (2)\n\n// since C++20\nclass json_pointer {\n template<typename RefStringTypeRhs>\n bool operator==(\n const json_pointer<RefStringTypeRhs>& rhs) const noexcept; // (1)\n\n bool operator==(const string_t& rhs) const; // (2)\n};\n</code></pre> <ol> <li> <p>Compares two JSON pointers for equality by comparing their reference tokens.</p> </li> <li> <p>Compares a JSON pointer and a string or a string and a JSON pointer for equality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.</p> </li> </ol>"},{"location":"api/json_pointer/operator_eq/#template-parameters","title":"Template parameters","text":"<code>RefStringTypeLhs</code>, <code>RefStringTypeRhs</code> the string type of the left-hand side or right-hand side JSON pointer, respectively <code>StringType</code> the string type derived from the <code>json_pointer</code> operand (<code>json_pointer::string_t</code>)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"<p>whether the values <code>lhs</code>/<code>*this</code> and <code>rhs</code> are equal</p>"},{"location":"api/json_pointer/operator_eq/#exception-safety","title":"Exception safety","text":"<ol> <li>No-throw guarantee: this function never throws exceptions.</li> <li>Strong exception safety: if an exception occurs, the original value stays intact.</li> </ol>"},{"location":"api/json_pointer/operator_eq/#exceptions","title":"Exceptions","text":"<ol> <li>(none)</li> <li>The function can throw the following exceptions:</li> <li>Throws parse_error.107 if the given JSON pointer <code>s</code> is nonempty and does not begin with a slash (<code>/</code>); see example below.</li> <li>Throws parse_error.108 if a tilde (<code>~</code>) in the given JSON pointer <code>s</code> is not followed by <code>0</code> (representing <code>~</code>) or <code>1</code> (representing <code>/</code>); see example below.</li> </ol>"},{"location":"api/json_pointer/operator_eq/#complexity","title":"Complexity","text":"<p>Constant if <code>lhs</code> and <code>rhs</code> differ in the number of reference tokens, otherwise linear in the number of reference tokens.</p>"},{"location":"api/json_pointer/operator_eq/#notes","title":"Notes","text":"<p>Deprecation</p> <p>Overload 2 is deprecated and will be removed in a future major version release.</p>"},{"location":"api/json_pointer/operator_eq/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointers <p>The example demonstrates comparing JSON pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // compare JSON pointers\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << ptr0 << \"\\\": \" << (ptr0 == ptr0) << '\\n'\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << ptr1 << \"\\\": \" << (ptr0 == ptr1) << '\\n'\n << \"\\\"\" << ptr1 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (ptr1 == ptr2) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (ptr2 == ptr2) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"\" == \"\": true\n\"\" == \"\": true\n\"\" == \"/foo\": false\n\"/foo\" == \"/foo\": true\n</code></pre> Example: (2) Comparing JSON pointers and strings <p>The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.</p> <pre><code>#include <exception>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // different strings\n std::string str0(\"\");\n std::string str1(\"/foo\");\n std::string str2(\"bar\");\n\n // compare JSON pointers and strings\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << str0 << \"\\\": \" << (ptr0 == str0) << '\\n'\n << \"\\\"\" << str0 << \"\\\" == \\\"\" << ptr1 << \"\\\": \" << (str0 == ptr1) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" == \\\"\" << str1 << \"\\\": \" << (ptr2 == str1) << std::endl;\n\n try\n {\n std::cout << \"\\\"\" << str2 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (str2 == ptr2) << std::endl;\n }\n catch (const json::parse_error& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"\" == \"\": true\n\"\" == \"\": true\n\"/foo\" == \"/foo\": true\n\"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'\n</code></pre>"},{"location":"api/json_pointer/operator_eq/#version-history","title":"Version history","text":"<ol> <li>Added in version 2.1.0. Added C++20 member functions in version 3.11.2.</li> <li>Added for backward compatibility and deprecated in version 3.11.2.</li> </ol>"},{"location":"api/json_pointer/operator_ne/","title":"nlohmann::json_pointer::operator!=","text":"<pre><code>// until C++20\ntemplate<typename RefStringTypeLhs, typename RefStringTypeRhs>\nbool operator!=(\n const json_pointer<RefStringTypeLhs>& lhs,\n const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)\n\ntemplate<typename RefStringTypeLhs, typename StringType>\nbool operator!=(\n const json_pointer<RefStringTypeLhs>& lhs,\n const StringType& rhs); // (2)\n\ntemplate<typename RefStringTypeRhs, typename StringType>\nbool operator!=(\n const StringType& lhs,\n const json_pointer<RefStringTypeRhs>& rhs); // (2)\n</code></pre> <ol> <li> <p>Compares two JSON pointers for inequality by comparing their reference tokens.</p> </li> <li> <p>Compares a JSON pointer and a string or a string and a JSON pointer for inequality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.</p> </li> </ol>"},{"location":"api/json_pointer/operator_ne/#template-parameters","title":"Template parameters","text":"<code>RefStringTypeLhs</code>, <code>RefStringTypeRhs</code> the string type of the left-hand side or right-hand side JSON pointer, respectively <code>StringType</code> the string type derived from the <code>json_pointer</code> operand (<code>json_pointer::string_t</code>)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"<code>lhs</code> (in) first value to consider <code>rhs</code> (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"<p>whether the values <code>lhs</code>/<code>*this</code> and <code>rhs</code> are not equal</p>"},{"location":"api/json_pointer/operator_ne/#exception-safety","title":"Exception safety","text":"<ol> <li>No-throw guarantee: this function never throws exceptions.</li> <li>Strong exception safety: if an exception occurs, the original value stays intact.</li> </ol>"},{"location":"api/json_pointer/operator_ne/#exceptions","title":"Exceptions","text":"<ol> <li>(none)</li> <li>The function can throw the following exceptions:</li> <li>Throws parse_error.107 if the given JSON pointer <code>s</code> is nonempty and does not begin with a slash (<code>/</code>); see example below.</li> <li>Throws parse_error.108 if a tilde (<code>~</code>) in the given JSON pointer <code>s</code> is not followed by <code>0</code> (representing <code>~</code>) or <code>1</code> (representing <code>/</code>); see example below.</li> </ol>"},{"location":"api/json_pointer/operator_ne/#complexity","title":"Complexity","text":"<p>Constant if <code>lhs</code> and <code>rhs</code> differ in the number of reference tokens, otherwise linear in the number of reference tokens.</p>"},{"location":"api/json_pointer/operator_ne/#notes","title":"Notes","text":"<p>Operator overload resolution</p> <p>Since C++20 overload resolution will consider the rewritten candidate generated from <code>operator==</code>.</p> <p>Deprecation</p> <p>Overload 2 is deprecated and will be removed in a future major version release.</p>"},{"location":"api/json_pointer/operator_ne/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointers <p>The example demonstrates comparing JSON pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // compare JSON pointers\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << ptr0 << \"\\\": \" << (ptr0 != ptr0) << '\\n'\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << ptr1 << \"\\\": \" << (ptr0 != ptr1) << '\\n'\n << \"\\\"\" << ptr1 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (ptr1 != ptr2) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (ptr2 != ptr2) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"\" != \"\": false\n\"\" != \"\": false\n\"\" != \"/foo\": true\n\"/foo\" != \"/foo\": false\n</code></pre> Example: (2) Comparing JSON pointers and strings <p>The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // different strings\n std::string str0(\"\");\n std::string str1(\"/foo\");\n std::string str2(\"bar\");\n\n // compare JSON pointers and strings\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << str0 << \"\\\": \" << (ptr0 != str0) << '\\n'\n << \"\\\"\" << str0 << \"\\\" != \\\"\" << ptr1 << \"\\\": \" << (str0 != ptr1) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" != \\\"\" << str1 << \"\\\": \" << (ptr2 != str1) << std::endl;\n\n try\n {\n std::cout << \"\\\"\" << str2 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (str2 != ptr2) << std::endl;\n }\n catch (const json::parse_error& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>\"\" != \"\": false\n\"\" != \"\": false\n\"/foo\" != \"/foo\": false\n\"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'\n</code></pre>"},{"location":"api/json_pointer/operator_ne/#version-history","title":"Version history","text":"<ol> <li>Added in version 2.1.0.</li> <li>Added for backward compatibility and deprecated in version 3.11.2.</li> </ol>"},{"location":"api/json_pointer/operator_slash/","title":"nlohmann::json_pointer::operator/","text":"<pre><code>// (1)\njson_pointer operator/(const json_pointer& lhs, const json_pointer& rhs);\n\n// (2)\njson_pointer operator/(const json_pointer& lhs, string_t token);\n\n// (3)\njson_pointer operator/(const json_pointer& lhs, std::size_t array_idx);\n</code></pre> <ol> <li>create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer</li> <li>create a new JSON pointer by appending the unescaped token at the end of the JSON pointer</li> <li>create a new JSON pointer by appending the array-index-token at the end of the JSON pointer</li> </ol>"},{"location":"api/json_pointer/operator_slash/#parameters","title":"Parameters","text":"<code>lhs</code> (in) JSON pointer <code>rhs</code> (in) JSON pointer to append <code>token</code> (in) reference token to append <code>array_idx</code> (in) array index to append"},{"location":"api/json_pointer/operator_slash/#return-value","title":"Return value","text":"<ol> <li>a new JSON pointer with <code>rhs</code> appended to <code>lhs</code></li> <li>a new JSON pointer with unescaped <code>token</code> appended to <code>lhs</code></li> <li>a new JSON pointer with <code>array_idx</code> appended to <code>lhs</code></li> </ol>"},{"location":"api/json_pointer/operator_slash/#complexity","title":"Complexity","text":"<ol> <li>Linear in the length of <code>lhs</code> and <code>rhs</code>.</li> <li>Linear in the length of <code>lhs</code>.</li> <li>Linear in the length of <code>lhs</code>.</li> </ol>"},{"location":"api/json_pointer/operator_slash/#examples","title":"Examples","text":"Example <p>The example shows the usage of <code>operator/</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON pointer\n json::json_pointer ptr(\"/foo\");\n\n // append a JSON Pointer\n std::cout << \"\\\"\" << ptr / json::json_pointer(\"/bar/baz\") << \"\\\"\\n\";\n\n // append a string\n std::cout << \"\\\"\" << ptr / \"fob\" << \"\\\"\\n\";\n\n // append an array index\n std::cout << \"\\\"\" << ptr / 42 << \"\\\"\" << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"/foo/bar/baz\"\n\"/foo/fob\"\n\"/foo/42\"\n</code></pre>"},{"location":"api/json_pointer/operator_slash/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.6.0.</li> <li>Added in version 3.6.0. Changed type of <code>token</code> to <code>string_t</code> in version 3.11.0.</li> <li>Added in version 3.6.0.</li> </ol>"},{"location":"api/json_pointer/operator_slasheq/","title":"nlohmann::json_pointer::operator/=","text":"<pre><code>// (1)\njson_pointer& operator/=(const json_pointer& ptr);\n\n// (2)\njson_pointer& operator/=(string_t token);\n\n// (3)\njson_pointer& operator/=(std::size_t array_idx)\n</code></pre> <ol> <li>append another JSON pointer at the end of this JSON pointer</li> <li>append an unescaped reference token at the end of this JSON pointer</li> <li>append an array index at the end of this JSON pointer</li> </ol>"},{"location":"api/json_pointer/operator_slasheq/#parameters","title":"Parameters","text":"<code>ptr</code> (in) JSON pointer to append <code>token</code> (in) reference token to append <code>array_idx</code> (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"<ol> <li>JSON pointer with <code>ptr</code> appended</li> <li>JSON pointer with <code>token</code> appended without escaping <code>token</code></li> <li>JSON pointer with <code>array_idx</code> appended</li> </ol>"},{"location":"api/json_pointer/operator_slasheq/#complexity","title":"Complexity","text":"<ol> <li>Linear in the length of <code>ptr</code>.</li> <li>Amortized constant.</li> <li>Amortized constant.</li> </ol>"},{"location":"api/json_pointer/operator_slasheq/#examples","title":"Examples","text":"Example <p>The example shows the usage of <code>operator/=</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON pointer\n json::json_pointer ptr(\"/foo\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append a JSON Pointer\n ptr /= json::json_pointer(\"/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append a string\n ptr /= \"fob\";\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append an array index\n ptr /= 42;\n std::cout << \"\\\"\" << ptr << \"\\\"\" << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"/foo\"\n\"/foo/bar/baz\"\n\"/foo/bar/baz/fob\"\n\"/foo/bar/baz/fob/42\"\n</code></pre>"},{"location":"api/json_pointer/operator_slasheq/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.6.0.</li> <li>Added in version 3.6.0. Changed type of <code>token</code> to <code>string_t</code> in version 3.11.0.</li> <li>Added in version 3.6.0.</li> </ol>"},{"location":"api/json_pointer/operator_string_t/","title":"nlohmann::json_pointer::operator string_t","text":"<pre><code>operator string_t() const\n</code></pre> <p>Return a string representation of the JSON pointer.</p>"},{"location":"api/json_pointer/operator_string_t/#return-value","title":"Return value","text":"<p>A string representation of the JSON pointer</p>"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","title":"Possible implementation","text":"<pre><code>operator string_t() const\n{\n return to_string();\n}\n</code></pre>"},{"location":"api/json_pointer/operator_string_t/#notes","title":"Notes","text":"<p>Deprecation</p> <p>This function is deprecated in favor of <code>to_string</code> and will be removed in a future major version release.</p>"},{"location":"api/json_pointer/operator_string_t/#examples","title":"Examples","text":"Example <p>The example shows how JSON Pointers can be implicitly converted to strings.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo/0\");\n json::json_pointer ptr2(\"/a~1b\");\n\n // implicit conversion to string\n std::string s;\n s += ptr1;\n s += \"\\n\";\n s += ptr2;\n\n std::cout << s << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>/foo/0\n/a~1b\n</code></pre>"},{"location":"api/json_pointer/operator_string_t/#version-history","title":"Version history","text":"<ul> <li>Since version 2.0.0.</li> <li>Changed type to <code>string_t</code> and deprecated in version 3.11.0.</li> </ul>"},{"location":"api/json_pointer/parent_pointer/","title":"nlohmann::json_pointer::parent_pointer","text":"<pre><code>json_pointer parent_pointer() const;\n</code></pre> <p>Returns the parent of this JSON pointer.</p>"},{"location":"api/json_pointer/parent_pointer/#return-value","title":"Return value","text":"<p>Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.</p>"},{"location":"api/json_pointer/parent_pointer/#complexity","title":"Complexity","text":"<p>Linear in the length of the JSON pointer.</p>"},{"location":"api/json_pointer/parent_pointer/#examples","title":"Examples","text":"Example <p>The example shows the result of <code>parent_pointer</code> for different JSON Pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n\n // call parent_pointer()\n std::cout << std::boolalpha\n << \"parent of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.parent_pointer() << \"\\\"\\n\"\n << \"parent of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.parent_pointer() << \"\\\"\\n\"\n << \"parent of \\\"\" << ptr3 << \"\\\" is \\\"\" << ptr3.parent_pointer() << \"\\\"\" << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>parent of \"\" is \"\"\nparent of \"/foo\" is \"\"\nparent of \"/foo/0\" is \"/foo\"\n</code></pre>"},{"location":"api/json_pointer/parent_pointer/#version-history","title":"Version history","text":"<p>Added in version 3.6.0.</p>"},{"location":"api/json_pointer/pop_back/","title":"nlohmann::json_pointer::pop_back","text":"<pre><code>void pop_back();\n</code></pre> <p>Remove last reference token.</p>"},{"location":"api/json_pointer/pop_back/#exceptions","title":"Exceptions","text":"<p>Throws out_of_range.405 if JSON pointer has no parent.</p>"},{"location":"api/json_pointer/pop_back/#complexity","title":"Complexity","text":"<p>Constant.</p>"},{"location":"api/json_pointer/pop_back/#examples","title":"Examples","text":"Example <p>The example shows the usage of <code>pop_back</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr(\"/foo/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call pop_back()\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>\"/foo/bar/baz\"\n\"/foo/bar\"\n\"/foo\"\n\"\"\n</code></pre>"},{"location":"api/json_pointer/pop_back/#version-history","title":"Version history","text":"<p>Added in version 3.6.0.</p>"},{"location":"api/json_pointer/push_back/","title":"nlohmann::json_pointer::push_back","text":"<pre><code>void push_back(const string_t& token);\n\nvoid push_back(string_t&& token);\n</code></pre> <p>Append an unescaped token at the end of the reference pointer.</p>"},{"location":"api/json_pointer/push_back/#parameters","title":"Parameters","text":"<code>token</code> (in) token to add"},{"location":"api/json_pointer/push_back/#complexity","title":"Complexity","text":"<p>Amortized constant.</p>"},{"location":"api/json_pointer/push_back/#examples","title":"Examples","text":"Example <p>The example shows the result of <code>push_back</code> for different JSON Pointers.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr;\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call push_back()\n ptr.push_back(\"foo\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.push_back(\"0\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.push_back(\"bar\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}\n</code></pre> <p>Output:</p> <pre><code>\"\"\n\"/foo\"\n\"/foo/0\"\n\"/foo/0/bar\"\n</code></pre>"},{"location":"api/json_pointer/push_back/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.6.0.</li> <li>Changed type of <code>token</code> to <code>string_t</code> in version 3.11.0.</li> </ul>"},{"location":"api/json_pointer/string_t/","title":"nlohmann::json_pointer::string_t","text":"<pre><code>using string_t = RefStringType;\n</code></pre> <p>The string type used for the reference tokens making up the JSON pointer.</p> <p>See <code>basic_json::string_t</code> for more information.</p>"},{"location":"api/json_pointer/string_t/#examples","title":"Examples","text":"Example <p>The example shows the type <code>string_t</code> and its relation to <code>basic_json::string_t</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::json_pointer::string_t s = \"This is a string.\";\n\n std::cout << s << std::endl;\n\n std::cout << std::boolalpha << std::is_same<json::json_pointer::string_t, json::string_t>::value << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>This is a string.\ntrue\n</code></pre>"},{"location":"api/json_pointer/string_t/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/json_pointer/to_string/","title":"nlohmann::json_pointer::to_string","text":"<pre><code>string_t to_string() const;\n</code></pre> <p>Return a string representation of the JSON pointer.</p>"},{"location":"api/json_pointer/to_string/#return-value","title":"Return value","text":"<p>A string representation of the JSON pointer</p>"},{"location":"api/json_pointer/to_string/#notes","title":"Notes","text":"<p>For each JSON pointer <code>ptr</code>, it holds:</p> <pre><code>ptr == json_pointer(ptr.to_string());\n</code></pre>"},{"location":"api/json_pointer/to_string/#examples","title":"Examples","text":"Example <p>The example shows the result of <code>to_string</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n json::json_pointer ptr4(\"/\");\n json::json_pointer ptr5(\"/a~1b\");\n json::json_pointer ptr6(\"/c%d\");\n json::json_pointer ptr7(\"/e^f\");\n json::json_pointer ptr8(\"/g|h\");\n json::json_pointer ptr9(\"/i\\\\j\");\n json::json_pointer ptr10(\"/k\\\"l\");\n json::json_pointer ptr11(\"/ \");\n json::json_pointer ptr12(\"/m~0n\");\n\n std::cout << \"\\\"\" << ptr1.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr2.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr3.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr4.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr5.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr6.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr7.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr8.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr9.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr10.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr11.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr12.to_string() << \"\\\"\" << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"\"\n\"/foo\"\n\"/foo/0\"\n\"/\"\n\"/a~1b\"\n\"/c%d\"\n\"/e^f\"\n\"/g|h\"\n\"/i\\j\"\n\"/k\"l\"\n\"/ \"\n\"/m~0n\"\n</code></pre>"},{"location":"api/json_pointer/to_string/#version-history","title":"Version history","text":"<ul> <li>Since version 2.0.0.</li> <li>Changed return type to <code>string_t</code> in version 3.11.0.</li> </ul>"},{"location":"api/json_sax/","title":"nlohmann::json_sax","text":"<pre><code>template<typename BasicJsonType>\nstruct json_sax;\n</code></pre> <p>This class describes the SAX interface used by sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input.</p>"},{"location":"api/json_sax/#template-parameters","title":"Template parameters","text":"<code>BasicJsonType</code> a specialization of <code>basic_json</code>"},{"location":"api/json_sax/#member-types","title":"Member types","text":"<ul> <li>number_integer_t - <code>BasicJsonType</code>'s type for numbers (integer)</li> <li>number_unsigned_t - <code>BasicJsonType</code>'s type for numbers (unsigned)</li> <li>number_float_t - <code>BasicJsonType</code>'s type for numbers (floating-point)</li> <li>string_t - <code>BasicJsonType</code>'s type for strings</li> <li>binary_t - <code>BasicJsonType</code>'s type for binary arrays</li> </ul>"},{"location":"api/json_sax/#member-functions","title":"Member functions","text":"<ul> <li>binary (virtual) - a binary value was read</li> <li>boolean (virtual) - a boolean value was read</li> <li>end_array (virtual) - the end of an array was read</li> <li>end_object (virtual) - the end of an object was read</li> <li>key (virtual) - an object key was read</li> <li>null (virtual) - a null value was read</li> <li>number_float (virtual) - a floating-point number was read</li> <li>number_integer (virtual) - an integer number was read</li> <li>number_unsigned (virtual) - an unsigned integer number was read</li> <li>parse_error (virtual) - a parse error occurred</li> <li>start_array (virtual) - the beginning of an array was read</li> <li>start_object (virtual) - the beginning of an object was read</li> <li>string (virtual) - a string value was read</li> </ul>"},{"location":"api/json_sax/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> <li>Support for binary values (<code>binary_t</code>, <code>binary</code>) added in version 3.8.0.</li> </ul>"},{"location":"api/json_sax/binary/","title":"nlohmann::json_sax::binary","text":"<pre><code>virtual bool binary(binary_t& val) = 0;\n</code></pre> <p>A binary value was read.</p>"},{"location":"api/json_sax/binary/#parameters","title":"Parameters","text":"<code>val</code> (in) binary value"},{"location":"api/json_sax/binary/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/binary/#notes","title":"Notes","text":"<p>It is safe to move the passed binary value.</p>"},{"location":"api/json_sax/binary/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // CBOR byte string\n std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse CBOR\n bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>binary(val=[...])\n\nresult: true\n</code></pre>"},{"location":"api/json_sax/binary/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.8.0.</li> </ul>"},{"location":"api/json_sax/boolean/","title":"nlohmann::json_sax::boolean","text":"<pre><code>virtual bool boolean(bool val) = 0;\n</code></pre> <p>A boolean value was read.</p>"},{"location":"api/json_sax/boolean/#parameters","title":"Parameters","text":"<code>val</code> (in) boolean value"},{"location":"api/json_sax/boolean/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/boolean/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/boolean/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/end_array/","title":"nlohmann::json_sax::end_array","text":"<pre><code>virtual bool end_array() = 0;\n</code></pre> <p>The end of an array was read.</p>"},{"location":"api/json_sax/end_array/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/end_array/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/end_array/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/end_object/","title":"nlohmann::json_sax::end_object","text":"<pre><code>virtual bool end_object() = 0;\n</code></pre> <p>The end of an object was read.</p>"},{"location":"api/json_sax/end_object/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/end_object/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/end_object/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/key/","title":"nlohmann::json_sax::key","text":"<pre><code>virtual bool key(string_t& val) = 0;\n</code></pre> <p>An object key was read.</p>"},{"location":"api/json_sax/key/#parameters","title":"Parameters","text":"<code>val</code> (in) object key"},{"location":"api/json_sax/key/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/key/#notes","title":"Notes","text":"<p>It is safe to move the passed object key value.</p>"},{"location":"api/json_sax/key/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/key/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/null/","title":"nlohmann::json_sax::null","text":"<pre><code>virtual bool null() = 0;\n</code></pre> <p>A null value was read.</p>"},{"location":"api/json_sax/null/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/null/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/null/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/number_float/","title":"nlohmann::json_sax::number_float","text":"<pre><code>virtual bool number_float(number_float_t val, const string_t& s) = 0;\n</code></pre> <p>A floating-point number was read.</p>"},{"location":"api/json_sax/number_float/#parameters","title":"Parameters","text":"<code>val</code> (in) floating-point value <code>s</code> (in) string representation of the original input"},{"location":"api/json_sax/number_float/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/number_float/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/number_float/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/number_integer/","title":"nlohmann::json_sax::number_integer","text":"<pre><code>virtual bool number_integer(number_integer_t val) = 0;\n</code></pre> <p>An integer number was read.</p>"},{"location":"api/json_sax/number_integer/#parameters","title":"Parameters","text":"<code>val</code> (in) integer value"},{"location":"api/json_sax/number_integer/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/number_integer/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/number_integer/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/number_unsigned/","title":"nlohmann::json_sax::number_unsigned","text":"<pre><code>virtual bool number_unsigned(number_unsigned_t val) = 0;\n</code></pre> <p>An unsigned integer number was read.</p>"},{"location":"api/json_sax/number_unsigned/#parameters","title":"Parameters","text":"<code>val</code> (in) unsigned integer value"},{"location":"api/json_sax/number_unsigned/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/number_unsigned/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/number_unsigned/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/parse_error/","title":"nlohmann::json_sax::parse_error","text":"<pre><code>virtual bool parse_error(std::size_t position,\n const std::string& last_token,\n const detail::exception& ex) = 0;\n</code></pre> <p>A parse error occurred.</p>"},{"location":"api/json_sax/parse_error/#parameters","title":"Parameters","text":"<code>position</code> (in) the position in the input where the error occurs <code>last_token</code> (in) the last read token <code>ex</code> (in) an exception object describing the error"},{"location":"api/json_sax/parse_error/#return-value","title":"Return value","text":"<p>Whether parsing should proceed (must return <code>false</code>).</p>"},{"location":"api/json_sax/parse_error/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/parse_error/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/start_array/","title":"nlohmann::json_sax::start_array","text":"<pre><code>virtual bool start_array(std::size_t elements) = 0;\n</code></pre> <p>The beginning of an array was read.</p>"},{"location":"api/json_sax/start_array/#parameters","title":"Parameters","text":"<code>elements</code> (in) number of object elements or <code>-1</code> if unknown"},{"location":"api/json_sax/start_array/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/start_array/#notes","title":"Notes","text":"<p>Binary formats may report the number of elements.</p>"},{"location":"api/json_sax/start_array/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/start_array/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/start_object/","title":"nlohmann::json_sax::start_object","text":"<pre><code>virtual bool start_object(std::size_t elements) = 0;\n</code></pre> <p>The beginning of an object was read.</p>"},{"location":"api/json_sax/start_object/#parameters","title":"Parameters","text":"<code>elements</code> (in) number of object elements or <code>-1</code> if unknown"},{"location":"api/json_sax/start_object/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/start_object/#notes","title":"Notes","text":"<p>Binary formats may report the number of elements.</p>"},{"location":"api/json_sax/start_object/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/start_object/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/json_sax/string/","title":"nlohmann::json_sax::string","text":"<pre><code>virtual bool string(string_t& val) = 0;\n</code></pre> <p>A string value was read.</p>"},{"location":"api/json_sax/string/#parameters","title":"Parameters","text":"<code>val</code> (in) string value"},{"location":"api/json_sax/string/#return-value","title":"Return value","text":"<p>Whether parsing should proceed.</p>"},{"location":"api/json_sax/string/#notes","title":"Notes","text":"<p>It is safe to move the passed string value.</p>"},{"location":"api/json_sax/string/#examples","title":"Examples","text":"Example <p>The example below shows how the SAX interface is used.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n</code></pre>"},{"location":"api/json_sax/string/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.2.0.</li> </ul>"},{"location":"api/macros/","title":"Macros","text":"<p>Some aspects of the library can be configured by defining preprocessor macros before including the <code>json.hpp</code> header. See also the macro overview page.</p>"},{"location":"api/macros/#runtime-assertions","title":"Runtime assertions","text":"<ul> <li>JSON_ASSERT(x) - control behavior of runtime assertions</li> </ul>"},{"location":"api/macros/#exceptions","title":"Exceptions","text":"<ul> <li>JSON_CATCH_USER(exception)JSON_THROW_USER(exception)JSON_TRY_USER - control exceptions</li> <li>JSON_DIAGNOSTICS - control extended diagnostics</li> <li>JSON_NOEXCEPTION - switch off exceptions</li> </ul>"},{"location":"api/macros/#language-support","title":"Language support","text":"<ul> <li>JSON_HAS_CPP_11JSON_HAS_CPP_14JSON_HAS_CPP_17JSON_HAS_CPP_20 - set supported C++ standard</li> <li>JSON_HAS_FILESYSTEMJSON_HAS_EXPERIMENTAL_FILESYSTEM - control <code>std::filesystem</code> support</li> <li>JSON_HAS_RANGES - control <code>std::ranges</code> support</li> <li>JSON_HAS_THREE_WAY_COMPARISON - control 3-way comparison support</li> <li>JSON_NO_IO - switch off functions relying on certain C++ I/O headers</li> <li>JSON_SKIP_UNSUPPORTED_COMPILER_CHECK - do not warn about unsupported compilers</li> <li>JSON_USE_GLOBAL_UDLS - place user-defined string literals (UDLs) into the global namespace</li> </ul>"},{"location":"api/macros/#library-version","title":"Library version","text":"<ul> <li>JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check</li> <li>NLOHMANN_JSON_VERSION_MAJORNLOHMANN_JSON_VERSION_MINORNLOHMANN_JSON_VERSION_PATCH - library version information</li> </ul>"},{"location":"api/macros/#library-namespace","title":"Library namespace","text":"<ul> <li>NLOHMANN_JSON_NAMESPACE - full name of the <code>nlohmann</code> namespace</li> <li>NLOHMANN_JSON_NAMESPACE_BEGINNLOHMANN_JSON_NAMESPACE_END - open and close the library namespace</li> <li>NLOHMANN_JSON_NAMESPACE_NO_VERSION - disable the version component of the inline namespace</li> </ul>"},{"location":"api/macros/#type-conversions","title":"Type conversions","text":"<ul> <li>JSON_DISABLE_ENUM_SERIALIZATION - switch off default serialization/deserialization functions for enums</li> <li>JSON_USE_IMPLICIT_CONVERSIONS - control implicit conversions</li> </ul>"},{"location":"api/macros/#comparison-behavior","title":"Comparison behavior","text":"<ul> <li>JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - control comparison of discarded values</li> </ul>"},{"location":"api/macros/#serializationdeserialization-macros","title":"Serialization/deserialization macros","text":"<ul> <li>NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) - serialization/deserialization of types with access to private variables</li> <li>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...) - serialization/deserialization of types without access to private variables</li> <li>NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) - serialization/deserialization of enum types</li> </ul>"},{"location":"api/macros/json_assert/","title":"JSON_ASSERT","text":"<pre><code>#define JSON_ASSERT(x) /* value */\n</code></pre> <p>This macro controls which code is executed for runtime assertions of the library.</p>"},{"location":"api/macros/json_assert/#parameters","title":"Parameters","text":"<code>x</code> (in) expression of scalar type"},{"location":"api/macros/json_assert/#default-definition","title":"Default definition","text":"<p>The default value is <code>assert(x)</code>.</p> <pre><code>#define JSON_ASSERT(x) assert(x)\n</code></pre> <p>Therefore, assertions can be switched off by defining <code>NDEBUG</code>.</p>"},{"location":"api/macros/json_assert/#notes","title":"Notes","text":"<ul> <li>The library uses numerous assertions to guarantee invariants and to abort in case of otherwise undefined behavior (e.g., when calling operator[] with a missing object key on a <code>const</code> object). See page runtime assertions for more information.</li> <li>Defining the macro to code that does not call <code>std::abort</code> may leave the library in an undefined state.</li> <li>The macro is undefined outside the library.</li> </ul>"},{"location":"api/macros/json_assert/#examples","title":"Examples","text":"Example 1: default behavior <p>The following code will trigger an assertion at runtime:</p> <pre><code>#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n</code></pre> <p>Output:</p> <pre><code>Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n</code></pre> Example 2: user-defined behavior <p>The assertion reporting can be changed by defining <code>JSON_ASSERT(x)</code> differently.</p> <pre><code>#include <cstdio>\n#include <cstdlib>\n#define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();}\n\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n</code></pre> <p>Output:</p> <pre><code>assertion error in operator[]\n</code></pre>"},{"location":"api/macros/json_assert/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.9.0.</li> </ul>"},{"location":"api/macros/json_diagnostics/","title":"JSON_DIAGNOSTICS","text":"<pre><code>#define JSON_DIAGNOSTICS /* value */\n</code></pre> <p>This macro enables extended diagnostics for exception messages. Possible values are <code>1</code> to enable or <code>0</code> to disable (default).</p> <p>When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.</p>"},{"location":"api/macros/json_diagnostics/#default-definition","title":"Default definition","text":"<p>The default value is <code>0</code> (extended diagnostics are switched off).</p> <pre><code>#define JSON_DIAGNOSTICS 0\n</code></pre> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/json_diagnostics/#notes","title":"Notes","text":"<p>ABI compatibility</p> <p>As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names. </p> <p>This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior.</p> <p>Where possible, it is still recommended that all code define this the same way for maximum interoperability.</p> <p>CMake option</p> <p>Diagnostic messages can also be controlled with the CMake option <code>JSON_Diagnostics</code> (<code>OFF</code> by default) which defines <code>JSON_DIAGNOSTICS</code> accordingly.</p>"},{"location":"api/macros/json_diagnostics/#examples","title":"Examples","text":"Example 1: default behavior <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.type_error.302] type must be number, but is string\n</code></pre> <p>This exception can be hard to debug if storing the value <code>\"12\"</code> and accessing it is further apart.</p> Example 2: extended diagnostic messages <pre><code>#include <iostream>\n\n# define JSON_DIAGNOSTICS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n</code></pre> <p>Now the exception message contains a JSON Pointer <code>/address/housenumber</code> that indicates which value has the wrong type.</p>"},{"location":"api/macros/json_diagnostics/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.10.0.</li> <li>As of version 3.11.0 the definition is allowed to vary between translation units.</li> </ul>"},{"location":"api/macros/json_disable_enum_serialization/","title":"JSON_DISABLE_ENUM_SERIALIZATION","text":"<pre><code>#define JSON_DISABLE_ENUM_SERIALIZATION /* value */\n</code></pre> <p>When defined to <code>1</code>, default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> (see arbitrary type conversions for more details).</p> <p>Parsing or serializing an enum will result in a compiler error.</p> <p>This works for both unscoped and scoped enums.</p>"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","title":"Default definition","text":"<p>The default value is <code>0</code>.</p> <pre><code>#define JSON_DISABLE_ENUM_SERIALIZATION 0\n</code></pre>"},{"location":"api/macros/json_disable_enum_serialization/#notes","title":"Notes","text":"<p>CMake option</p> <p>Enum serialization can also be controlled with the CMake option <code>JSON_DisableEnumSerialization</code> (<code>OFF</code> by default) which defines <code>JSON_DISABLE_ENUM_SERIALIZATION</code> accordingly.</p>"},{"location":"api/macros/json_disable_enum_serialization/#examples","title":"Examples","text":"Example 1: Disabled behavior <p>The code below forces the library not to create default serialization/deserialization functions <code>from_json</code> and <code>to_json</code>, meaning the code below does not compile.</p> <pre><code>#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nint main()\n{\n // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not\n const json j = Choice::first; \n\n // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not\n Choice ch = j.template get<Choice>();\n}\n</code></pre> Example 2: Serialize enum macro <p>The code below forces the library not to create default serialization/deserialization functions <code>from_json</code> and <code>to_json</code>, but uses <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> to parse and serialize the enum.</p> <pre><code>#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Choice,\n{\n { Choice::first, \"first\" },\n { Choice::second, \"second\" },\n})\n\nint main()\n{\n // uses user-defined to_json function defined by macro\n const json j = Choice::first; \n\n // uses user-defined from_json function defined by macro\n Choice ch = j.template get<Choice>();\n}\n</code></pre> Example 3: User-defined serialization/deserialization functions <p>The code below forces the library not to create default serialization/deserialization functions <code>from_json</code> and <code>to_json</code>, but uses user-defined functions to parse and serialize the enum.</p> <pre><code>#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nvoid from_json(const json& j, Choice& ch)\n{\n auto value = j.template get<std::string>();\n if (value == \"first\")\n {\n ch = Choice::first;\n }\n else if (value == \"second\")\n {\n ch = Choice::second;\n }\n}\n\nvoid to_json(json& j, const Choice& ch)\n{\n auto value = j.template get<std::string>();\n if (value == \"first\")\n {\n ch = Choice::first;\n }\n else if (value == \"second\")\n {\n ch = Choice::second;\n }\n}\n\nint main()\n{\n // uses user-defined to_json function\n const json j = Choice::first; \n\n // uses user-defined from_json function\n Choice ch = j.template get<Choice>();\n}\n</code></pre>"},{"location":"api/macros/json_disable_enum_serialization/#see-also","title":"See also","text":"<ul> <li><code>NLOHMANN_JSON_SERIALIZE_ENUM</code></li> </ul>"},{"location":"api/macros/json_disable_enum_serialization/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/macros/json_has_cpp_11/","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20","text":"<pre><code>#define JSON_HAS_CPP_11\n#define JSON_HAS_CPP_14\n#define JSON_HAS_CPP_17\n#define JSON_HAS_CPP_20\n</code></pre> <p>The library targets C++11, but also supports some features introduced in later C++ versions (e.g., <code>std::string_view</code> support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.</p>"},{"location":"api/macros/json_has_cpp_11/#default-definition","title":"Default definition","text":"<p>The default value is detected based on preprocessor macros such as <code>__cplusplus</code>, <code>_HAS_CXX17</code>, or <code>_MSVC_LANG</code>.</p>"},{"location":"api/macros/json_has_cpp_11/#notes","title":"Notes","text":"<ul> <li><code>JSON_HAS_CPP_11</code> is always defined.</li> <li>All macros are undefined outside the library.</li> </ul>"},{"location":"api/macros/json_has_cpp_11/#examples","title":"Examples","text":"Example <p>The code below forces the library to use the C++14 standard:</p> <pre><code>#define JSON_HAS_CPP_14 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_has_cpp_11/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.10.5.</li> </ul>"},{"location":"api/macros/json_has_filesystem/","title":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"<pre><code>#define JSON_HAS_FILESYSTEM /* value */\n#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */\n</code></pre> <p>When compiling with C++17, the library provides conversions from and to <code>std::filesystem::path</code>. As compiler support for filesystem is limited, the library tries to detect whether <code><filesystem></code>/<code>std::filesystem</code> (<code>JSON_HAS_FILESYSTEM</code>) or <code><experimental/filesystem></code>/<code>std::experimental::filesystem</code> (<code>JSON_HAS_EXPERIMENTAL_FILESYSTEM</code>) should be used. To override the built-in check, define <code>JSON_HAS_FILESYSTEM</code> or <code>JSON_HAS_EXPERIMENTAL_FILESYSTEM</code> to <code>1</code>.</p>"},{"location":"api/macros/json_has_filesystem/#default-definition","title":"Default definition","text":"<p>The default value is detected based on the preprocessor macros <code>__cpp_lib_filesystem</code>, <code>__cpp_lib_experimental_filesystem</code>, <code>__has_include(<filesystem>)</code>, or <code>__has_include(<experimental/filesystem>)</code>.</p>"},{"location":"api/macros/json_has_filesystem/#notes","title":"Notes","text":"<ul> <li>Note that older compilers or older versions of libstd++ also require the library <code>stdc++fs</code> to be linked to for filesystem support.</li> <li>Both macros are undefined outside the library.</li> </ul>"},{"location":"api/macros/json_has_filesystem/#examples","title":"Examples","text":"Example <p>The code below forces the library to use the header <code><experimental/filesystem></code>.</p> <pre><code>#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_has_filesystem/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.10.5.</li> </ul>"},{"location":"api/macros/json_has_ranges/","title":"JSON_HAS_RANGES","text":"<pre><code>#define JSON_HAS_RANGES /* value */\n</code></pre> <p>This macro indicates whether the standard library has any support for ranges. Implies support for concepts. Possible values are <code>1</code> when supported or <code>0</code> when unsupported.</p>"},{"location":"api/macros/json_has_ranges/#default-definition","title":"Default definition","text":"<p>The default value is detected based on the preprocessor macro <code>__cpp_lib_ranges</code>.</p> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/json_has_ranges/#examples","title":"Examples","text":"Example <p>The code below forces the library to enable support for ranges:</p> <pre><code>#define JSON_HAS_RANGES 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_has_ranges/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/macros/json_has_static_rtti/","title":"JSON_HAS_STATIC_RTTI","text":"<pre><code>#define JSON_HAS_STATIC_RTTI /* value */\n</code></pre> <p>This macro indicates whether the standard library has any support for RTTI (run time type information). Possible values are <code>1</code> when supported or <code>0</code> when unsupported.</p>"},{"location":"api/macros/json_has_static_rtti/#default-definition","title":"Default definition","text":"<p>The default value is detected based on the preprocessor macro <code>_HAS_STATIC_RTTI</code>.</p> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/json_has_static_rtti/#examples","title":"Examples","text":"Example <p>The code below forces the library to enable support for libraries with RTTI dependence:</p> <pre><code>#define JSON_HAS_STATIC_RTTI 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_has_static_rtti/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.3.</li> </ul>"},{"location":"api/macros/json_has_three_way_comparison/","title":"JSON_HAS_THREE_WAY_COMPARISON","text":"<pre><code>#define JSON_HAS_THREE_WAY_COMPARISON /* value */\n</code></pre> <p>This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are <code>1</code> when supported or <code>0</code> when unsupported.</p>"},{"location":"api/macros/json_has_three_way_comparison/#default-definition","title":"Default definition","text":"<p>The default value is detected based on the preprocessor macros <code>__cpp_impl_three_way_comparison</code> and <code>__cpp_lib_three_way_comparison</code>.</p> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/json_has_three_way_comparison/#examples","title":"Examples","text":"Example <p>The code below forces the library to use 3-way comparison:</p> <pre><code>#define JSON_HAS_THREE_WAY_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_has_three_way_comparison/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/macros/json_no_io/","title":"JSON_NO_IO","text":"<pre><code>#define JSON_NO_IO\n</code></pre> <p>When defined, headers <code><cstdio></code>, <code><ios></code>, <code><iosfwd></code>, <code><istream></code>, and <code><ostream></code> are not included and parse functions relying on these headers are excluded. This is relevant for environments where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).</p>"},{"location":"api/macros/json_no_io/#default-definition","title":"Default definition","text":"<p>By default, <code>JSON_NO_IO</code> is not defined.</p> <pre><code>#undef JSON_NO_IO\n</code></pre>"},{"location":"api/macros/json_no_io/#examples","title":"Examples","text":"Example <p>The code below forces the library not to use the headers <code><cstdio></code>, <code><ios></code>, <code><iosfwd></code>, <code><istream></code>, and <code><ostream></code>.</p> <pre><code>#define JSON_NO_IO 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_no_io/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.10.0.</li> </ul>"},{"location":"api/macros/json_noexception/","title":"JSON_NOEXCEPTION","text":"<pre><code>#define JSON_NOEXCEPTION\n</code></pre> <p>Exceptions can be switched off by defining the symbol <code>JSON_NOEXCEPTION</code>. When defining <code>JSON_NOEXCEPTION</code>, <code>try</code> is replaced by <code>if (true)</code>, <code>catch</code> is replaced by <code>if (false)</code>, and <code>throw</code> is replaced by <code>std::abort()</code>.</p> <p>The same effect is achieved by setting the compiler flag <code>-fno-exceptions</code>.</p>"},{"location":"api/macros/json_noexception/#default-definition","title":"Default definition","text":"<p>By default, the macro is not defined.</p> <pre><code>#undef JSON_NOEXCEPTION\n</code></pre>"},{"location":"api/macros/json_noexception/#notes","title":"Notes","text":"<p>The explanatory <code>what()</code> string of exceptions is not available for MSVC if exceptions are disabled, see #2824.</p>"},{"location":"api/macros/json_noexception/#examples","title":"Examples","text":"Example <p>The code below switches off exceptions in the library.</p> <pre><code>#define JSON_NOEXCEPTION 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_noexception/#see-also","title":"See also","text":"<ul> <li>Switch off exceptions for more information how to switch off exceptions</li> </ul>"},{"location":"api/macros/json_noexception/#version-history","title":"Version history","text":"<p>Added in version 2.1.0.</p>"},{"location":"api/macros/json_skip_library_version_check/","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"<pre><code>#define JSON_SKIP_LIBRARY_VERSION_CHECK\n</code></pre> <p>When defined, the library will not create a compiler warning when a different version of the library was already included.</p>"},{"location":"api/macros/json_skip_library_version_check/#default-definition","title":"Default definition","text":"<p>By default, the macro is not defined.</p> <pre><code>#undef JSON_SKIP_LIBRARY_VERSION_CHECK\n</code></pre>"},{"location":"api/macros/json_skip_library_version_check/#notes","title":"Notes","text":"<p>ABI compatibility</p> <p>Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.</p>"},{"location":"api/macros/json_skip_library_version_check/#examples","title":"Examples","text":"<p>Example</p> <p>The following warning will be shown in case a different version of the library was already included:</p> <pre><code>Already included a different version of the library!\n</code></pre>"},{"location":"api/macros/json_skip_library_version_check/#version-history","title":"Version history","text":"<p>Added in version 3.11.0.</p>"},{"location":"api/macros/json_skip_unsupported_compiler_check/","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"<pre><code>#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n</code></pre> <p>When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.</p>"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","title":"Default definition","text":"<p>By default, the macro is not defined.</p> <pre><code>#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n</code></pre>"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","title":"Examples","text":"Example <p>The code below switches off the check whether the compiler is supported.</p> <pre><code>#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","title":"Version history","text":"<p>Added in version 3.2.0.</p>"},{"location":"api/macros/json_throw_user/","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER","text":"<pre><code>// (1)\n#define JSON_CATCH_USER(exception) /* value */\n// (2)\n#define JSON_THROW_USER(exception) /* value */\n// (3)\n#define JSON_TRY_USER /* value */\n</code></pre> <p>Controls how exceptions are handled by the library.</p> <ol> <li>This macro overrides <code>catch</code> calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches <code>std::out_of_range</code> exceptions internally to rethrow them as <code>json::out_of_range</code> exceptions. The macro is always followed by a scope.</li> <li>This macro overrides <code>throw</code> calls inside the library. The argument is the exception to be thrown. Note that <code>JSON_THROW_USER</code> should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.</li> <li>This macro overrides <code>try</code> calls inside the library. It has no arguments and is always followed by a scope.</li> </ol>"},{"location":"api/macros/json_throw_user/#parameters","title":"Parameters","text":"<code>exception</code> (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"<p>By default, the macros map to their respective C++ keywords:</p> <pre><code>#define JSON_CATCH_USER(exception) catch(exception)\n#define JSON_THROW_USER(exception) throw exception\n#define JSON_TRY_USER try\n</code></pre> <p>When exceptions are switched off, the <code>try</code> block is executed unconditionally, and throwing exceptions is replaced by calling <code>std::abort</code> to make reaching the <code>throw</code> branch abort the process.</p> <pre><code>#define JSON_THROW_USER(exception) std::abort()\n#define JSON_TRY_USER if (true)\n#define JSON_CATCH_USER(exception) if (false)\n</code></pre>"},{"location":"api/macros/json_throw_user/#examples","title":"Examples","text":"Example <p>The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.</p> <pre><code>#include <iostream>\n\n#define JSON_TRY_USER if(true)\n#define JSON_CATCH_USER(exception) if(false)\n#define JSON_THROW_USER(exception) \\\n {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\\n << \" (function \" << __FUNCTION__ << \") - \" \\\n << (exception).what() << std::endl; \\\n std::abort();}\n\n#include <nlohmann/json.hpp>\n</code></pre>"},{"location":"api/macros/json_throw_user/#see-also","title":"See also","text":"<ul> <li>Switch off exceptions for more information how to switch off exceptions</li> <li>JSON_NOEXCEPTION - switch off exceptions</li> </ul>"},{"location":"api/macros/json_throw_user/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.1.0.</li> </ul>"},{"location":"api/macros/json_use_global_udls/","title":"JSON_USE_GLOBAL_UDLS","text":"<pre><code>#define JSON_USE_GLOBAL_UDLS /* value */\n</code></pre> <p>When defined to <code>1</code>, the user-defined string literals (UDLs) are placed into the global namespace instead of <code>nlohmann::literals::json_literals</code>.</p>"},{"location":"api/macros/json_use_global_udls/#default-definition","title":"Default definition","text":"<p>The default value is <code>1</code>.</p> <pre><code>#define JSON_USE_GLOBAL_UDLS 1\n</code></pre> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/json_use_global_udls/#notes","title":"Notes","text":"<p>Future behavior change</p> <p>The user-defined string literals will be removed from the global namespace in the next major release of the library.</p> <p>To prepare existing code, define <code>JSON_USE_GLOBAL_UDLS</code> to <code>0</code> and bring the string literals into scope where needed. Refer to any of the string literals for details.</p> <p>CMake option</p> <p>The placement of user-defined string literals can also be controlled with the CMake option <code>JSON_GlobalUDLs</code> (<code>ON</code> by default) which defines <code>JSON_USE_GLOBAL_UDLS</code> accordingly.</p>"},{"location":"api/macros/json_use_global_udls/#examples","title":"Examples","text":"Example 1: Default behavior <p>The code below shows the default behavior using the <code>_json</code> UDL.</p> <pre><code>#include <nlohmann/json.hpp>\n\n#include <iostream>\n\nint main()\n{\n auto j = \"42\"_json;\n\n std::cout << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>42\n</code></pre> Example 2: Namespaced UDLs <p>The code below shows how UDLs need to be brought into scope before using <code>_json</code> when <code>JSON_USE_GLOBAL_UDLS</code> is defined to <code>0</code>.</p> <pre><code>#define JSON_USE_GLOBAL_UDLS 0\n#include <nlohmann/json.hpp>\n\n#include <iostream>\n\nint main()\n{\n // auto j = \"42\"_json; // This line would fail to compile,\n // because the UDLs are not in the global namespace\n\n // Bring the UDLs into scope\n using namespace nlohmann::json_literals;\n\n auto j = \"42\"_json;\n\n std::cout << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>42\n</code></pre>"},{"location":"api/macros/json_use_global_udls/#see-also","title":"See also","text":"<ul> <li><code>operator\"\"_json</code></li> <li><code>operator\"\"_json_pointer</code></li> </ul>"},{"location":"api/macros/json_use_global_udls/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/macros/json_use_implicit_conversions/","title":"JSON_USE_IMPLICIT_CONVERSIONS","text":"<pre><code>#define JSON_USE_IMPLICIT_CONVERSIONS /* value */\n</code></pre> <p>When defined to <code>0</code>, implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects <code>operator ValueType</code>.</p>"},{"location":"api/macros/json_use_implicit_conversions/#default-definition","title":"Default definition","text":"<p>By default, implicit conversions are enabled.</p> <pre><code>#define JSON_USE_IMPLICIT_CONVERSIONS 1\n</code></pre>"},{"location":"api/macros/json_use_implicit_conversions/#notes","title":"Notes","text":"<p>Future behavior change</p> <p>Implicit conversions will be switched off by default in the next major release of the library.</p> <p>You can prepare existing code by already defining <code>JSON_USE_IMPLICIT_CONVERSIONS</code> to <code>0</code> and replace any implicit conversions with calls to <code>get</code>.</p> <p>CMake option</p> <p>Implicit conversions can also be controlled with the CMake option <code>JSON_ImplicitConversions</code> (<code>ON</code> by default) which defines <code>JSON_USE_IMPLICIT_CONVERSIONS</code> accordingly.</p>"},{"location":"api/macros/json_use_implicit_conversions/#examples","title":"Examples","text":"Example <p>This is an example for an implicit conversion:</p> <pre><code>json j = \"Hello, world!\";\nstd::string s = j;\n</code></pre> <p>When <code>JSON_USE_IMPLICIT_CONVERSIONS</code> is defined to <code>0</code>, the code above does no longer compile. Instead, it must be written like this:</p> <pre><code>json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n</code></pre>"},{"location":"api/macros/json_use_implicit_conversions/#see-also","title":"See also","text":"<ul> <li>operator ValueType - get a value (implicit)</li> <li>get - get a value (explicit)</li> </ul>"},{"location":"api/macros/json_use_implicit_conversions/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.9.0.</li> </ul>"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON","text":"<pre><code>#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */\n</code></pre> <p>This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are <code>1</code> to enable or <code>0</code> to disable (default).</p> <p>When enabled, comparisons involving at least one discarded JSON value yield results as follows:</p> Operator Result <code>==</code> <code>false</code> <code>!=</code> <code>true</code> <code><</code> <code>false</code> <code><=</code> <code>true</code> <code>>=</code> <code>true</code> <code>></code> <code>false</code> <p>Otherwise, comparisons involving at least one discarded JSON value always yield <code>false</code>.</p>"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#default-definition","title":"Default definition","text":"<p>The default value is <code>0</code>.</p> <pre><code>#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0\n</code></pre> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","title":"Notes","text":"<p>Inconsistent behavior in C++20 and beyond</p> <p>When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.</p> <ul> <li>The 3-way comparison operator (<code><=></code>) will always give the correct result (<code>std::partial_ordering::unordered</code>) regardless of the value of <code>JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON</code>.</li> <li>Overloads for the equality and relational operators emulate the legacy behavior.</li> </ul> <p>Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in inconsistent and unpredictable behavior.</p> <p>See <code>operator<=></code> for more information on 3-way comparison.</p> <p>Deprecation</p> <p>The legacy comparison behavior is deprecated and may be removed in a future major version release.</p> <p>New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.</p> <p>CMake option</p> <p>Legacy comparison can also be controlled with the CMake option <code>JSON_LegacyDiscardedValueComparison</code> (<code>OFF</code> by default) which defines <code>JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON</code> accordingly.</p>"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#examples","title":"Examples","text":"Example <p>The code below switches on the legacy discarded value comparison behavior in the library.</p> <pre><code>#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n</code></pre>"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0.</li> </ul>"},{"location":"api/macros/nlohmann_define_type_intrusive/","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE","text":"<pre><code>#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1)\n#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)\n#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)\n</code></pre> <p>These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code>, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.</p> <ol> <li>Will use <code>at</code> during deserialization and will throw <code>out_of_range.403</code> if a key is missing in the JSON object.</li> <li>Will use <code>value</code> during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated <code>from_json()</code> function default constructs an object and uses its values as the defaults when calling the <code>value</code> function.</li> <li>Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.</li> </ol>"},{"location":"api/macros/nlohmann_define_type_intrusive/#parameters","title":"Parameters","text":"<code>type</code> (in) name of the type (class, struct) to serialize/deserialize <code>member</code> (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","title":"Default definition","text":"<p>The macros add two friend functions to the class which take care of the serialization and deserialization:</p> <pre><code>friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&); // except (3)\n</code></pre> <p>See examples below for the concrete generated code.</p>"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","title":"Notes","text":"<p>Prerequisites</p> <ol> <li>The type <code>type</code> must be default constructible (except (3)). See How can I use <code>get()</code> for non-default constructible/non-copyable types? for how to overcome this limitation.</li> <li>The macro must be used inside the type (class/struct).</li> </ol> <p>Implementation limits</p> <ul> <li>The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the <code>to_json</code>/<code>from_json</code> functions manually.</li> <li>The macros only work for the <code>nlohmann::json</code> type; other specializations such as <code>nlohmann::ordered_json</code> are currently unsupported.</li> </ul>"},{"location":"api/macros/nlohmann_define_type_intrusive/#examples","title":"Examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE <p>Consider the following complete example:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n</code></pre> <p>Notes:</p> <ul> <li><code>ns::person</code> is default-constructible. This is a requirement for using the macro.</li> <li><code>ns::person</code> has private member variables. This makes <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> applicable, but not <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code>.</li> <li>The macro <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> is used inside the class.</li> <li>A missing key \"age\" in the deserialization yields an exception. To fall back to the default value, <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</code> can be used.</li> </ul> <p>The macro is equivalent to:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n\n friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n {\n nlohmann_json_t.name = nlohmann_json_j.at(\"name\");\n nlohmann_json_t.address = nlohmann_json_j.at(\"address\");\n nlohmann_json_t.age = nlohmann_json_j.at(\"age\");\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n</code></pre> Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT <p>Consider the following complete example:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n</code></pre> <p>Notes:</p> <ul> <li><code>ns::person</code> is default-constructible. This is a requirement for using the macro.</li> <li><code>ns::person</code> has private member variables. This makes <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</code> applicable, but not <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT</code>.</li> <li>The macro <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</code> is used inside the class.</li> <li>A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value <code>-1</code> is used.</li> </ul> <p>The macro is equivalent to:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n\n friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n {\n person nlohmann_json_default_obj;\n nlohmann_json_t.name = nlohmann_json_j.value(\"name\", nlohmann_json_default_obj.name);\n nlohmann_json_t.address = nlohmann_json_j.value(\"address\", nlohmann_json_default_obj.address);\n nlohmann_json_t.age = nlohmann_json_j.value(\"age\", nlohmann_json_default_obj.age);\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n</code></pre> <p>Note how a default-initialized <code>person</code> object is used in the <code>from_json</code> to fill missing values.</p> Example (3): NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE <p>Consider the following complete example:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n // No default constructor\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n</code></pre> <p>Notes:</p> <ul> <li><code>ns::person</code> is non-default-constructible. This allows this macro to be used instead of <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> and <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</code>.</li> <li><code>ns::person</code> has private member variables. This makes <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE</code> applicable, but not <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE</code>.</li> <li>The macro <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE</code> is used inside the class.</li> </ul> <p>The macro is equivalent to:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n // No default constructor\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n</code></pre>"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","title":"See also","text":"<ul> <li>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE{_WITH_DEFAULT, _ONLY_SERIALIZE} for a similar macro that can be defined outside the type.</li> <li>Arbitrary Type Conversions for an overview.</li> </ul>"},{"location":"api/macros/nlohmann_define_type_intrusive/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.9.0.</li> <li>Added in version 3.11.0.</li> <li>Added in version TODO.</li> </ol>"},{"location":"api/macros/nlohmann_define_type_non_intrusive/","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE","text":"<pre><code>#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1)\n#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)\n#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)\n</code></pre> <p>These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined outside the class/struct to create code for, but inside its namespace. Unlike <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code>, it cannot access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.</p> <ol> <li>Will use <code>at</code> during deserialization and will throw <code>out_of_range.403</code> if a key is missing in the JSON object.</li> <li>Will use <code>value</code> during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated <code>from_json()</code> function default constructs an object and uses its values as the defaults when calling the <code>value</code> function.</li> <li>Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.</li> </ol>"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#parameters","title":"Parameters","text":"<code>type</code> (in) name of the type (class, struct) to serialize/deserialize <code>member</code> (in) name of the (public) member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","title":"Default definition","text":"<p>The macros add two functions to the namespace which take care of the serialization and deserialization:</p> <pre><code>void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&); // except (3)\n</code></pre> <p>See examples below for the concrete generated code.</p>"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","title":"Notes","text":"<p>Prerequisites</p> <ol> <li>The type <code>type</code> must be default constructible (except (3). See How can I use <code>get()</code> for non-default constructible/non-copyable types? for how to overcome this limitation.</li> <li>The macro must be used outside the type (class/struct).</li> <li>The passed members must be public.</li> </ol> <p>Implementation limits</p> <ul> <li>The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the <code>to_json</code>/<code>from_json</code> functions manually.</li> <li>The macros only work for the <code>nlohmann::json</code> type; other specializations such as <code>nlohmann::ordered_json</code> are currently unsupported.</li> </ul>"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#examples","title":"Examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE <p>Consider the following complete example:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n</code></pre> <p>Notes:</p> <ul> <li><code>ns::person</code> is default-constructible. This is a requirement for using the macro.</li> <li><code>ns::person</code> has only public member variables. This makes <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code> applicable.</li> <li>The macro <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code> is used outside the class, but inside its namespace <code>ns</code>.</li> <li>A missing key \"age\" in the deserialization yields an exception. To fall back to the default value, <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT</code> can be used.</li> </ul> <p>The macro is equivalent to:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n\nvoid from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n{\n nlohmann_json_t.name = nlohmann_json_j.at(\"name\");\n nlohmann_json_t.address = nlohmann_json_j.at(\"address\");\n nlohmann_json_t.age = nlohmann_json_j.at(\"age\");\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n</code></pre> Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT <p>Consider the following complete example:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n</code></pre> <p>Notes:</p> <ul> <li><code>ns::person</code> is default-constructible. This is a requirement for using the macro.</li> <li><code>ns::person</code> has only public member variables. This makes <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT</code> applicable.</li> <li>The macro <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT</code> is used outside the class, but inside its namespace <code>ns</code>.</li> <li>A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value <code>-1</code> is used.</li> </ul> <p>The macro is equivalent to:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n\nvoid from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n{\n person nlohmann_json_default_obj;\n nlohmann_json_t.name = nlohmann_json_j.value(\"name\", nlohmann_json_default_obj.name);\n nlohmann_json_t.address = nlohmann_json_j.value(\"address\", nlohmann_json_default_obj.address);\n nlohmann_json_t.age = nlohmann_json_j.value(\"age\", nlohmann_json_default_obj.age);\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n</code></pre> <p>Note how a default-initialized <code>person</code> object is used in the <code>from_json</code> to fill missing values.</p> Example (3): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE <p>Consider the following complete example:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n</code></pre> <p>Notes:</p> <ul> <li><code>ns::person</code> is non-default-constructible. This allows this macro to be used instead of <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code> and <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT</code>.</li> <li><code>ns::person</code> has only public member variables. This makes <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE</code> applicable.</li> <li>The macro <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE</code> is used outside the class, but inside its namespace <code>ns</code>.</li> </ul> <p>The macro is equivalent to:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n</code></pre>"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","title":"See also","text":"<ul> <li>NLOHMANN_DEFINE_TYPE_INTRUSIVE{_WITH_DEFAULT, _ONLY_SERIALIZE} for a similar macro that can be defined inside the type.</li> <li>Arbitrary Type Conversions for an overview.</li> </ul>"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#version-history","title":"Version history","text":"<ol> <li>Added in version 3.9.0.</li> <li>Added in version 3.11.0.</li> <li>Added in version TODO.</li> </ol>"},{"location":"api/macros/nlohmann_json_namespace/","title":"NLOHMANN_JSON_NAMESPACE","text":"<pre><code>#define NLOHMANN_JSON_NAMESPACE /* value */\n</code></pre> <p>This macro evaluates to the full name of the <code>nlohmann</code> namespace.</p>"},{"location":"api/macros/nlohmann_json_namespace/#default-definition","title":"Default definition","text":"<p>The default value consists of the root namespace (<code>nlohmann</code>) and an inline ABI namespace. See <code>nlohmann</code> Namespace for details.</p> <p>When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.</p>"},{"location":"api/macros/nlohmann_json_namespace/#examples","title":"Examples","text":"Example <p>The example shows how to use <code>NLOHMANN_JSON_NAMESPACE</code> instead of just <code>nlohmann</code>, as well as how to output the value of <code>NLOHMANN_JSON_NAMESPACE</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\n// possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann\nusing json = NLOHMANN_JSON_NAMESPACE::json;\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>nlohmann::json_abi_v3_11_3\n</code></pre>"},{"location":"api/macros/nlohmann_json_namespace/#see-also","title":"See also","text":"<ul> <li><code>NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END</code></li> <li><code>NLOHMANN_JSON_NAMESPACE_NO_VERSION</code></li> </ul>"},{"location":"api/macros/nlohmann_json_namespace/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0. Changed inline namespace name in version 3.11.2.</li> </ul>"},{"location":"api/macros/nlohmann_json_namespace_begin/","title":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END","text":"<pre><code>#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1)\n#define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2)\n</code></pre> <p>These macros can be used to open and close the <code>nlohmann</code> namespace. See <code>nlohmann</code> Namespace for details.</p> <ol> <li>Opens the namespace.</li> <li>Closes the namespace.</li> </ol>"},{"location":"api/macros/nlohmann_json_namespace_begin/#default-definition","title":"Default definition","text":"<p>The default definitions open and close the <code>nlohmann</code> namespace. The precise definition of [<code>NLOHMANN_JSON_NAMESPACE_BEGIN</code>] varies as described here.</p> <ol> <li> <p>Default definition of <code>NLOHMANN_JSON_NAMESPACE_BEGIN</code>:</p> <pre><code>namespace nlohmann\n{\ninline namespace json_abi_v3_11_2\n{\n</code></pre> </li> <li> <p>Default definition of <code>NLOHMANN_JSON_NAMESPACE_END</code>: <pre><code>} // namespace json_abi_v3_11_2\n} // namespace nlohmann\n</code></pre></p> </li> </ol> <p>When these macros are not defined, the library will define them to their default definitions.</p>"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","title":"Examples","text":"Example <p>The example shows how to use <code>NLOHMANN_JSON_NAMESPACE_BEGIN</code>/<code>NLOHMANN_JSON_NAMESPACE_END</code> from the How do I convert third-party types? page.</p> <pre><code>#include <iostream>\n#include <optional>\n#include <nlohmann/json.hpp>\n\n// partial specialization (see https://json.nlohmann.me/features/arbitrary_types/)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<std::optional<T>>\n{\n static void to_json(json& j, const std::optional<T>& opt)\n {\n if (opt == std::nullopt)\n {\n j = nullptr;\n }\n else\n {\n j = *opt;\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n\nint main()\n{\n std::optional<int> o1 = 1;\n std::optional<int> o2 = std::nullopt;\n\n NLOHMANN_JSON_NAMESPACE::json j;\n j.push_back(o1);\n j.push_back(o2);\n std::cout << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>[1,null]\n</code></pre>"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","title":"See also","text":"<ul> <li><code>nlohmann</code> Namespace</li> <li>NLOHMANN_JSON_NAMESPACE</li> <li><code>NLOHMANN_JSON_NAMESPACE_NO_VERSION</code></li> </ul>"},{"location":"api/macros/nlohmann_json_namespace_begin/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.0. Changed inline namespace name in version 3.11.2.</li> </ul>"},{"location":"api/macros/nlohmann_json_namespace_no_version/","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION","text":"<pre><code>#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */\n</code></pre> <p>If defined to <code>1</code>, the version component is omitted from the inline namespace. See <code>nlohmann</code> Namespace for details.</p>"},{"location":"api/macros/nlohmann_json_namespace_no_version/#default-definition","title":"Default definition","text":"<p>The default value is <code>0</code>.</p> <pre><code>#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0\n</code></pre> <p>When the macro is not defined, the library will define it to its default value.</p>"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","title":"Examples","text":"Example <p>The example shows how to use <code>NLOHMANN_JSON_NAMESPACE_NO_VERSION</code> to disable the version component of the inline namespace.</p> <pre><code>#include <iostream>\n\n#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1\n#include <nlohmann/json.hpp>\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>nlohmann::json_abi\n</code></pre>"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","title":"See also","text":"<ul> <li><code>nlohmann</code> Namespace</li> <li><code>NLOHMANN_JSON_NAMESPACE</code></li> <li><code>NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END</code></li> </ul>"},{"location":"api/macros/nlohmann_json_namespace_no_version/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.11.2.</li> </ul>"},{"location":"api/macros/nlohmann_json_serialize_enum/","title":"NLOHMANN_JSON_SERIALIZE_ENUM","text":"<pre><code>#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)\n</code></pre> <p>By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.</p> <p>The <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> allows to define a user-defined serialization for every enumerator.</p>"},{"location":"api/macros/nlohmann_json_serialize_enum/#parameters","title":"Parameters","text":"<code>type</code> (in) name of the enum to serialize/deserialize <code>conversion</code> (in) a pair of an enumerator and a JSON serialization; arbitrary pairs can be given as a comma-separated list"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","title":"Default definition","text":"<p>The macros add two friend functions to the class which take care of the serialization and deserialization:</p> <pre><code>template<typename BasicJsonType>\ninline void to_json(BasicJsonType& j, const type& e);\ntemplate<typename BasicJsonType>\ninline void from_json(const BasicJsonType& j, type& e);\n</code></pre>"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","title":"Notes","text":"<p>Prerequisites</p> <p>The macro must be used inside the namespace of the enum.</p> <p>Important notes</p> <ul> <li>When using <code>template get<ENUM_TYPE>()</code>, undefined JSON values will default to the first specified conversion. Select this default pair carefully. See example 1 below.</li> <li>If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the list will be returned when converting to or from JSON. See example 2 below.</li> </ul>"},{"location":"api/macros/nlohmann_json_serialize_enum/#examples","title":"Examples","text":"Example 1: Basic usage <p>The example shows how <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> can be used to serialize/deserialize both classical enums and C++11 enum classes:</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum TaskState\n{\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID = -1\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(TaskState,\n{\n { TS_INVALID, nullptr },\n { TS_STOPPED, \"stopped\" },\n { TS_RUNNING, \"running\" },\n { TS_COMPLETED, \"completed\" }\n})\n\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" }\n})\n} // namespace ns\n\nint main()\n{\n // serialization\n json j_stopped = ns::TS_STOPPED;\n json j_red = ns::Color::red;\n std::cout << \"ns::TS_STOPPED -> \" << j_stopped\n << \", ns::Color::red -> \" << j_red << std::endl;\n\n // deserialization\n json j_running = \"running\";\n json j_blue = \"blue\";\n auto running = j_running.template get<ns::TaskState>();\n auto blue = j_blue.template get<ns::Color>();\n std::cout << j_running << \" -> \" << running\n << \", \" << j_blue << \" -> \" << static_cast<int>(blue) << std::endl;\n\n // deserializing undefined JSON value to enum\n // (where the first map entry above is the default)\n json j_pi = 3.14;\n auto invalid = j_pi.template get<ns::TaskState>();\n auto unknown = j_pi.template get<ns::Color>();\n std::cout << j_pi << \" -> \" << invalid << \", \"\n << j_pi << \" -> \" << static_cast<int>(unknown) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>ns::TS_STOPPED -> \"stopped\", ns::Color::red -> \"red\"\n\"running\" -> 1, \"blue\" -> 2\n3.14 -> -1, 3.14 -> 3\n</code></pre> Example 2: Multiple conversions for one enumerator <p>The example shows how to use multiple conversions for a single enumerator. In the example, <code>Color::red</code> will always be serialized to <code>\"red\"</code>, because the first occurring conversion. The second conversion, however, offers an alternative deserialization from <code>\"rot\"</code> to <code>Color::red</code>.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" },\n { Color::red, \"rot\" } // a second conversion for Color::red\n})\n}\n\nint main()\n{\n // serialization\n json j_red = ns::Color::red;\n std::cout << static_cast<int>(ns::Color::red) << \" -> \" << j_red << std::endl;\n\n // deserialization\n json j_rot = \"rot\";\n auto rot = j_rot.template get<ns::Color>();\n auto red = j_red.template get<ns::Color>();\n std::cout << j_rot << \" -> \" << static_cast<int>(rot) << std::endl;\n std::cout << j_red << \" -> \" << static_cast<int>(red) << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0 -> \"red\"\n\"rot\" -> 0\n\"red\" -> 0\n</code></pre>"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","title":"See also","text":"<ul> <li>Specializing enum conversion</li> <li><code>JSON_DISABLE_ENUM_SERIALIZATION</code></li> </ul>"},{"location":"api/macros/nlohmann_json_serialize_enum/#version-history","title":"Version history","text":"<p>Added in version 3.4.0.</p>"},{"location":"api/macros/nlohmann_json_version_major/","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"<pre><code>#define NLOHMANN_JSON_VERSION_MAJOR /* value */\n#define NLOHMANN_JSON_VERSION_MINOR /* value */\n#define NLOHMANN_JSON_VERSION_PATCH /* value */\n</code></pre> <p>These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.</p>"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","title":"Default definition","text":"<p>The macros are defined according to the current library version.</p>"},{"location":"api/macros/nlohmann_json_version_major/#examples","title":"Examples","text":"Example <p>The example below shows how <code>NLOHMANN_JSON_VERSION_MAJOR</code>, <code>NLOHMANN_JSON_VERSION_MINOR</code>, and <code>NLOHMANN_JSON_VERSION_PATCH</code> are defined by the library.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << \"JSON for Modern C++ version \"\n << NLOHMANN_JSON_VERSION_MAJOR << \".\"\n << NLOHMANN_JSON_VERSION_MINOR << \".\"\n << NLOHMANN_JSON_VERSION_PATCH << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>JSON for Modern C++ version 3.11.3\n</code></pre>"},{"location":"api/macros/nlohmann_json_version_major/#see-also","title":"See also","text":"<ul> <li>meta - returns version information on the library</li> <li>JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check</li> </ul>"},{"location":"api/macros/nlohmann_json_version_major/#version-history","title":"Version history","text":"<ul> <li>Added in version 3.1.0.</li> </ul>"},{"location":"features/arbitrary_types/","title":"Arbitrary Type Conversions","text":"<p>Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:</p> <pre><code>namespace ns {\n // a simple struct to model a person\n struct person {\n std::string name;\n std::string address;\n int age;\n };\n} // namespace ns\n\nns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// convert to JSON: copy each value into the JSON object\njson j;\nj[\"name\"] = p.name;\nj[\"address\"] = p.address;\nj[\"age\"] = p.age;\n\n// ...\n\n// convert from JSON: copy each value from the JSON object\nns::person p {\n j[\"name\"].template get<std::string>(),\n j[\"address\"].template get<std::string>(),\n j[\"age\"].template get<int>()\n};\n</code></pre> <p>It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:</p> <pre><code>// create a person\nns::person p {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// conversion: person -> json\njson j = p;\n\nstd::cout << j << std::endl;\n// {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n\n// conversion: json -> person\nauto p2 = j.template get<ns::person>();\n\n// that's it\nassert(p == p2);\n</code></pre>"},{"location":"features/arbitrary_types/#basic-usage","title":"Basic usage","text":"<p>To make this work with one of your types, you only need to provide two functions:</p> <pre><code>using json = nlohmann::json;\n\nnamespace ns {\n void to_json(json& j, const person& p) {\n j = json{ {\"name\", p.name}, {\"address\", p.address}, {\"age\", p.age} };\n }\n\n void from_json(const json& j, person& p) {\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n }\n} // namespace ns\n</code></pre> <p>That's all! When calling the <code>json</code> constructor with your type, your custom <code>to_json</code> method will be automatically called. Likewise, when calling <code>template get<your_type>()</code> or <code>get_to(your_type&)</code>, the <code>from_json</code> method will be called.</p> <p>Some important things:</p> <ul> <li>Those methods MUST be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace <code>ns</code>, where <code>person</code> is defined).</li> <li>Those methods MUST be available (e.g., proper headers must be included) everywhere you use these conversions. Look at issue 1108 for errors that may occur otherwise.</li> <li>When using <code>template get<your_type>()</code>, <code>your_type</code> MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)</li> <li>In function <code>from_json</code>, use function <code>at()</code> to access the object values rather than <code>operator[]</code>. In case a key does not exist, <code>at</code> throws an exception that you can handle, whereas <code>operator[]</code> exhibits undefined behavior.</li> <li>You do not need to add serializers or deserializers for STL types like <code>std::vector</code>: the library already implements these.</li> </ul>"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","title":"Simplify your life with macros","text":"<p>If you just want to serialize/deserialize some structs, the <code>to_json</code>/<code>from_json</code> functions can be a lot of boilerplate.</p> <p>There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object:</p> <ul> <li><code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...)</code> is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in <code>from_json()</code> due to a missing value in the JSON object.</li> <li><code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...)</code> is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in <code>from_json()</code> due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type.</li> <li><code>NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...)</code> is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in <code>from_json()</code> due to a missing value in the JSON object.</li> <li><code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...)</code> is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in <code>from_json()</code> due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type.</li> </ul> <p>In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here.</p> <p>Implementation limits</p> <ul> <li>The current macro implementations are limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the <code>to_json</code>/<code>from_json</code> functions manually.</li> <li>The macros only work for the <code>nlohmann::json</code> type; other specializations such as <code>nlohmann::ordered_json</code> are currently unsupported.</li> </ul> Example <p>The <code>to_json</code>/<code>from_json</code> functions for the <code>person</code> struct above can be created with:</p> <pre><code>namespace ns {\n NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n}\n</code></pre> <p>Here is an example with private members, where <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> is needed:</p> <pre><code>namespace ns {\n class address {\n private:\n std::string street;\n int housenumber;\n int postcode;\n\n public:\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)\n };\n}\n</code></pre>"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"<p>This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:</p> <p>The library uses JSON Serializers to convert types to json. The default serializer for <code>nlohmann::json</code> is <code>nlohmann::adl_serializer</code> (ADL means Argument-Dependent Lookup).</p> <p>It is implemented like this (simplified):</p> <pre><code>template <typename T>\nstruct adl_serializer {\n static void to_json(json& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n static void from_json(const json& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n</code></pre> <p>This serializer works fine when you have control over the type's namespace. However, what about <code>boost::optional</code> or <code>std::filesystem::path</code> (C++17)? Hijacking the <code>boost</code> namespace is pretty bad, and it's illegal to add something other than template specializations to <code>std</code>...</p> <p>To solve this, you need to add a specialization of <code>adl_serializer</code> to the <code>nlohmann</code> namespace, here's an example:</p> <pre><code>// partial specialization (full specialization works too)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<boost::optional<T>> {\n static void to_json(json& j, const boost::optional<T>& opt) {\n if (opt == boost::none) {\n j = nullptr;\n } else {\n j = *opt; // this will call adl_serializer<T>::to_json which will\n // find the free function to_json in T's namespace!\n }\n }\n\n static void from_json(const json& j, boost::optional<T>& opt) {\n if (j.is_null()) {\n opt = boost::none;\n } else {\n opt = j.template get<T>(); // same as above, but with\n // adl_serializer<T>::from_json\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n</code></pre> <p>ABI compatibility</p> <p>Use <code>NLOHMANN_JSON_NAMESPACE_BEGIN</code> and <code>NLOHMANN_JSON_NAMESPACE_END</code> instead of <code>namespace nlohmann { }</code> in code which may be linked with different versions of this library.</p>"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types","title":"How can I use <code>get()</code> for non-default constructible/non-copyable types?","text":"<p>There is a way, if your type is MoveConstructible. You will need to specialize the <code>adl_serializer</code> as well, but with a special <code>from_json</code> overload:</p> <pre><code>struct move_only_type {\n move_only_type() = delete;\n move_only_type(int ii): i(ii) {}\n move_only_type(const move_only_type&) = delete;\n move_only_type(move_only_type&&) = default;\n\n int i;\n};\n\nnamespace nlohmann {\n template <>\n struct adl_serializer<move_only_type> {\n // note: the return type is no longer 'void', and the method only takes\n // one argument\n static move_only_type from_json(const json& j) {\n return {j.template get<int>()};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert move_only_type to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, move_only_type t) {\n j = t.i;\n }\n };\n}\n</code></pre>"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"<p>Yes. You might want to take a look at <code>unit-udt.cpp</code> in the test suite, to see a few examples.</p> <p>If you write your own serializer, you'll need to do a few things:</p> <ul> <li>use a different <code>basic_json</code> alias than <code>nlohmann::json</code> (the last template parameter of <code>basic_json</code> is the <code>JSONSerializer</code>)</li> <li>use your <code>basic_json</code> alias (or a template parameter) in all your <code>to_json</code>/<code>from_json</code> methods</li> <li>use <code>nlohmann::to_json</code> and <code>nlohmann::from_json</code> when you need ADL</li> </ul> <p>Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.</p> <pre><code>// You should use void as a second template argument\n// if you don't need compile-time checks on T\ntemplate<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>\nstruct less_than_32_serializer {\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, T value) {\n // we want to use ADL, and call the correct to_json overload\n using nlohmann::to_json; // this method is called by adl_serializer,\n // this is where the magic happens\n to_json(j, value);\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing here\n using nlohmann::from_json;\n from_json(j, value);\n }\n};\n</code></pre> <p>Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:</p> <pre><code>template <typename T, void>\nstruct bad_serializer\n{\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, const T& value) {\n // this calls BasicJsonType::json_serializer<T>::to_json(j, value);\n // if BasicJsonType::json_serializer == bad_serializer ... oops!\n j = value;\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // this calls BasicJsonType::json_serializer<T>::from_json(j, value);\n // if BasicJsonType::json_serializer == bad_serializer ... oops!\n value = j.template template get<T>(); // oops!\n }\n};\n</code></pre>"},{"location":"features/assertions/","title":"Runtime Assertions","text":"<p>The code contains numerous debug assertions to ensure class invariants are valid or to detect undefined behavior. Whereas the former class invariants are nothing to be concerned of, the latter checks for undefined behavior are to detect bugs in client code.</p>"},{"location":"features/assertions/#switch-off-runtime-assertions","title":"Switch off runtime assertions","text":"<p>Runtime assertions can be switched off by defining the preprocessor macro <code>NDEBUG</code> (see the documentation of assert) which is the default for release builds.</p>"},{"location":"features/assertions/#change-assertion-behavior","title":"Change assertion behavior","text":"<p>The behavior of runtime assertions can be changes by defining macro <code>JSON_ASSERT(x)</code> before including the <code>json.hpp</code> header.</p>"},{"location":"features/assertions/#function-with-runtime-assertions","title":"Function with runtime assertions","text":""},{"location":"features/assertions/#unchecked-object-access-to-a-const-value","title":"Unchecked object access to a const value","text":"<p>Function <code>operator[]</code> implements unchecked access for objects. Whereas a missing key is added in case of non-const objects, accessing a const object with a missing key is undefined behavior (think of a dereferenced null pointer) and yields a runtime assertion.</p> <p>If you are not sure whether an element in an object exists, use checked access with the <code>at</code> function or call the <code>contains</code> function before.</p> <p>See also the documentation on element access.</p> Example 1: Missing object key <p>The following code will trigger an assertion at runtime:</p> <pre><code>#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n</code></pre> <p>Output:</p> <pre><code>Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n</code></pre>"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"<p>Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.</p> Example 2: Uninitialized iterator range <p>The following code will trigger an assertion at runtime:</p> <pre><code>#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::iterator it1, it2;\n json j(it1, it2);\n}\n</code></pre> <p>Output:</p> <pre><code>Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n</code></pre>"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"<p>Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.</p> Example 3: Uninitialized iterator <p>The following code will trigger an assertion at runtime:</p> <pre><code>#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::iterator it;\n ++it;\n}\n</code></pre> <p>Output:</p> <pre><code>Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n</code></pre>"},{"location":"features/assertions/#reading-from-a-null-file-pointer","title":"Reading from a null <code>FILE</code> pointer","text":"<p>Reading from a null <code>FILE</code> pointer is undefined behavior and yields a runtime assertion. This can happen when calling <code>std::fopen</code> on a nonexistent file.</p> Example 4: Uninitialized iterator <p>The following code will trigger an assertion at runtime:</p> <pre><code>#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::FILE* f = std::fopen(\"nonexistent_file.json\", \"r\");\n json j = json::parse(f);\n}\n</code></pre> <p>Output:</p> <pre><code>Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.\n</code></pre>"},{"location":"features/binary_values/","title":"Binary Values","text":"<p>The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored.</p> <p>JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.</p>"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"<p>By default, binary values are stored as <code>std::vector<std::uint8_t></code>. This type can be changed by providing a template parameter to the <code>basic_json</code> type. To store binary subtypes, the storage type is extended and exposed as <code>json::binary_t</code>:</p> <pre><code>auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE});\nauto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n</code></pre> <p>There are several convenience functions to check and set the subtype:</p> <pre><code>binary.has_subtype(); // returns false\nbinary_with_subtype.has_subtype(); // returns true\n\nbinary_with_subtype.clear_subtype();\nbinary_with_subtype.has_subtype(); // returns true\n\nbinary_with_subtype.set_subtype(42);\nbinary.set_subtype(23);\n\nbinary.subtype(); // returns 23\n</code></pre> <p>As <code>json::binary_t</code> is subclassing <code>std::vector<std::uint8_t></code>, all member functions are available:</p> <pre><code>binary.size(); // returns 4\nbinary[1]; // returns 0xFE\n</code></pre> <p>JSON values can be constructed from <code>json::binary_t</code>:</p> <pre><code>json j = binary;\n</code></pre> <p>Binary values are primitive values just like numbers or strings:</p> <pre><code>j.is_binary(); // returns true\nj.is_primitive(); // returns true\n</code></pre> <p>Given a binary JSON value, the <code>binary_t</code> can be accessed by reference as via <code>get_binary()</code>:</p> <pre><code>j.get_binary().has_subtype(); // returns true\nj.get_binary().size(); // returns 4\n</code></pre> <p>For convenience, binary JSON values can be constructed via <code>json::binary</code>:</p> <pre><code>auto j2 = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 23);\nauto j3 = json::binary({0xCA, 0xFE, 0xBA, 0xBE});\n\nj2 == j; // returns true\nj3.get_binary().has_subtype(); // returns false\nj3.get_binary().subtype(); // returns std::uint64_t(-1) as j3 has no subtype\n</code></pre>"},{"location":"features/binary_values/#serialization","title":"Serialization","text":"<p>Binary values are serialized differently according to the formats.</p>"},{"location":"features/binary_values/#json","title":"JSON","text":"<p>JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: <code>bytes</code> holds an array of integers, and <code>subtype</code> is an integer or <code>null</code>.</p> Example <p>Code:</p> <pre><code>// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// serialize to standard output\nstd::cout << j.dump(2) << std::endl;\n</code></pre> <p>Output:</p> <pre><code>{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n</code></pre> <p>No roundtrip for binary values</p> <p>The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes.</p>"},{"location":"features/binary_values/#bjdata","title":"BJData","text":"<p>BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.</p> Example <p>Code:</p> <pre><code>// create a binary value of subtype 42 (will be ignored in BJData)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BJData\nauto v = json::to_bjdata(j); \n</code></pre> <p><code>v</code> is a <code>std::vector<std::uint8t></code> with the following 20 elements:</p> <pre><code>0x7B // '{'\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '['\n 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')\n 0x5D // ']'\n0x7D // '}'\n</code></pre> <p>The following code uses the type and size optimization for UBJSON:</p> <pre><code>// convert to UBJSON using the size and type optimization\nauto v = json::to_bjdata(j, true, true);\n</code></pre> <p>The resulting vector has 22 elements; the optimization is not effective for examples with few values:</p> <pre><code>0x7B // '{'\n 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '[' array\n 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers\n 0x23 0x69 0x04 // '#' i 4 number of array elements\n 0xCA 0xFE 0xBA 0xBE // content\n</code></pre> <p>Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing <code>v</code> would yield the following value:</p> <pre><code>{\n \"binary\": [202, 254, 186, 190]\n}\n</code></pre>"},{"location":"features/binary_values/#bson","title":"BSON","text":"<p>BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used.</p> Example <p>Code:</p> <pre><code>// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BSON\nauto v = json::to_bson(j); \n</code></pre> <p><code>v</code> is a <code>std::vector<std::uint8t></code> with the following 22 elements:</p> <pre><code>0x16 0x00 0x00 0x00 // number of bytes in the document\n 0x05 // binary value\n 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte\n 0x04 0x00 0x00 0x00 // number of bytes\n 0x2a // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n0x00 // end of the document\n</code></pre> <p>Note that the serialization preserves the subtype, and deserializing <code>v</code> would yield the following value:</p> <pre><code>{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n</code></pre>"},{"location":"features/binary_values/#cbor","title":"CBOR","text":"<p>CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.</p> Example <p>Code:</p> <pre><code>// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to CBOR\nauto v = json::to_cbor(j); \n</code></pre> <p><code>v</code> is a <code>std::vector<std::uint8t></code> with the following 15 elements:</p> <pre><code>0xA1 // map(1)\n 0x66 // text(6)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0xD8 0x2A // tag(42)\n 0x44 // bytes(4)\n 0xCA 0xFE 0xBA 0xBE // content\n</code></pre> <p>Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless <code>json::cbor_tag_handler_t::ignore</code> or <code>json::cbor_tag_handler_t::store</code> is passed to <code>json::from_cbor</code>.</p> <pre><code>{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": null\n }\n}\n</code></pre>"},{"location":"features/binary_values/#messagepack","title":"MessagePack","text":"<p>MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer.</p> <p>If no subtype is given, the bin family (bin8, bin16, bin32) is used.</p> Example <p>Code:</p> <pre><code>// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to MessagePack\nauto v = json::to_msgpack(j); \n</code></pre> <p><code>v</code> is a <code>std::vector<std::uint8t></code> with the following 14 elements:</p> <pre><code>0x81 // fixmap1\n 0xA6 // fixstr6\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0xD6 // fixext4\n 0x2A // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n</code></pre> <p>Note that the serialization preserves the subtype, and deserializing <code>v</code> would yield the following value:</p> <pre><code>{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n</code></pre>"},{"location":"features/binary_values/#ubjson","title":"UBJSON","text":"<p>UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.</p> Example <p>Code:</p> <pre><code>// create a binary value of subtype 42 (will be ignored in UBJSON)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to UBJSON\nauto v = json::to_ubjson(j); \n</code></pre> <p><code>v</code> is a <code>std::vector<std::uint8t></code> with the following 20 elements:</p> <pre><code>0x7B // '{'\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '['\n 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')\n 0x5D // ']'\n0x7D // '}'\n</code></pre> <p>The following code uses the type and size optimization for UBJSON:</p> <pre><code>// convert to UBJSON using the size and type optimization\nauto v = json::to_ubjson(j, true, true);\n</code></pre> <p>The resulting vector has 23 elements; the optimization is not effective for examples with few values:</p> <pre><code>0x7B // '{'\n 0x24 // '$' type of the object elements\n 0x5B // '[' array\n 0x23 0x69 0x01 // '#' i 1 number of object elements\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers\n 0x23 0x69 0x04 // '#' i 4 number of array elements\n 0xCA 0xFE 0xBA 0xBE // content\n</code></pre> <p>Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing <code>v</code> would yield the following value:</p> <pre><code>{\n \"binary\": [202, 254, 186, 190]\n}\n</code></pre>"},{"location":"features/comments/","title":"Comments","text":"<p>This library does not support comments by default. It does so for three reasons:</p> <ol> <li>Comments are not part of the JSON specification. You may argue that <code>//</code> or <code>/* */</code> are allowed in JavaScript, but JSON is not JavaScript.</li> <li> <p>This was not an oversight: Douglas Crockford wrote on this in May 2012:</p> <pre><code>I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.\n\nSuppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.\n</code></pre> </li> <li> <p>It is dangerous for interoperability if some libraries would add comment support while others don't. Please check The Harmful Consequences of the Robustness Principle on this.</p> </li> </ol> <p>However, you can pass set parameter <code>ignore_comments</code> to <code>true</code> in the parse function to ignore <code>//</code> or <code>/* */</code> comments. Comments will then be treated as whitespace.</p> <p>Example</p> <p>Consider the following JSON with comments.</p> <pre><code>{\n // update in 2006: removed Pluto\n \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n}\n</code></pre> <p>When calling <code>parse</code> without additional argument, a parse error exception is thrown. If <code>ignore_comments</code> is set to <code>true</code>, the comments are ignored during parsing:</p> <pre><code>#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::string s = R\"(\n {\n // update in 2006: removed Pluto\n \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n }\n )\";\n\n try\n {\n json j = json::parse(s);\n }\n catch (json::exception &e)\n {\n std::cout << e.what() << std::endl;\n }\n\n json j = json::parse(s,\n /* callback */ nullptr,\n /* allow exceptions */ true,\n /* ignore_comments */ true);\n std::cout << j.dump(2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.parse_error.101] parse error at line 3, column 9:\nsyntax error while parsing object key - invalid literal;\nlast read: '<U+000A> {<U+000A> /'; expected string literal\n</code></pre> <pre><code>{\n \"planets\": [\n \"Mercury\",\n \"Venus\",\n \"Earth\",\n \"Mars\",\n \"Jupiter\",\n \"Uranus\",\n \"Neptune\"\n ]\n}\n</code></pre>"},{"location":"features/enum_conversion/","title":"Specializing enum conversion","text":"<p>By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.</p> <p>It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:</p> <pre><code>// example enum type declaration\nenum TaskState {\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID=-1,\n};\n\n// map TaskState values to JSON as strings\nNLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {\n {TS_INVALID, nullptr},\n {TS_STOPPED, \"stopped\"},\n {TS_RUNNING, \"running\"},\n {TS_COMPLETED, \"completed\"},\n})\n</code></pre> <p>The <code>NLOHMANN_JSON_SERIALIZE_ENUM()</code> macro declares a set of <code>to_json()</code> / <code>from_json()</code> functions for type <code>TaskState</code> while avoiding repetition and boilerplate serialization code.</p>"},{"location":"features/enum_conversion/#usage","title":"Usage","text":"<pre><code>// enum to JSON as string\njson j = TS_STOPPED;\nassert(j == \"stopped\");\n\n// json string to enum\njson j3 = \"running\";\nassert(j3.template get<TaskState>() == TS_RUNNING);\n\n// undefined json value to enum (where the first map entry above is the default)\njson jPi = 3.14;\nassert(jPi.template get<TaskState>() == TS_INVALID );\n</code></pre>"},{"location":"features/enum_conversion/#notes","title":"Notes","text":"<p>Just as in Arbitrary Type Conversions above,</p> <ul> <li><code>NLOHMANN_JSON_SERIALIZE_ENUM()</code> MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization.</li> <li>It MUST be available (e.g., proper headers must be included) everywhere you use the conversions.</li> </ul> <p>Other Important points:</p> <ul> <li>When using <code>template get<ENUM_TYPE>()</code>, undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.</li> <li>If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.</li> <li>To disable the default serialization of enumerators as integers and force a compiler error instead, see <code>JSON_DISABLE_ENUM_SERIALIZATION</code>.</li> </ul>"},{"location":"features/iterators/","title":"Iterators","text":""},{"location":"features/iterators/#overview","title":"Overview","text":"<p>A <code>basic_json</code> value is a container and allows access via iterators. Depending on the value type, <code>basic_json</code> stores zero or more values.</p> <p>As for other containers, <code>begin()</code> returns an iterator to the first value and <code>end()</code> returns an iterator to the value following the last value. The latter iterator is a placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, <code>begin()</code> will return <code>end()</code>.</p> <p></p>"},{"location":"features/iterators/#iteration-order-for-objects","title":"Iteration order for objects","text":"<p>When iterating over objects, values are ordered with respect to the <code>object_comparator_t</code> type which defaults to <code>std::less</code>. See the types documentation for more information.</p> Example <pre><code>// create JSON object {\"one\": 1, \"two\": 2, \"three\": 3}\njson j;\nj[\"one\"] = 1;\nj[\"two\"] = 2;\nj[\"three\"] = 3;\n\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>1\n3\n2\n</code></pre> <p>The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".</p>"},{"location":"features/iterators/#access-object-key-during-iteration","title":"Access object key during iteration","text":"<p>The JSON iterators have two member functions, <code>key()</code> and <code>value()</code> to access the object key and stored value, respectively. When calling <code>key()</code> on a non-object iterator, an invalid_iterator.207 exception is thrown.</p> Example <pre><code>// create JSON object {\"one\": 1, \"two\": 2, \"three\": 3}\njson j;\nj[\"one\"] = 1;\nj[\"two\"] = 2;\nj[\"three\"] = 3;\n\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << it.key() << \" : \" << it.value() << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>one : 1\nthree : 3\ntwo : 2\n</code></pre>"},{"location":"features/iterators/#range-based-for-loops","title":"Range-based for loops","text":"<p>C++11 allows using range-based for loops to iterate over a container.</p> <pre><code>for (auto it : j_object)\n{\n // \"it\" is of type json::reference and has no key() member\n std::cout << \"value: \" << it << '\\n';\n}\n</code></pre> <p>For this reason, the <code>items()</code> function allows accessing <code>iterator::key()</code> and <code>iterator::value()</code> during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.</p> <pre><code>for (auto& el : j_object.items())\n{\n std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n</code></pre> <p>The items() function also allows using structured bindings (C++17):</p> <pre><code>for (auto& [key, val] : j_object.items())\n{\n std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n</code></pre> <p>Note</p> <p>When iterating over an array, <code>key()</code> will return the index of the element as string. For primitive types (e.g., numbers), <code>key()</code> returns an empty string.</p> <p>Warning</p> <p>Using <code>items()</code> on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.</p>"},{"location":"features/iterators/#reverse-iteration-order","title":"Reverse iteration order","text":"<p><code>rbegin()</code> and <code>rend()</code> return iterators in the reverse sequence.</p> <p></p> Example <pre><code>json j = {1, 2, 3, 4};\n\nfor (auto it = j.rbegin(); it != j.rend(); ++it)\n{\n std::cout << *it << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>4\n3\n2\n1\n</code></pre>"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"<p>Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, <code>*begin()</code> returns the complete string or binary array and is also safe the underlying string or binary array is empty.</p> Example <pre><code>json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>\"Hello, world\"\n</code></pre>"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators <code>clear</code> all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"<p>JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the <code>patch</code> function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.</p> Example <p>The following code shows how a JSON patch is applied to a value.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // apply the patch\n json patched_doc = doc.patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << doc << \"\\n\\n\"\n << std::setw(4) << patched_doc << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n</code></pre>"},{"location":"features/json_patch/#diff","title":"Diff","text":"<p>The library can also calculate a JSON patch (i.e., a diff) given two JSON values.</p> <p>Invariant</p> <p>For two JSON values source and target, the following code yields always true:</p> <pre><code>source.patch(diff(source, target)) == target;\n</code></pre> Example <p>The following code shows how a JSON patch is created as a diff for two JSON values.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the source document\n json source = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the target document\n json target = R\"(\n {\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n }\n )\"_json;\n\n // create the patch\n json patch = json::diff(source, target);\n\n // roundtrip\n json patched_source = source.patch(patch);\n\n // output patch and roundtrip result\n std::cout << std::setw(4) << patch << \"\\n\\n\"\n << std::setw(4) << patched_source << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>[\n {\n \"op\": \"replace\",\n \"path\": \"/baz\",\n \"value\": \"boo\"\n },\n {\n \"op\": \"remove\",\n \"path\": \"/foo\"\n },\n {\n \"op\": \"add\",\n \"path\": \"/hello\",\n \"value\": [\n \"world\"\n ]\n }\n]\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n</code></pre>"},{"location":"features/json_pointer/","title":"JSON Pointer","text":""},{"location":"features/json_pointer/#introduction","title":"Introduction","text":"<p>The library supports JSON Pointer (RFC 6901) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document.</p> <p>Consider the following JSON document</p> <pre><code>{\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n}\n</code></pre> <p>Then every value inside the JSON document can be identified as follows:</p> JSON Pointer JSON value `` <code>{\"array\":[\"A\",\"B\",\"C\"],\"nested\":{\"one\":1,\"two\":2,\"three\":[true,false]}}</code> <code>/array</code> <code>[\"A\",\"B\",\"C\"]</code> <code>/array/0</code> <code>A</code> <code>/array/1</code> <code>B</code> <code>/array/2</code> <code>C</code> <code>/nested</code> <code>{\"one\":1,\"two\":2,\"three\":[true,false]}</code> <code>/nested/one</code> <code>1</code> <code>/nested/two</code> <code>2</code> <code>/nested/three</code> <code>[true,false]</code> <code>/nested/three/0</code> <code>true</code> <code>/nested/three/1</code> <code>false</code> <p>Note <code>/</code> does not identify the root (i.e., the whole document), but an object entry with empty key <code>\"\"</code>. See RFC 6901 for more information.</p>"},{"location":"features/json_pointer/#json-pointer-creation","title":"JSON Pointer creation","text":"<p>JSON Pointers can be created from a string:</p> <pre><code>json::json_pointer p = \"/nested/one\";\n</code></pre> <p>Furthermore, a user-defined string literal can be used to achieve the same result:</p> <pre><code>auto p = \"/nested/one\"_json_pointer;\n</code></pre> <p>The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.</p>"},{"location":"features/json_pointer/#value-access","title":"Value access","text":"<p>JSON Pointers can be used in the <code>at</code>, <code>operator[]</code>, and <code>value</code> functions just like object keys or array indices.</p> <pre><code>// the JSON value from above\nauto j = json::parse(R\"({\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n})\");\n\n// access values\nauto val = j[\"/\"_json_pointer]; // {\"array\":[\"A\",\"B\",\"C\"],...}\nauto val1 = j[\"/nested/one\"_json_pointer]; // 1\nauto val2 = j.at[json::json_pointer(\"/nested/three/1\")]; // false\nauto val3 = j.value[json::json_pointer(\"/nested/four\", 0)]; // 0\n</code></pre>"},{"location":"features/json_pointer/#flatten-unflatten","title":"Flatten / unflatten","text":"<p>The library implements a function <code>flatten</code> to convert any JSON document into a JSON object where each key is a JSON Pointer and each value is a primitive JSON value (i.e., a string, boolean, number, or null).</p> <pre><code>// the JSON value from above\nauto j = json::parse(R\"({\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n})\");\n\n// create flattened value\nauto j_flat = j.flatten();\n</code></pre> <p>The resulting value <code>j_flat</code> is:</p> <pre><code>{\n \"/array/0\": \"A\",\n \"/array/1\": \"B\",\n \"/array/2\": \"C\",\n \"/nested/one\": 1,\n \"/nested/two\": 2,\n \"/nested/three/0\": true,\n \"/nested/three/1\": false\n}\n</code></pre> <p>The reverse function, <code>unflatten</code> recreates the original value.</p> <pre><code>auto j_original = j_flat.unflatten();\n</code></pre>"},{"location":"features/json_pointer/#see-also","title":"See also","text":"<ul> <li>Class <code>json_pointer</code></li> <li>Function <code>flatten</code></li> <li>Function <code>unflatten</code></li> <li>JSON Patch</li> </ul>"},{"location":"features/macros/","title":"Supported Macros","text":"<p>Some aspects of the library can be configured by defining preprocessor macros before including the <code>json.hpp</code> header. See also the API documentation for macros for examples and more information.</p>"},{"location":"features/macros/#json_assertx","title":"<code>JSON_ASSERT(x)</code>","text":"<p>This macro controls which code is executed for runtime assertions of the library.</p> <p>See full documentation of <code>JSON_ASSERT(x)</code>.</p>"},{"location":"features/macros/#json_catch_userexception","title":"<code>JSON_CATCH_USER(exception)</code>","text":"<p>This macro overrides <code>catch</code> calls inside the library.</p> <p>See full documentation of <code>JSON_CATCH_USER(exception)</code>.</p>"},{"location":"features/macros/#json_diagnostics","title":"<code>JSON_DIAGNOSTICS</code>","text":"<p>This macro enables extended diagnostics for exception messages. Possible values are <code>1</code> to enable or <code>0</code> to disable (default).</p> <p>When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.</p> <p>The diagnostics messages can also be controlled with the CMake option <code>JSON_Diagnostics</code> (<code>OFF</code> by default) which sets <code>JSON_DIAGNOSTICS</code> accordingly.</p> <p>See full documentation of <code>JSON_DIAGNOSTICS</code>.</p>"},{"location":"features/macros/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","title":"<code>JSON_HAS_CPP_11</code>, <code>JSON_HAS_CPP_14</code>, <code>JSON_HAS_CPP_17</code>, <code>JSON_HAS_CPP_20</code>","text":"<p>The library targets C++11, but also supports some features introduced in later C++ versions (e.g., <code>std::string_view</code> support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.</p> <p>See full documentation of <code>JSON_HAS_CPP_11</code>, <code>JSON_HAS_CPP_14</code>, <code>JSON_HAS_CPP_17</code>, and <code>JSON_HAS_CPP_20</code>.</p>"},{"location":"features/macros/#json_has_filesystem-json_has_experimental_filesystem","title":"<code>JSON_HAS_FILESYSTEM</code>, <code>JSON_HAS_EXPERIMENTAL_FILESYSTEM</code>","text":"<p>When compiling with C++17, the library provides conversions from and to <code>std::filesystem::path</code>. As compiler support for filesystem is limited, the library tries to detect whether <code><filesystem></code>/<code>std::filesystem</code> (<code>JSON_HAS_FILESYSTEM</code>) or <code><experimental/filesystem></code>/<code>std::experimental::filesystem</code> (<code>JSON_HAS_EXPERIMENTAL_FILESYSTEM</code>) should be used. To override the built-in check, define <code>JSON_HAS_FILESYSTEM</code> or <code>JSON_HAS_EXPERIMENTAL_FILESYSTEM</code> to <code>1</code>.</p> <p>See full documentation of <code>JSON_HAS_FILESYSTEM</code> and <code>JSON_HAS_EXPERIMENTAL_FILESYSTEM</code>.</p>"},{"location":"features/macros/#json_noexception","title":"<code>JSON_NOEXCEPTION</code>","text":"<p>Exceptions can be switched off by defining the symbol <code>JSON_NOEXCEPTION</code>.</p> <p>See full documentation of <code>JSON_NOEXCEPTION</code>.</p>"},{"location":"features/macros/#json_disable_enum_serialization","title":"<code>JSON_DISABLE_ENUM_SERIALIZATION</code>","text":"<p>When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using <code>NLOHMANN_JSON_SERIALIZE_ENUM</code>.</p> <p>See full documentation of <code>JSON_DISABLE_ENUM_SERIALIZATION</code>.</p>"},{"location":"features/macros/#json_no_io","title":"<code>JSON_NO_IO</code>","text":"<p>When defined, headers <code><cstdio></code>, <code><ios></code>, <code><iosfwd></code>, <code><istream></code>, and <code><ostream></code> are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).</p> <p>See full documentation of <code>JSON_NO_IO</code>.</p>"},{"location":"features/macros/#json_skip_library_version_check","title":"<code>JSON_SKIP_LIBRARY_VERSION_CHECK</code>","text":"<p>When defined, the library will not create a compiler warning when a different version of the library was already included.</p> <p>See full documentation of <code>JSON_SKIP_LIBRARY_VERSION_CHECK</code>.</p>"},{"location":"features/macros/#json_skip_unsupported_compiler_check","title":"<code>JSON_SKIP_UNSUPPORTED_COMPILER_CHECK</code>","text":"<p>When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.</p> <p>See full documentation of <code>JSON_SKIP_UNSUPPORTED_COMPILER_CHECK</code>.</p>"},{"location":"features/macros/#json_throw_userexception","title":"<code>JSON_THROW_USER(exception)</code>","text":"<p>This macro overrides <code>throw</code> calls inside the library. The argument is the exception to be thrown.</p> <p>See full documentation of <code>JSON_THROW_USER(exception)</code>.</p>"},{"location":"features/macros/#json_try_user","title":"<code>JSON_TRY_USER</code>","text":"<p>This macro overrides <code>try</code> calls inside the library.</p> <p>See full documentation of <code>JSON_TRY_USER</code>.</p>"},{"location":"features/macros/#json_use_implicit_conversions","title":"<code>JSON_USE_IMPLICIT_CONVERSIONS</code>","text":"<p>When defined to <code>0</code>, implicit conversions are switched off. By default, implicit conversions are switched on.</p> <p>See full documentation of <code>JSON_USE_IMPLICIT_CONVERSIONS</code>.</p>"},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","title":"<code>NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)</code>","text":"<p>This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.</p> <p>The macro is to be defined inside the class/struct to create code for. Unlike <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code>, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.</p> <p>See full documentation of <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code>.</p>"},{"location":"features/macros/#nlohmann_define_type_intrusive_with_defaulttype-member","title":"<code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)</code>","text":"<p>This macro is similar to <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code>. It will not throw an exception in <code>from_json()</code> due to a missing value in the JSON object, but can throw due to a mismatched type. The <code>from_json()</code> function default constructs an object and uses its values as the defaults when calling the <code>value</code> function.</p> <p>See full documentation of <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT</code>.</p>"},{"location":"features/macros/#nlohmann_define_type_intrusive_only_serializetype-member","title":"<code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...)</code>","text":"<p>This macro is similar to <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> except that it defines only the serialization code. This is useful when the user type does not have a default constructor and only the serialization is required.</p> <p>See full documentation of <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE</code>.</p>"},{"location":"features/macros/#nlohmann_define_type_non_intrusivetype-member","title":"<code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)</code>","text":"<p>This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.</p> <p>The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use <code>NLOHMANN_DEFINE_TYPE_INTRUSIVE</code> in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members.</p> <p>See full documentation of <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code>.</p>"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_with_defaulttype-member","title":"<code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)</code>","text":"<p>This macro is similar to <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code>. It will not throw an exception in <code>from_json()</code> due to a missing value in the JSON object, but can throw due to a mismatched type. The <code>from_json()</code> function default constructs an object and uses its values as the defaults when calling the <code>value</code> function.</p> <p>See full documentation of <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT</code>.</p>"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_only_serializetype-member","title":"<code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...)</code>","text":"<p>This macro is similar to <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE</code> except that it defines only the serialization code. This is useful when the user type does not have a default constructor and only the serialization is required.</p> <p>See full documentation of <code>NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE</code>.</p>"},{"location":"features/macros/#nlohmann_json_serialize_enumtype","title":"<code>NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)</code>","text":"<p>This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information.</p> <p>See full documentation of <code>NLOHMANN_JSON_SERIALIZE_ENUM</code>.</p>"},{"location":"features/macros/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","title":"<code>NLOHMANN_JSON_VERSION_MAJOR</code>, <code>NLOHMANN_JSON_VERSION_MINOR</code>, <code>NLOHMANN_JSON_VERSION_PATCH</code>","text":"<p>These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.</p> <p>See full documentation of <code>NLOHMANN_JSON_VERSION_MAJOR</code>, <code>NLOHMANN_JSON_VERSION_MINOR</code>, and <code>NLOHMANN_JSON_VERSION_PATCH</code>.</p>"},{"location":"features/merge_patch/","title":"JSON Merge Patch","text":"<p>The library supports JSON Merge Patch (RFC 7386) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.</p> <p>Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.</p> Example <p>The following code shows how a JSON Merge Patch is applied to a JSON document.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n</code></pre>"},{"location":"features/namespace/","title":"<code>nlohmann</code> Namespace","text":"<p>The 3.11.0 release introduced an inline namespace to allow different parts of a codebase to safely use different versions of the JSON library as long as they never exchange instances of library types.</p>"},{"location":"features/namespace/#structure","title":"Structure","text":"<p>The complete default namespace name is derived as follows:</p> <ul> <li>The root namespace is always <code>nlohmann</code>.</li> <li>The inline namespace starts with <code>json_abi</code> and is followed by serveral optional ABI tags according to the value of these ABI-affecting macros, in order:<ul> <li><code>JSON_DIAGNOSTICS</code> defined non-zero appends <code>_diag</code>.</li> <li><code>JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON</code> defined non-zero appends <code>_ldvcmp</code>.</li> </ul> </li> <li>The inline namespace ends with the suffix <code>_v</code> followed by the 3 components of the version number separated by underscores. To omit the version component, see Disabling the version component below.</li> </ul> <p>For example, the namespace name for version 3.11.2 with <code>JSON_DIAGNOSTICS</code> defined to <code>1</code> is:</p> <pre><code>nlohmann::json_abi_diag_v3_11_2\n</code></pre>"},{"location":"features/namespace/#purpose","title":"Purpose","text":"<p>Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of <code>JSON_DIAGNOSTICS</code>. This is illustrated in the diagram below.</p> <p></p> <p>In releases prior to 3.11.0, mixing any version of the JSON library with different <code>JSON_DIAGNOSTICS</code> settings would result in a crashing application. If <code>some_library</code> never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.</p>"},{"location":"features/namespace/#limitations","title":"Limitations","text":"<p>Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types.</p> <p>There is an exception when forward declarations are used (i.e., when including <code>json_fwd.hpp</code>) in which case the linker may complain about undefined references.</p>"},{"location":"features/namespace/#disabling-the-version-component","title":"Disabling the version component","text":"<p>Different versions are not necessarily ABI-incompatible, but the project does not actively track changes in the ABI and recommends that all parts of a codebase exchanging library types be built with the same version. Users can, at their own risk, disable the version component of the linline namespace, allowing different versions \u2013 but not configurations \u2013 to be used in cases where the linker would otherwise output undefined reference errors.</p> <p>To do so, define <code>NLOHMANN_JSON_NAMESPACE_NO_VERSION</code> to <code>1</code>.</p> <p>This applies to version 3.11.2 and above only, versions 3.11.0 and 3.11.1 can apply the technique described in the next section to emulate the effect of the <code>NLOHMANN_JSON_NAMESPACE_NO_VERSION</code> macro.</p> <p>Use at your own risk</p> <p>Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!</p>"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"<p>When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining <code>NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END</code> as follows:</p> <pre><code>#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {\n#define NLOHMANN_JSON_NAMESPACE_END }\n</code></pre> <p>Use at your own risk</p> <p>Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!</p>"},{"location":"features/namespace/#version-history","title":"Version history","text":"<ul> <li>Introduced inline namespace (<code>json_v3_11_0[_abi-tag]*</code>) in version 3.11.0.</li> <li>Changed structure of inline namespace in version 3.11.2.</li> </ul>"},{"location":"features/object_order/","title":"Object Order","text":"<p>The JSON standard defines objects as \"an unordered collection of zero or more name/value pairs\". As such, an implementation does not need to preserve any specific order of object keys.</p>"},{"location":"features/object_order/#default-behavior-sort-keys","title":"Default behavior: sort keys","text":"<p>The default type <code>nlohmann::json</code> uses a <code>std::map</code> to store JSON objects, and thus stores object keys sorted alphabetically.</p> Example <pre><code>#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n</code></pre>"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","title":"Alternative behavior: preserve insertion order","text":"<p>If you do want to preserve the insertion order, you can try the type <code>nlohmann::ordered_json</code>.</p> Example <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing ordered_json = nlohmann::ordered_json;\n\nint main()\n{\n ordered_json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n</code></pre> <p>Alternatively, you can use a more sophisticated ordered map like <code>tsl::ordered_map</code> (integration) or <code>nlohmann::fifo_map</code> (integration).</p>"},{"location":"features/object_order/#notes-on-parsing","title":"Notes on parsing","text":"<p>Note that you also need to call the right <code>parse</code> function when reading from a file. Assume file <code>input.json</code> contains the JSON object above:</p> <pre><code>{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n</code></pre> <p>Right way</p> <p>The following code correctly calls the <code>parse</code> function from <code>nlohmann::ordered_json</code>:</p> <pre><code>std::ifstream i(\"input.json\");\nauto j = nlohmann::ordered_json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n</code></pre> <p>The output will be:</p> <pre><code>{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n</code></pre> Wrong way <p>The following code incorrectly calls the <code>parse</code> function from <code>nlohmann::json</code> which does not preserve the insertion order, but sorts object keys. Assigning the result to <code>nlohmann::ordered_json</code> compiles, but does not restore the order from the input file.</p> <pre><code>std::ifstream i(\"input.json\");\nnlohmann::ordered_json j = nlohmann::json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n</code></pre> <p>The output will be:</p> <pre><code>{\n \"one\": 1,\n \"three\": 3\n \"two\": 2,\n}\n</code></pre>"},{"location":"features/binary_formats/","title":"Binary Formats","text":"<p>Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports</p> <ul> <li>BJData (Binary JData),</li> <li>BSON (Binary JSON),</li> <li>CBOR (Concise Binary Object Representation),</li> <li>MessagePack, and</li> <li>UBJSON (Universal Binary JSON)</li> </ul> <p>to efficiently encode JSON values to byte vectors and to decode such vectors.</p>"},{"location":"features/binary_formats/#comparison","title":"Comparison","text":""},{"location":"features/binary_formats/#completeness","title":"Completeness","text":"Format Serialization Deserialization BJData complete complete BSON incomplete: top-level value must be an object incomplete, but all JSON types are supported CBOR complete incomplete, but all JSON types are supported MessagePack complete complete UBJSON complete complete"},{"location":"features/binary_formats/#binary-values","title":"Binary values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported <p>See binary values for more information.</p>"},{"location":"features/binary_formats/#sizes","title":"Sizes","text":"Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 % <p>Sizes compared to minified JSON value.</p>"},{"location":"features/binary_formats/bjdata/","title":"BJData","text":"<p>The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays (ND-arrays); it also adds 4 new type markers - <code>[u] - uint16</code>, <code>[m] - uint32</code>, <code>[M] - uint64</code> and <code>[h] - float16</code> - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms.</p> <p>Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable. This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing.</p> <p>References</p> <ul> <li>BJData Specification</li> </ul>"},{"location":"features/binary_formats/bjdata/#serialization","title":"Serialization","text":"<p>The library uses the following mapping from JSON values types to BJData types according to the BJData specification:</p> JSON value type value/range BJData type marker null <code>null</code> null <code>Z</code> boolean <code>true</code> true <code>T</code> boolean <code>false</code> false <code>F</code> number_integer -9223372036854775808..-2147483649 int64 <code>L</code> number_integer -2147483648..-32769 int32 <code>l</code> number_integer -32768..-129 int16 <code>I</code> number_integer -128..127 int8 <code>i</code> number_integer 128..255 uint8 <code>U</code> number_integer 256..32767 int16 <code>I</code> number_integer 32768..65535 uint16 <code>u</code> number_integer 65536..2147483647 int32 <code>l</code> number_integer 2147483648..4294967295 uint32 <code>m</code> number_integer 4294967296..9223372036854775807 int64 <code>L</code> number_integer 9223372036854775808..18446744073709551615 uint64 <code>M</code> number_unsigned 0..127 int8 <code>i</code> number_unsigned 128..255 uint8 <code>U</code> number_unsigned 256..32767 int16 <code>I</code> number_unsigned 32768..65535 uint16 <code>u</code> number_unsigned 65536..2147483647 int32 <code>l</code> number_unsigned 2147483648..4294967295 uint32 <code>m</code> number_unsigned 4294967296..9223372036854775807 int64 <code>L</code> number_unsigned 9223372036854775808..18446744073709551615 uint64 <code>M</code> number_float any value float64 <code>D</code> string with shortest length indicator string <code>S</code> array see notes on optimized format/ND-array array <code>[</code> object see notes on optimized format map <code>{</code> <p>Complete mapping</p> <p>The mapping is complete in the sense that any JSON value type can be converted to a BJData value.</p> <p>Any BJData output created by <code>to_bjdata</code> can be successfully parsed by <code>from_bjdata</code>.</p> <p>Size constraints</p> <p>The following values can not be converted to a BJData value:</p> <ul> <li>strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 bytes (theoretical)</li> </ul> <p>Unused BJData markers</p> <p>The following markers are not used in the conversion:</p> <ul> <li><code>Z</code>: no-op values are not created.</li> <li><code>C</code>: single-byte strings are serialized with <code>S</code> markers.</li> </ul> <p>NaN/infinity handling</p> <p>If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the <code>dump()</code> function which serializes NaN or Infinity to <code>null</code>.</p> <p>Endianness</p> <p>A breaking difference between BJData and UBJSON is the endianness of numerical values. In BJData, all numerical data types (integers <code>UiuImlML</code> and floating-point values <code>hdD</code>) are stored in the little-endian (LE) byte order as opposed to big-endian as used by UBJSON. Adopting LE to store numeric records avoids unnecessary byte swapping on most modern computers where LE is used as the default byte order.</p> <p>Optimized formats</p> <p>Optimized formats for containers are supported via two parameters of <code>to_bjdata</code>:</p> <ul> <li>Parameter <code>use_size</code> adds size information to the beginning of a container and removes the closing marker.</li> <li>Parameter <code>use_type</code> further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The <code>use_type</code> parameter must only be used together with <code>use_size = true</code>.</li> </ul> <p>Note that <code>use_size = true</code> alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed of the number of elements in the container.</p> <p>ND-array optimized format</p> <p>BJData extends UBJSON's optimized array size marker to support ND-arrays of uniform numerical data types (referred to as packed arrays). For example, the 2-D <code>uint8</code> integer array <code>[[1,2],[3,4],[5,6]]</code>, stored as nested optimized array in UBJSON <code>[ [$U#i2 1 2 [$U#i2 3 4 [$U#i2 5 6 ]</code>, can be further compressed in BJData to <code>[$U#[$i#i2 2 3 1 2 3 4 5 6</code> or <code>[$U#[i2 i3] 1 2 3 4 5 6</code>.</p> <p>To maintain type and size information, ND-arrays are converted to JSON objects following the annotated array format (defined in the JData specification (Draft 3)), when parsed using <code>from_bjdata</code>. For example, the above 2-D <code>uint8</code> array can be parsed and accessed as</p> <pre><code>{\n \"_ArrayType_\": \"uint8\",\n \"_ArraySize_\": [2,3],\n \"_ArrayData_\": [1,2,3,4,5,6]\n}\n</code></pre> <p>Likewise, when a JSON object in the above form is serialzed using <code>to_bjdata</code>, it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in <code>\"_ArraySize_\"</code> contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated.</p> <p>The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array.</p> <p>Restrictions in optimized data types for arrays and objects</p> <p>Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the <code>$</code> marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of <code>UiuImlMLhdDC</code>. This also means other variable (<code>[{SH</code>) or zero-length types (<code>TFN</code>) can not be used in an optimized array or object in BJData.</p> <p>Binary values</p> <p>If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print BJData's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to BJData\n std::vector<std::uint8_t> v = json::to_bjdata(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to BJData using default representation\n std::vector<std::uint8_t> v_array = json::to_bjdata(array);\n // serialize it to BJData using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);\n // serialize it to BJData using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n</code></pre>"},{"location":"features/binary_formats/bjdata/#deserialization","title":"Deserialization","text":"<p>The library maps BJData types to JSON value types as follows:</p> BJData type JSON value type marker no-op no value, next value is read <code>N</code> null <code>null</code> <code>Z</code> false <code>false</code> <code>F</code> true <code>true</code> <code>T</code> float16 number_float <code>h</code> float32 number_float <code>d</code> float64 number_float <code>D</code> uint8 number_unsigned <code>U</code> int8 number_integer <code>i</code> uint16 number_unsigned <code>u</code> int16 number_integer <code>I</code> uint32 number_unsigned <code>m</code> int32 number_integer <code>l</code> uint64 number_unsigned <code>M</code> int64 number_integer <code>L</code> string string <code>S</code> char string <code>C</code> array array (optimized values are supported) <code>[</code> ND-array object (in JData annotated array format) <code>[$.#[.</code> object object (optimized values are supported) <code>{</code> <p>Complete mapping</p> <p>The mapping is complete in the sense that any BJData value can be converted to a JSON value.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with BJData\n json j = json::from_bjdata(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"features/binary_formats/bson/","title":"BSON","text":"<p>BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type.</p> <p>References</p> <ul> <li>BSON Website - the main source on BSON</li> <li>BSON Specification - the specification</li> </ul>"},{"location":"features/binary_formats/bson/#serialization","title":"Serialization","text":"<p>The library uses the following mapping from JSON values types to BSON types:</p> JSON value type value/range BSON type marker null <code>null</code> null 0x0A boolean <code>true</code>, <code>false</code> boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 <p>Incomplete mapping</p> <p>The mapping is incomplete, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector<std::uint8_t> v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 \n</code></pre>"},{"location":"features/binary_formats/bson/#deserialization","title":"Deserialization","text":"<p>The library maps BSON record types to JSON value types as follows:</p> BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported <p>Incomplete mapping</p> <p>The mapping is incomplete. The unsupported mappings are indicated in the table above.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d,\n 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73,\n 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00\n };\n\n // deserialize it with BSON\n json j = json::from_bson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"features/binary_formats/cbor/","title":"CBOR","text":"<p>The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation.</p> <p>References</p> <ul> <li>CBOR Website - the main source on CBOR</li> <li>CBOR Playground - an interactive webpage to translate between JSON and CBOR</li> <li>RFC 7049 - the CBOR specification</li> </ul>"},{"location":"features/binary_formats/cbor/#serialization","title":"Serialization","text":"<p>The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049):</p> JSON value type value/range CBOR type first byte null <code>null</code> Null 0xF6 boolean <code>true</code> True 0xF5 boolean <code>false</code> False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length: 0..23 UTF-8 string 0x60..0x77 string length: 23..255 UTF-8 string (1 byte follow) 0x78 string length: 256..65535 UTF-8 string (2 bytes follow) 0x79 string length: 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length: 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size: 0..23 array 0x80..0x97 array size: 23..255 array (1 byte follow) 0x98 array size: 256..65535 array (2 bytes follow) 0x99 array size: 65536..4294967295 array (4 bytes follow) 0x9A array size: 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size: 0..23 map 0xA0..0xB7 object size: 23..255 map (1 byte follow) 0xB8 object size: 256..65535 map (2 bytes follow) 0xB9 object size: 65536..4294967295 map (4 bytes follow) 0xBA object size: 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size: 0..23 byte string 0x40..0x57 binary size: 23..255 byte string (1 byte follow) 0x58 binary size: 256..65535 byte string (2 bytes follow) 0x59 binary size: 65536..4294967295 byte string (4 bytes follow) 0x5A binary size: 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B <p>Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above.</p> <p>Complete mapping</p> <p>The mapping is complete in the sense that any JSON value type can be converted to a CBOR value.</p> <p>NaN/infinity handling</p> <p>If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to <code>null</code>.</p> <p>Unused CBOR types</p> <p>The following CBOR types are not used in the conversion:</p> <ul> <li>UTF-8 strings terminated by \"break\" (0x7F)</li> <li>arrays terminated by \"break\" (0x9F)</li> <li>maps terminated by \"break\" (0xBF)</li> <li>byte strings terminated by \"break\" (0x5F)</li> <li>date/time (0xC0..0xC1)</li> <li>bignum (0xC2..0xC3)</li> <li>decimal fraction (0xC4)</li> <li>bigfloat (0xC5)</li> <li>expected conversions (0xD5..0xD7)</li> <li>simple values (0xE0..0xF3, 0xF8)</li> <li>undefined (0xF7)</li> <li>half-precision floats (0xF9)</li> <li>break (0xFF)</li> </ul> <p>Tagged items</p> <p>Binary subtypes will be serialized as tagged items. See binary values for an example.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to CBOR\n std::vector<std::uint8_t> v = json::to_cbor(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n</code></pre>"},{"location":"features/binary_formats/cbor/#deserialization","title":"Deserialization","text":"<p>The library maps CBOR types to JSON value types as follows:</p> CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF False <code>false</code> 0xF4 True <code>true</code> 0xF5 Null <code>null</code> 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB <p>Incomplete mapping</p> <p>The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors:</p> <ul> <li>date/time (0xC0..0xC1)</li> <li>bignum (0xC2..0xC3)</li> <li>decimal fraction (0xC4)</li> <li>bigfloat (0xC5)</li> <li>expected conversions (0xD5..0xD7)</li> <li>simple values (0xE0..0xF3, 0xF8)</li> <li>undefined (0xF7)</li> </ul> <p>Object keys</p> <p>CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected.</p> <p>Tagged items</p> <p>Tagged items will throw a parse error by default. They can be ignored by passing <code>cbor_tag_handler_t::ignore</code> to function <code>from_cbor</code>. They can be stored by passing <code>cbor_tag_handler_t::store</code> to function <code>from_cbor</code>.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with CBOR\n json j = json::from_cbor(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"features/binary_formats/messagepack/","title":"MessagePack","text":"<p>MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.</p> <p>References</p> <ul> <li>MessagePack website</li> <li>MessagePack specification</li> </ul>"},{"location":"features/binary_formats/messagepack/#serialization","title":"Serialization","text":"<p>The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification:</p> JSON value type value/range MessagePack type first byte null <code>null</code> nil 0xC0 boolean <code>true</code> true 0xC3 boolean <code>false</code> false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length: 0..31 fixstr 0xA0..0xBF string length: 32..255 str 8 0xD9 string length: 256..65535 str 16 0xDA string length: 65536..4294967295 str 32 0xDB array size: 0..15 fixarray 0x90..0x9F array size: 16..65535 array 16 0xDC array size: 65536..4294967295 array 32 0xDD object size: 0..15 fix map 0x80..0x8F object size: 16..65535 map 16 0xDE object size: 65536..4294967295 map 32 0xDF binary size: 0..255 bin 8 0xC4 binary size: 256..65535 bin 16 0xC5 binary size: 65536..4294967295 bin 32 0xC6 <p>Complete mapping</p> <p>The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value.</p> <p>Any MessagePack output created by <code>to_msgpack</code> can be successfully parsed by <code>from_msgpack</code>.</p> <p>Size constraints</p> <p>The following values can not be converted to a MessagePack value:</p> <ul> <li>strings with more than 4294967295 bytes</li> <li>byte strings with more than 4294967295 bytes</li> <li>arrays with more than 4294967295 elements</li> <li>objects with more than 4294967295 elements</li> </ul> <p>NaN/infinity handling</p> <p>If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the dump function which serializes NaN or Infinity to <code>null</code>.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n</code></pre>"},{"location":"features/binary_formats/messagepack/#deserialization","title":"Deserialization","text":"<p>The library maps MessagePack types to JSON value types as follows:</p> MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nil <code>null</code> 0xC0 false <code>false</code> 0xC2 true <code>true</code> 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF <p>Info</p> <p>Any MessagePack output created by <code>to_msgpack</code> can be successfully parsed by <code>from_msgpack</code>.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"features/binary_formats/ubjson/","title":"UBJSON","text":"<p>Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON.</p> <p>References</p> <ul> <li>UBJSON Website</li> </ul>"},{"location":"features/binary_formats/ubjson/#serialization","title":"Serialization","text":"<p>The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:</p> JSON value type value/range UBJSON type marker null <code>null</code> null <code>Z</code> boolean <code>true</code> true <code>T</code> boolean <code>false</code> false <code>F</code> number_integer -9223372036854775808..-2147483649 int64 <code>L</code> number_integer -2147483648..-32769 int32 <code>l</code> number_integer -32768..-129 int16 <code>I</code> number_integer -128..127 int8 <code>i</code> number_integer 128..255 uint8 <code>U</code> number_integer 256..32767 int16 <code>I</code> number_integer 32768..2147483647 int32 <code>l</code> number_integer 2147483648..9223372036854775807 int64 <code>L</code> number_unsigned 0..127 int8 <code>i</code> number_unsigned 128..255 uint8 <code>U</code> number_unsigned 256..32767 int16 <code>I</code> number_unsigned 32768..2147483647 int32 <code>l</code> number_unsigned 2147483648..9223372036854775807 int64 <code>L</code> number_unsigned 2147483649..18446744073709551615 high-precision <code>H</code> number_float any value float64 <code>D</code> string with shortest length indicator string <code>S</code> array see notes on optimized format array <code>[</code> object see notes on optimized format map <code>{</code> <p>Complete mapping</p> <p>The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.</p> <p>Any UBJSON output created by <code>to_ubjson</code> can be successfully parsed by <code>from_ubjson</code>.</p> <p>Size constraints</p> <p>The following values can not be converted to a UBJSON value:</p> <ul> <li>strings with more than 9223372036854775807 bytes (theoretical)</li> </ul> <p>Unused UBJSON markers</p> <p>The following markers are not used in the conversion:</p> <ul> <li><code>Z</code>: no-op values are not created.</li> <li><code>C</code>: single-byte strings are serialized with <code>S</code> markers.</li> </ul> <p>NaN/infinity handling</p> <p>If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the <code>dump()</code> function which serializes NaN or Infinity to <code>null</code>.</p> <p>Optimized formats</p> <p>The optimized formats for containers are supported: Parameter <code>use_size</code> adds size information to the beginning of a container and removes the closing marker. Parameter <code>use_type</code> further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The <code>use_type</code> parameter must only be used together with <code>use_size = true</code>.</p> <p>Note that <code>use_size = true</code> alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container.</p> <p>Binary values</p> <p>If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON documentation. In particular, this means that serialization and the deserialization of a JSON containing binary values into UBJSON and back will result in a different JSON object.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print UBJSON's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to UBJSON\n std::vector<std::uint8_t> v = json::to_ubjson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to UBJSON using default representation\n std::vector<std::uint8_t> v_array = json::to_ubjson(array);\n // serialize it to UBJSON using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);\n // serialize it to UBJSON using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n</code></pre>"},{"location":"features/binary_formats/ubjson/#deserialization","title":"Deserialization","text":"<p>The library maps UBJSON types to JSON value types as follows:</p> UBJSON type JSON value type marker no-op no value, next value is read <code>N</code> null <code>null</code> <code>Z</code> false <code>false</code> <code>F</code> true <code>true</code> <code>T</code> float32 number_float <code>d</code> float64 number_float <code>D</code> uint8 number_unsigned <code>U</code> int8 number_integer <code>i</code> int16 number_integer <code>I</code> int32 number_integer <code>l</code> int64 number_integer <code>L</code> string string <code>S</code> char string <code>C</code> array array (optimized values are supported) <code>[</code> object object (optimized values are supported) <code>{</code> <p>Complete mapping</p> <p>The mapping is complete in the sense that any UBJSON value can be converted to a JSON value.</p> Example <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with UBJSON\n json j = json::from_ubjson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"compact\": true,\n \"schema\": 0\n}\n</code></pre>"},{"location":"features/element_access/","title":"Element Access","text":"<p>There are many ways elements in a JSON value can be accessed:</p> <ul> <li>unchecked access via <code>operator[]</code></li> <li>checked access via <code>at</code></li> <li>access with default value via <code>value</code></li> <li>iterators</li> <li>JSON pointers</li> </ul>"},{"location":"features/element_access/checked_access/","title":"Checked access: at","text":""},{"location":"features/element_access/checked_access/#overview","title":"Overview","text":"<p>The <code>at</code> member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a <code>basic_json::out_of_range</code> exception otherwise.</p> Read access <p>Consider the following JSON value:</p> <pre><code>{\n \"name\": \"Mary Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n</code></pre> <p>Assume the value is parsed to a <code>json</code> variable <code>j</code>.</p> expression value <code>j</code> <code>{\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]}</code> <code>j.at(\"name\")</code> <code>\"Mary Smith\"</code> <code>j.at(\"age\")</code> <code>42</code> <code>j.at(\"hobbies\")</code> <code>[\"hiking\", \"reading\"]</code> <code>j.at(\"hobbies\").at(0)</code> <code>\"hiking\"</code> <code>j.at(\"hobbies\").at(1)</code> <code>\"reading\"</code> <p>The return value is a reference, so it can be modified by the original value.</p> Write access <pre><code>j.at(\"name\") = \"John Smith\";\n</code></pre> <p>This code produces the following JSON value:</p> <pre><code>{\n \"name\": \"John Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n</code></pre> <p>When accessing an invalid index (i.e., an index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown.</p> Accessing via invalid index or missing key <pre><code>j.at(\"hobbies\").at(3) = \"cooking\";\n</code></pre> <p>This code produces the following exception:</p> <pre><code>[json.exception.out_of_range.401] array index 3 is out of range\n</code></pre> <p>When you extended diagnostic messages are enabled by defining <code>JSON_DIAGNOSTICS</code>, the exception further gives information where the key or index is missing or out of range.</p> <pre><code>[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n</code></pre>"},{"location":"features/element_access/checked_access/#notes","title":"Notes","text":"<p>Exceptions</p> <ul> <li><code>at</code> can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a <code>basic_json::type_error</code> is thrown.</li> <li><code>basic_json::out_of_range</code> exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid.</li> </ul>"},{"location":"features/element_access/checked_access/#summary","title":"Summary","text":"scenario non-const value const value access to existing object key reference to existing value is returned const reference to existing value is returned access to valid array index reference to existing value is returned const reference to existing value is returned access to non-existing object key <code>basic_json::out_of_range</code> exception is thrown <code>basic_json::out_of_range</code> exception is thrown access to invalid array index <code>basic_json::out_of_range</code> exception is thrown <code>basic_json::out_of_range</code> exception is thrown"},{"location":"features/element_access/default_value/","title":"Access with default value: value","text":""},{"location":"features/element_access/default_value/#overview","title":"Overview","text":"<p>In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present.</p> Example <p>Consider the following JSON value:</p> <pre><code>{\n \"logOutput\": \"result.log\",\n \"append\": true\n}\n</code></pre> <p>Assume the value is parsed to a <code>json</code> variable <code>j</code>.</p> expression value <code>j</code> <code>{\"logOutput\": \"result.log\", \"append\": true}</code> <code>j.value(\"logOutput\", \"logfile.log\")</code> <code>\"result.log\"</code> <code>j.value(\"append\", true)</code> <code>true</code> <code>j.value(\"append\", false)</code> <code>true</code> <code>j.value(\"logLevel\", \"verbose\")</code> <code>\"verbose\"</code>"},{"location":"features/element_access/default_value/#note","title":"Note","text":"<p>Exceptions</p> <ul> <li><code>value</code> can only be used with objects. For other types, a <code>basic_json::type_error</code> is thrown.</li> </ul>"},{"location":"features/element_access/unchecked_access/","title":"Unchecked access: operator[]","text":""},{"location":"features/element_access/unchecked_access/#overview","title":"Overview","text":"<p>Elements in a JSON object and a JSON array can be accessed via <code>operator[]</code> similar to a <code>std::map</code> and a <code>std::vector</code>, respectively.</p> Read access <p>Consider the following JSON value:</p> <pre><code>{\n \"name\": \"Mary Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n</code></pre> <p>Assume the value is parsed to a <code>json</code> variable <code>j</code>.</p> expression value <code>j</code> <code>{\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]}</code> <code>j[\"name\"]</code> <code>\"Mary Smith\"</code> <code>j[\"age\"]</code> <code>42</code> <code>j[\"hobbies\"]</code> <code>[\"hiking\", \"reading\"]</code> <code>j[\"hobbies\"][0]</code> <code>\"hiking\"</code> <code>j[\"hobbies\"][1]</code> <code>\"reading\"</code> <p>The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a <code>null</code> value is inserted which can be immediately be overwritten.</p> Write access <pre><code>j[\"name\"] = \"John Smith\";\nj[\"maidenName\"] = \"Jones\";\n</code></pre> <p>This code produces the following JSON value:</p> <pre><code>{\n \"name\": \"John Smith\",\n \"maidenName\": \"Jones\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n</code></pre> <p>When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with <code>null</code>.</p> Filling up arrays with <code>null</code> values <pre><code>j[\"hobbies\"][0] = \"running\";\nj[\"hobbies\"][3] = \"cooking\";\n</code></pre> <p>This code produces the following JSON value:</p> <pre><code>{\n \"name\": \"John Smith\",\n \"maidenName\": \"Jones\",\n \"age\": 42,\n \"hobbies\": [\"running\", \"reading\", null, \"cooking\"]\n}\n</code></pre>"},{"location":"features/element_access/unchecked_access/#notes","title":"Notes","text":"<p>Design rationale</p> <p>The library behaves differently to <code>std::vector</code> and <code>std::map</code>:</p> <ul> <li><code>std::vector::operator[]</code> never inserts a new element.</li> <li><code>std::map::operator[]</code> is not available for const values.</li> </ul> <p>The type <code>json</code> wraps all JSON value types. It would be impossible to remove <code>operator[]</code> for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward <code>insert</code> calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.</p> <p>Info</p> <p>The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.</p> <p>Danger</p> <ul> <li>It is undefined behavior to access a const object with a non-existing key.</li> <li>It is undefined behavior to access a const array with an invalid index.</li> <li>In debug mode, an assertion will fire in both cases. You can disable assertions by defining the preprocessor symbol <code>NDEBUG</code> or redefine the macro <code>JSON_ASSERT(x)</code>. See the documentation on runtime assertions for more information.</li> </ul> <p>Exceptions</p> <p><code>operator[]</code> can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a <code>basic_json::type_error</code> is thrown.</p>"},{"location":"features/element_access/unchecked_access/#summary","title":"Summary","text":"scenario non-const value const value access to existing object key reference to existing value is returned const reference to existing value is returned access to valid array index reference to existing value is returned const reference to existing value is returned access to non-existing object key reference to newly inserted <code>null</code> value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted <code>null</code> value is returned; any index between previous maximal index and passed index are filled with <code>null</code> undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"<p>Note</p> <p>This page is under construction.</p>"},{"location":"features/parsing/#input","title":"Input","text":""},{"location":"features/parsing/#sax-vs-dom-parsing","title":"SAX vs. DOM parsing","text":""},{"location":"features/parsing/#exceptions","title":"Exceptions","text":"<p>See parsing and exceptions.</p>"},{"location":"features/parsing/json_lines/","title":"JSON Lines","text":"<p>The JSON Lines format is a text format of newline-delimited JSON. In particular:</p> <ol> <li>The input must be UTF-8 encoded.</li> <li>Every line must be a valid JSON value.</li> <li>The line separator must be <code>\\n</code>. As <code>\\r</code> is silently ignored, <code>\\r\\n</code> is also supported.</li> <li>The final character may be <code>\\n</code>, but is not required to be one.</li> </ol> <p>JSON Text example</p> <pre><code>{\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]}\n{\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]}\n{\"name\": \"May\", \"wins\": []}\n{\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]}\n</code></pre> <p>JSON Lines input with more than one value is treated as invalid JSON by the <code>parse</code> or <code>accept</code> functions. To process it line by line, functions like <code>std::getline</code> can be used:</p> <p>Example: Parse JSON Text input line by line</p> <p>The example below demonstrates how JSON Lines can be processed.</p> <pre><code>#include <sstream>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // JSON Lines (see https://jsonlines.org)\n std::stringstream input;\n input << R\"({\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]}\n{\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]}\n{\"name\": \"May\", \"wins\": []}\n{\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]}\n)\";\n\n std::string line;\n while (std::getline(input, line))\n {\n std::cout << json::parse(line) << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>{\"name\":\"Gilbert\",\"wins\":[[\"straight\",\"7\u2663\"],[\"one pair\",\"10\u2665\"]]}\n{\"name\":\"Alexa\",\"wins\":[[\"two pair\",\"4\u2660\"],[\"two pair\",\"9\u2660\"]]}\n{\"name\":\"May\",\"wins\":[]}\n{\"name\":\"Deloise\",\"wins\":[[\"three of a kind\",\"5\u2663\"]]}\n</code></pre> <p>Note</p> <p>Using <code>operator>></code> like</p> <pre><code>json j;\nwhile (input >> j)\n{\n std::cout << j << std::endl;\n}\n</code></pre> <p>with a JSON Lines input does not work, because the parser will try to parse one value after the last one.</p>"},{"location":"features/parsing/parse_exceptions/","title":"Parsing and Exceptions","text":"<p>When the input is not valid JSON, an exception of type <code>parse_error</code> is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions. In case you process untrusted input, always enclose your code with a <code>try</code>/<code>catch</code> block, like</p> <pre><code>json j;\ntry\n{\n j = json::parse(my_input);\n}\ncatch (json::parse_error& ex)\n{\n std::cerr << \"parse error at byte \" << ex.byte << std::endl;\n}\n</code></pre> <p>In case exceptions are undesired or not supported by the environment, there are different ways to proceed:</p>"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"<p>The <code>parse()</code> function accepts a <code>bool</code> parameter <code>allow_exceptions</code> which controls whether an exception is thrown when a parse error occurs (<code>true</code>, default) or whether a discarded value should be returned (<code>false</code>).</p> <pre><code>json j = json::parse(my_input, nullptr, false);\nif (j.is_discarded())\n{\n std::cerr << \"parse error\" << std::endl;\n}\n</code></pre> <p>Note there is no diagnostic information available in this scenario.</p>"},{"location":"features/parsing/parse_exceptions/#use-accept-function","title":"Use accept() function","text":"<p>Alternatively, function <code>accept()</code> can be used which does not return a <code>json</code> value, but a <code>bool</code> indicating whether the input is valid JSON.</p> <pre><code>if (!json::accept(my_input))\n{\n std::cerr << \"parse error\" << std::endl;\n}\n</code></pre> <p>Again, there is no diagnostic information available.</p>"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","title":"User-defined SAX interface","text":"<p>Finally, you can implement the SAX interface and decide what should happen in case of a parse error.</p> <p>This function has the following interface:</p> <pre><code>bool parse_error(std::size_t position,\n const std::string& last_token,\n const json::exception& ex);\n</code></pre> <p>The return value indicates whether the parsing should continue, so the function should usually return <code>false</code>.</p> Example <pre><code>#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nclass sax_no_exception : public nlohmann::detail::json_sax_dom_parser<json>\n{\n public:\n sax_no_exception(json& j)\n : nlohmann::detail::json_sax_dom_parser<json>(j, false)\n {}\n\n bool parse_error(std::size_t position,\n const std::string& last_token,\n const json::exception& ex)\n {\n std::cerr << \"parse error at input byte \" << position << \"\\n\"\n << ex.what() << \"\\n\"\n << \"last read: \\\"\" << last_token << \"\\\"\"\n << std::endl;\n return false;\n }\n};\n\nint main()\n{\n std::string myinput = \"[1,2,3,]\";\n\n json result;\n sax_no_exception sax(result);\n\n bool parse_result = json::sax_parse(myinput, &sax);\n if (!parse_result)\n {\n std::cerr << \"parsing unsuccessful!\" << std::endl;\n }\n\n std::cout << \"parsed value: \" << result << std::endl;\n}\n</code></pre> <p>Output:</p> <pre><code>parse error at input byte 8\n[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nlast read: \"3,]\"\nparsing unsuccessful!\nparsed value: [1,2,3]\n</code></pre>"},{"location":"features/parsing/parser_callbacks/","title":"Parser Callbacks","text":""},{"location":"features/parsing/parser_callbacks/#overview","title":"Overview","text":"<p>With a parser callback function, the result of parsing a JSON text can be influenced. When passed to <code>parse</code>, it is called on certain events (passed as <code>parse_event_t</code> via parameter <code>event</code>) with a set recursion depth <code>depth</code> and context JSON value <code>parsed</code>. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.</p> <p>The type of the callback function is:</p> <pre><code>template<typename BasicJsonType>\nusing parser_callback_t =\n std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n</code></pre>"},{"location":"features/parsing/parser_callbacks/#callback-event-types","title":"Callback event types","text":"<p>We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters <code>depth</code>, <code>event</code>, and <code>parsed</code>.</p> parameter <code>event</code> description parameter <code>depth</code> parameter <code>parsed</code> <code>parse_event_t::object_start</code> the parser read <code>{</code> and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded <code>parse_event_t::key</code> the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key <code>parse_event_t::object_end</code> the parser read <code>}</code> and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object <code>parse_event_t::array_start</code> the parser read <code>[</code> and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded <code>parse_event_t::array_end</code> the parser read <code>]</code> and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array <code>parse_event_t::value</code> the parser finished reading a JSON value depth of the value the parsed JSON value Example <p>When parsing the following JSON text,</p> <pre><code>{\n \"name\": \"Berlin\",\n \"location\": [\n 52.519444,\n 13.406667\n ]\n}\n</code></pre> <p>these calls are made to the callback function:</p> event depth parsed <code>object_start</code> 0 discarded <code>key</code> 1 <code>\"name\"</code> <code>value</code> 1 <code>\"Berlin\"</code> <code>key</code> 1 <code>\"location\"</code> <code>array_start</code> 1 discarded <code>value</code> 2 <code>52.519444</code> <code>value</code> 2 <code>13.406667</code> <code>array_end</code> 1 <code>[52.519444,13.406667]</code> <code>object_end</code> 0 <code>{\"location\":[52.519444,13.406667],\"name\":\"Berlin\"}</code>"},{"location":"features/parsing/parser_callbacks/#return-value","title":"Return value","text":"<p>Discarding a value (i.e., returning <code>false</code>) has different effects depending on the context in which the function was called:</p> <ul> <li>Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read.</li> <li>In case a value outside a structured type is skipped, it is replaced with <code>null</code>. This case happens if the top-level element is skipped.</li> </ul> Example <p>The example below demonstrates the <code>parse()</code> function with and without callback function.</p> <pre><code>#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n</code></pre> <p>Output:</p> <pre><code>{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n</code></pre>"},{"location":"features/parsing/sax_interface/","title":"SAX Interface","text":"<p>The library uses a SAX-like interface with the following functions:</p> <p></p> <pre><code>// called when null is parsed\nbool null();\n\n// called when a boolean is parsed; value is passed\nbool boolean(bool val);\n\n// called when a signed or unsigned integer number is parsed; value is passed\nbool number_integer(number_integer_t val);\nbool number_unsigned(number_unsigned_t val);\n\n// called when a floating-point number is parsed; value and original string is passed\nbool number_float(number_float_t val, const string_t& s);\n\n// called when a string is parsed; value is passed and can be safely moved away\nbool string(string_t& val);\n// called when a binary value is parsed; value is passed and can be safely moved away\nbool binary(binary& val);\n\n// called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)\nbool start_object(std::size_t elements);\nbool end_object();\nbool start_array(std::size_t elements);\nbool end_array();\n// called when an object key is parsed; value is passed and can be safely moved away\nbool key(string_t& val);\n\n// called when a parse error occurs; byte position, the last token, and an exception is passed\nbool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex);\n</code></pre> <p>The return value of each function determines whether parsing should proceed.</p> <p>To implement your own SAX handler, proceed as follows:</p> <ol> <li>Implement the SAX interface in a class. You can use class <code>nlohmann::json_sax<json></code> as base class, but you can also use any class where the functions described above are implemented and public.</li> <li>Create an object of your SAX interface class, e.g. <code>my_sax</code>.</li> <li>Call <code>bool json::sax_parse(input, &my_sax);</code> where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.</li> </ol> <p>Note the <code>sax_parse</code> function only returns a <code>bool</code> indicating the result of the last executed SAX event. It does not return <code>json</code> value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error - it is up to you what to do with the exception object passed to your <code>parse_error</code> implementation. Internally, the SAX interface is used for the DOM parser (class <code>json_sax_dom_parser</code>) as well as the acceptor (<code>json_sax_acceptor</code>), see file <code>json_sax.hpp</code>.</p>"},{"location":"features/parsing/sax_interface/#see-also","title":"See also","text":"<ul> <li>json_sax - documentation of the SAX interface</li> <li>sax_parse - SAX parser</li> </ul>"},{"location":"features/types/","title":"Types","text":"<p>This page gives an overview how JSON values are stored and how this can be configured.</p>"},{"location":"features/types/#overview","title":"Overview","text":"<p>By default, JSON values are stored as follows:</p> JSON type C++ type object <code>std::map<std::string, basic_json></code> array <code>std::vector<basic_json></code> null <code>std::nullptr_t</code> string <code>std::string</code> boolean <code>bool</code> number <code>std::int64_t</code>, <code>std::uint64_t</code>, and <code>double</code> <p>Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.</p>"},{"location":"features/types/#storage","title":"Storage","text":""},{"location":"features/types/#template-arguments","title":"Template arguments","text":"<p>The data types to store a JSON value are derived from the template arguments passed to class <code>basic_json</code>:</p> <pre><code>template<\n template<typename U, typename V, typename... Args> class ObjectType = std::map,\n template<typename U, typename... Args> class ArrayType = std::vector,\n class StringType = std::string,\n class BooleanType = bool,\n class NumberIntegerType = std::int64_t,\n class NumberUnsignedType = std::uint64_t,\n class NumberFloatType = double,\n template<typename U> class AllocatorType = std::allocator,\n template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,\n class BinaryType = std::vector<std::uint8_t>\n>\nclass basic_json;\n</code></pre> <p>Type <code>json</code> is an alias for <code>basic_json<></code> and uses the default types.</p> <p>From the template arguments, the following types are derived:</p> <pre><code>using object_comparator_t = std::less<>;\nusing object_t = ObjectType<StringType, basic_json, object_comparator_t,\n AllocatorType<std::pair<const StringType, basic_json>>>;\n\nusing array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n\nusing string_t = StringType;\n\nusing boolean_t = BooleanType;\n\nusing number_integer_t = NumberIntegerType;\nusing number_unsigned_t = NumberUnsignedType;\nusing number_float_t = NumberFloatType;\n\nusing binary_t = nlohmann::byte_container_with_subtype<BinaryType>;\n</code></pre>"},{"location":"features/types/#objects","title":"Objects","text":"<p>RFC 8259 describes JSON objects as follows:</p> <p>An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.</p>"},{"location":"features/types/#default-type","title":"Default type","text":"<p>With the default values for ObjectType (<code>std::map</code>), StringType (<code>std::string</code>), and AllocatorType (<code>std::allocator</code>), the default value for <code>object_t</code> is:</p> <pre><code>std::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n</code></pre>"},{"location":"features/types/#behavior","title":"Behavior","text":"<p>The choice of <code>object_t</code> influences the behavior of the JSON class. With the default type, objects have the following behavior:</p> <ul> <li>When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.</li> <li>When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, <code>{\"key\": 2, \"key\": 1}</code> could be equal to either <code>{\"key\": 1}</code> or <code>{\"key\": 2}</code>.</li> <li>Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see <code>dump</code>) in this order. For instance, both <code>{\"b\": 1, \"a\": 2}</code> and <code>{\"a\": 2, \"b\": 1}</code> will be stored and serialized as <code>{\"a\": 2, \"b\": 1}</code>.</li> <li>When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, <code>{\"b\": 1, \"a\": 2}</code> and <code>{\"a\": 2, \"b\": 1}</code> will be treated as equal.</li> </ul>"},{"location":"features/types/#key-order","title":"Key order","text":"<p>The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as <code>std::map</code> with <code>std::less</code> is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.</p>"},{"location":"features/types/#limits","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the maximum depth of nesting.</p> <p>In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the <code>max_size</code> function of a JSON object.</p>"},{"location":"features/types/#storage_1","title":"Storage","text":"<p>Objects are stored as pointers in a <code>basic_json</code> type. That is, for any access to object values, a pointer of type <code>object_t*</code> must be dereferenced.</p>"},{"location":"features/types/#arrays","title":"Arrays","text":"<p>RFC 8259 describes JSON arrays as follows:</p> <p>An array is an ordered sequence of zero or more values.</p>"},{"location":"features/types/#default-type_1","title":"Default type","text":"<p>With the default values for ArrayType (<code>std::vector</code>) and AllocatorType (<code>std::allocator</code>), the default value for <code>array_t</code> is:</p> <pre><code>std::vector<\n basic_json, // value_type\n std::allocator<basic_json> // allocator_type\n>\n</code></pre>"},{"location":"features/types/#limits_1","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the maximum depth of nesting.</p> <p>In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the <code>max_size</code> function of a JSON array.</p>"},{"location":"features/types/#storage_2","title":"Storage","text":"<p>Arrays are stored as pointers in a <code>basic_json</code> type. That is, for any access to array values, a pointer of type <code>array_t*</code> must be dereferenced.</p>"},{"location":"features/types/#strings","title":"Strings","text":"<p>RFC 8259 describes JSON strings as follows:</p> <p>A string is a sequence of zero or more Unicode characters.</p> <p>Unicode values are split by the JSON class into byte-sized characters during deserialization.</p>"},{"location":"features/types/#default-type_2","title":"Default type","text":"<p>With the default values for StringType (<code>std::string</code>), the default value for <code>string_t</code> is <code>std::string</code>.</p>"},{"location":"features/types/#encoding","title":"Encoding","text":"<p>Strings are stored in UTF-8 encoding. Therefore, functions like <code>std::string::size()</code> or <code>std::string::length()</code> return the number of bytes in the string rather than the number of characters or glyphs.</p>"},{"location":"features/types/#string-comparison","title":"String comparison","text":"<p>RFC 8259 states:</p> <p>Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that <code>\"a\\\\b\"</code> and <code>\"a\\u005Cb\"</code> are not equal.</p> <p>This implementation is interoperable as it does compare strings code unit by code unit.</p>"},{"location":"features/types/#storage_3","title":"Storage","text":"<p>String values are stored as pointers in a <code>basic_json</code> type. That is, for any access to string values, a pointer of type <code>string_t*</code> must be dereferenced.</p>"},{"location":"features/types/#booleans","title":"Booleans","text":"<p>RFC 8259 implicitly describes a boolean as a type which differentiates the two literals <code>true</code> and <code>false</code>.</p>"},{"location":"features/types/#default-type_3","title":"Default type","text":"<p>With the default values for BooleanType (<code>bool</code>), the default value for <code>boolean_t</code> is <code>bool</code>.</p>"},{"location":"features/types/#storage_4","title":"Storage","text":"<p>Boolean values are stored directly inside a <code>basic_json</code> type.</p>"},{"location":"features/types/#numbers","title":"Numbers","text":"<p>See the number handling article for a detailed discussion on how numbers are handled by this library.</p> <p>RFC 8259 describes numbers as follows:</p> <p>The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.</p> <p>This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, <code>number_integer_t</code>, <code>number_unsigned_t</code>, and <code>number_float_t</code> are used.</p>"},{"location":"features/types/#default-types","title":"Default types","text":"<p>With the default values for NumberIntegerType (<code>std::int64_t</code>), the default value for <code>number_integer_t</code> is <code>std::int64_t</code>. With the default values for NumberUnsignedType (<code>std::uint64_t</code>), the default value for <code>number_unsigned_t</code> is <code>std::uint64_t</code>. With the default values for NumberFloatType (<code>double</code>), the default value for <code>number_float_t</code> is <code>double</code>.</p>"},{"location":"features/types/#default-behavior","title":"Default behavior","text":"<ul> <li>The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal <code>010</code> will be serialized to <code>8</code>. During deserialization, leading zeros yield an error.</li> <li>Not-a-number (NaN) values will be serialized to <code>null</code>.</li> </ul>"},{"location":"features/types/#limits_2","title":"Limits","text":"<p>RFC 8259 specifies:</p> <p>An implementation may set limits on the range and precision of numbers.</p> <p>When the default type is used, the maximal integer number that can be stored is <code>9223372036854775807</code> (<code>INT64_MAX</code>) and the minimal integer number that can be stored is <code>-9223372036854775808</code> (<code>INT64_MIN</code>). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as <code>number_unsigned_t</code> or <code>number_float_t</code>.</p> <p>When the default type is used, the maximal unsigned integer number that can be stored is <code>18446744073709551615</code> (<code>UINT64_MAX</code>) and the minimal integer number that can be stored is <code>0</code>. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as <code>number_integer_t</code> or <code>number_float_t</code>.</p> <p>RFC 8259 further states:</p> <p>Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.</p> <p>As this range is a subrange of the exactly supported range [<code>INT64_MIN</code>, <code>INT64_MAX</code>], this class's integer type is interoperable.</p> <p>RFC 8259 states:</p> <p>This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.</p> <p>This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than <code>-1.79769313486232e+308</code> and values greater than <code>1.79769313486232e+308</code> will be stored as NaN internally and be serialized to <code>null</code>.</p>"},{"location":"features/types/#storage_5","title":"Storage","text":"<p>Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a <code>basic_json</code> type.</p>"},{"location":"features/types/number_handling/","title":"Number Handling","text":"<p>This document describes how the library is handling numbers.</p>"},{"location":"features/types/number_handling/#background","title":"Background","text":"<p>This section briefly summarizes how the JSON specification describes how numbers should be handled.</p>"},{"location":"features/types/number_handling/#json-number-syntax","title":"JSON number syntax","text":"<p>JSON defines the syntax of numbers as follows:</p> <p>RFC 8259, Section 6</p> <p>The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed.</p> <p>A fraction part is a decimal point followed by one or more digits.</p> <p>An exponent part begins with the letter E in uppercase or lowercase, which may be followed by a plus or minus sign. The E and optional sign are followed by one or more digits.</p> <p>The following railroad diagram from json.org visualizes the number syntax:</p> <p></p>"},{"location":"features/types/number_handling/#number-interoperability","title":"Number interoperability","text":"<p>On number interoperability, the following remarks are made:</p> <p>RFC 8259, Section 6</p> <p>This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available.</p> <p>Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.</p>"},{"location":"features/types/number_handling/#library-implementation","title":"Library implementation","text":"<p>This section describes how the above number specification is implemented by this library.</p>"},{"location":"features/types/number_handling/#number-storage","title":"Number storage","text":"<p>In the default <code>json</code> type, numbers are stored as <code>std::uint64_t</code>, <code>std::int64_t</code>, and <code>double</code>, respectively. Thereby, <code>std::uint64_t</code> and <code>std::int64_t</code> are used only if they can store the number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as <code>double</code>.</p> <p>Notes</p> <ul> <li>Numbers with a decimal digit or scientific notation are always stored as <code>double</code>.</li> <li>The number types can be changed, see Template number types. </li> <li>As of version 3.9.1, the conversion is realized by <code>std::strtoull</code>, <code>std::strtoll</code>, and <code>std::strtod</code>, respectively.</li> </ul> <p>Examples</p> <ul> <li>Integer <code>-12345678912345789123456789</code> is smaller than <code>INT64_MIN</code> and will be stored as floating-point number <code>-1.2345678912345788e+25</code>.</li> <li>Integer <code>1E3</code> will be stored as floating-point number <code>1000.0</code>.</li> </ul>"},{"location":"features/types/number_handling/#number-limits","title":"Number limits","text":"<ul> <li>Any 64-bit signed or unsigned integer can be stored without loss of precision.</li> <li>Numbers exceeding the limits of <code>double</code> (i.e., numbers that after conversion via <code>std::strtod</code> are not satisfying <code>std::isfinite</code> such as <code>1E400</code>) will throw exception <code>json.exception.out_of_range.406</code> during parsing.</li> <li>Floating-point numbers are rounded to the next number representable as <code>double</code>. For instance <code>3.141592653589793238462643383279</code> is stored as <code>0x400921fb54442d18</code>. This is the same behavior as the code <code>double x = 3.141592653589793238462643383279;</code>.</li> </ul> <p>Interoperability</p> <ul> <li>The library interoperable with respect to the specification, because its supported range [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1].</li> <li>All integers outside the range [-2^{63}, 2^{64}-1], as well as floating-point numbers are stored as <code>double</code>. This also concurs with the specification above.</li> </ul>"},{"location":"features/types/number_handling/#zeros","title":"Zeros","text":"<p>The JSON number grammar allows for different ways to express zero, and this library will store zeros differently:</p> Literal Stored value and type Serialization <code>0</code> <code>std::uint64_t(0)</code> <code>0</code> <code>-0</code> <code>std::int64_t(0)</code> <code>0</code> <code>0.0</code> <code>double(0.0)</code> <code>0.0</code> <code>-0.0</code> <code>double(-0.0)</code> <code>-0.0</code> <code>0E0</code> <code>double(0.0)</code> <code>0.0</code> <code>-0E0</code> <code>double(-0.0)</code> <code>-0.0</code> <p>That is, <code>-0</code> is stored as a signed integer, but the serialization does not reproduce the <code>-</code>.</p>"},{"location":"features/types/number_handling/#number-serialization","title":"Number serialization","text":"<ul> <li>Integer numbers are serialized as is; that is, no scientific notation is used.</li> <li>Floating-point numbers are serialized as specified by the <code>%g</code> printf modifier with <code>std::numeric_limits<double>::max_digits10</code> significant digits. The rationale is to use the shortest representation while still allow round-tripping.</li> </ul> <p>Notes regarding precision of floating-point numbers</p> <p>As described above, floating-point numbers are rounded to the nearest double and serialized with the shortest representation to allow round-tripping. This can yield confusing examples:</p> <ul> <li>The serialization can have fewer decimal places than the input: <code>2555.5599999999999</code> will be serialized as <code>2555.56</code>. The reverse can also be true.</li> <li>The serialization can be in scientific notation even if the input is not: <code>0.0000972439793401814</code> will be serialized as <code>9.72439793401814e-05</code>. The reverse can also be true: <code>12345E-5</code> will be serialized as <code>0.12345</code>.</li> <li>Conversions from <code>float</code> to <code>double</code> can also introduce rounding errors: <pre><code>float f = 0.3;\njson j = f;\nstd::cout << j << '\\n';\n</code></pre> yields <code>0.30000001192092896</code>.</li> </ul> <p>All examples here can be reproduced by passing the original double value to</p> <pre><code>std::printf(\"%.*g\\n\", std::numeric_limits<double>::max_digits10, double_value);\n</code></pre>"},{"location":"features/types/number_handling/#nan-handling","title":"NaN handling","text":"<p>NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded:</p> <p>RFC 8259, Section 6</p> <p>Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.</p> <p>That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment.</p> <p>This library serializes NaN values as <code>null</code>. This corresponds to the behavior of JavaScript's <code>JSON.stringify</code> function.</p> <p>Example</p> <p>The following example shows how a NaN value is stored in a <code>json</code> value.</p> <pre><code>int main()\n{\n double val = std::numeric_limits<double>::quiet_NaN();\n std::cout << \"val=\" << val << std::endl;\n json j = val;\n std::cout << \"j=\" << j.dump() << std::endl;\n val = j;\n std::cout << \"val=\" << val << std::endl;\n}\n</code></pre> <p>output:</p> <pre><code>val=nan\nj=null\nval=nan\n</code></pre>"},{"location":"features/types/number_handling/#number-comparison","title":"Number comparison","text":"<p>Floating-point inside JSON values numbers are compared with <code>json::number_float_t::operator==</code> which is <code>double::operator==</code> by default.</p> <p>Alternative comparison functions</p> <p>To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance</p> <p><pre><code>template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\ninline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n{\n return std::abs(a - b) <= epsilon;\n}\n</code></pre> Or you can self-define an operator equal function like this:</p> <pre><code>bool my_equal(const_reference lhs, const_reference rhs)\n{\n const auto lhs_type lhs.type();\n const auto rhs_type rhs.type();\n if (lhs_type == rhs_type)\n {\n switch(lhs_type)\n {\n // self_defined case\n case value_t::number_float:\n return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();\n\n // other cases remain the same with the original\n ...\n }\n }\n ...\n}\n</code></pre> <p>(see #703 for more information.)</p> <p>Note</p> <p>NaN values never compare equal to themselves or to other NaN values. See #514.</p>"},{"location":"features/types/number_handling/#number-conversion","title":"Number conversion","text":"<p>Just like the C++ language itself, the <code>get</code> family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising.</p> <p>Unconditional number conversions</p> <pre><code>double d = 42.3; // non-integer double value 42.3\njson jd = d; // stores double value 42.3\nstd::int64_t i = jd.template get<std::int64_t>(); // now i==42; no warning or error is produced\n</code></pre> <p>Note the last line with throw a <code>json.exception.type_error.302</code> exception if <code>jd</code> is not a numerical type, for instance a string.</p> <p>The rationale is twofold:</p> <ol> <li>JSON does not define a number type or precision (see above).</li> <li>C++ also allows to silently convert between number types.</li> </ol> <p>Conditional number conversion</p> <p>The code above can be solved by explicitly checking the nature of the value with members such as <code>is_number_integer()</code> or <code>is_number_unsigned()</code>:</p> <pre><code>// check if jd is really integer-valued\nif (jd.is_number_integer())\n{\n // if so, do the conversion and use i\n std::int64_t i = jd.template get<std::int64_t>();\n // ...\n}\nelse\n{\n // otherwise, take appropriate action\n // ...\n}\n</code></pre> <p>Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.</p> <p>(Example taken from #777.)</p>"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"<p>As the example in Number conversion shows, there are different functions to determine the type of the stored number:</p> <ul> <li><code>is_number()</code> returns <code>true</code> for any number type</li> <li><code>is_number_integer()</code> returns <code>true</code> for signed and unsigned integers</li> <li><code>is_number_unsigned()</code> returns <code>true</code> for unsigned integers only</li> <li><code>is_number_float()</code> returns <code>true</code> for floating-point numbers</li> <li><code>type_name()</code> returns <code>\"number\"</code> for any number type</li> <li><code>type()</code> returns a different enumerator of <code>value_t</code> for all number types</li> </ul> function unsigned integer signed integer floating-point string <code>is_number()</code> <code>true</code> <code>true</code> <code>true</code> <code>false</code> <code>is_number_integer()</code> <code>true</code> <code>true</code> <code>false</code> <code>false</code> <code>is_number_unsigned()</code> <code>true</code> <code>false</code> <code>false</code> <code>false</code> <code>is_number_float()</code> <code>false</code> <code>false</code> <code>true</code> <code>false</code> <code>type_name()</code> <code>\"number\"</code> <code>\"number\"</code> <code>\"number\"</code> <code>\"string\"</code> <code>type()</code> <code>number_unsigned</code> <code>number_integer</code> <code>number_float</code> <code>string</code>"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"<p>The number types can be changed with template parameters.</p> position number type default type possible values 5 signed integers <code>std::int64_t</code> <code>std::int32_t</code>, <code>std::int16_t</code>, etc. 6 unsigned integers <code>std::uint64_t</code> <code>std::uint32_t</code>, <code>std::uint16_t</code>, etc. 7 floating-point <code>double</code> <code>float</code>, <code>long double</code> <p>Constraints on number types</p> <ul> <li>The type for signed integers must be convertible from <code>long long</code>. The type for floating-point numbers is used in case of overflow.</li> <li>The type for unsigned integers must be convertible from <code>unsigned long long</code>. The type for floating-point numbers is used in case of overflow.</li> <li>The types for signed and unsigned integers must be distinct, see #2573.</li> <li>Only <code>double</code>, <code>float</code>, and <code>long double</code> are supported for floating-point numbers.</li> </ul> <p>Example</p> <p>A <code>basic_json</code> type that uses <code>long double</code> as floating-point type.</p> <pre><code>using json_ld = nlohmann::basic_json<std::map, std::vector, std::string, bool,\n std::int64_t, std::uint64_t, long double>;\n</code></pre> <p>Note values should then be parsed with <code>json_ld::parse</code> rather than <code>json::parse</code> as the latter would parse floating-point values to <code>double</code> before then converting them to <code>long double</code>.</p>"},{"location":"home/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"home/code_of_conduct/#our-pledge","title":"Our Pledge","text":"<p>In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.</p>"},{"location":"home/code_of_conduct/#our-standards","title":"Our Standards","text":"<p>Examples of behavior that contributes to creating a positive environment include:</p> <ul> <li>Using welcoming and inclusive language</li> <li>Being respectful of differing viewpoints and experiences</li> <li>Gracefully accepting constructive criticism</li> <li>Focusing on what is best for the community</li> <li>Showing empathy towards other community members</li> </ul> <p>Examples of unacceptable behavior by participants include:</p> <ul> <li>The use of sexualized language or imagery and unwelcome sexual attention or advances</li> <li>Trolling, insulting/derogatory comments, and personal or political attacks</li> <li>Public or private harassment</li> <li>Publishing others' private information, such as a physical or electronic address, without explicit permission</li> <li>Other conduct which could reasonably be considered inappropriate in a professional setting</li> </ul>"},{"location":"home/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"<p>Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.</p> <p>Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.</p>"},{"location":"home/code_of_conduct/#scope","title":"Scope","text":"<p>This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.</p>"},{"location":"home/code_of_conduct/#enforcement","title":"Enforcement","text":"<p>Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.</p> <p>Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.</p>"},{"location":"home/code_of_conduct/#attribution","title":"Attribution","text":"<p>This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4</p>"},{"location":"home/design_goals/","title":"Design goals","text":"<p>There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:</p> <ul> <li> <p>Intuitive syntax. In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code. Check out the examples below, and you'll know what I mean.</p> </li> <li> <p>Trivial integration. Our whole code consists of a single header file <code>json.hpp</code>. That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings.</p> </li> <li> <p>Serious testing. Our class is heavily unit-tested and covers 100% of the code, including all exceptional behavior. Furthermore, we checked with Valgrind and the Clang Sanitizers that there are no memory leaks. Google OSS-Fuzz additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the Core Infrastructure Initiative (CII) best practices.</p> </li> </ul> <p>Other aspects were not so important to us:</p> <ul> <li> <p>Memory efficiency. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C++ data types: <code>std::string</code> for strings, <code>int64_t</code>, <code>uint64_t</code> or <code>double</code> for numbers, <code>std::map</code> for objects, <code>std::vector</code> for arrays, and <code>bool</code> for Booleans. However, you can template the generalized class <code>basic_json</code> to your needs.</p> </li> <li> <p>Speed. There are certainly faster JSON libraries out there. However, if your goal is to speed up your development by adding JSON support with a single header, then this library is the way to go. If you know how to use a <code>std::vector</code> or <code>std::map</code>, you are already set.</p> </li> </ul> <p>See the contribution guidelines for more information.</p>"},{"location":"home/exceptions/","title":"Exceptions","text":""},{"location":"home/exceptions/#overview","title":"Overview","text":""},{"location":"home/exceptions/#base-type","title":"Base type","text":"<p>All exceptions inherit from class <code>json::exception</code> (which in turn inherits from <code>std::exception</code>). It is used as the base class for all exceptions thrown by the <code>basic_json</code> class. This class can hence be used as \"wildcard\" to catch exceptions.</p> <p></p>"},{"location":"home/exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"<p>Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag <code>-fno-exceptions</code> or by defining the symbol <code>JSON_NOEXCEPTION</code>. In this case, exceptions are replaced by <code>abort()</code> calls. You can further control this behavior by defining <code>JSON_THROW_USER</code> (overriding <code>throw</code>), <code>JSON_TRY_USER</code> (overriding <code>try</code>), and <code>JSON_CATCH_USER</code> (overriding <code>catch</code>).</p> <p>Note that <code>JSON_THROW_USER</code> should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.</p> Example <p>The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.</p> <pre><code>#include <iostream>\n\n#define JSON_TRY_USER if(true)\n#define JSON_CATCH_USER(exception) if(false)\n#define JSON_THROW_USER(exception) \\\n {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\\n << \" (function \" << __FUNCTION__ << \") - \" \\\n << (exception).what() << std::endl; \\\n std::abort();}\n\n#include <nlohmann/json.hpp>\n</code></pre> <p>Note the explanatory <code>what()</code> string of exceptions is not available for MSVC if exceptions are disabled, see #2824.</p> <p>See documentation of <code>JSON_TRY_USER</code>, <code>JSON_CATCH_USER</code> and <code>JSON_THROW_USER</code> for more information.</p>"},{"location":"home/exceptions/#extended-diagnostic-messages","title":"Extended diagnostic messages","text":"<p>Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult.</p> Example <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.type_error.302] type must be number, but is string\n</code></pre> <p>This exception can be hard to debug if storing the value <code>\"12\"</code> and accessing it is further apart.</p> <p>To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer.</p> <p>As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol <code>JSON_DIAGNOSTICS</code> to <code>1</code> before including <code>json.hpp</code>.</p> Example <pre><code>#include <iostream>\n\n# define JSON_DIAGNOSTICS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n</code></pre> <p>Output:</p> <pre><code>[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n</code></pre> <p>Now the exception message contains a JSON Pointer <code>/address/housenumber</code> that indicates which value has the wrong type.</p> <p>See documentation of <code>JSON_DIAGNOSTICS</code> for more information.</p>"},{"location":"home/exceptions/#parse-errors","title":"Parse errors","text":"<p>This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.</p> <p>Exceptions have ids 1xx.</p> <p>Byte index</p> <p>Member <code>byte</code> holds the byte index of the last read character in the input file.</p> <p>For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).</p> Example <p>The following code shows how a <code>parse_error</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // parsing input with a syntax error\n json::parse(\"[1,2,3,]\");\n }\n catch (const json::parse_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << '\\n'\n << \"byte position of error: \" << e.byte << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nexception id: 101\nbyte position of error: 8\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionparse_error101","title":"json.exception.parse_error.101","text":"<p>This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member <code>byte</code> indicates the error position.</p> <p>Example message</p> <p>Input ended prematurely:</p> <pre><code>[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal\n</code></pre> <p>No input:</p> <pre><code>[json.exception.parse_error.101] parse error at line 1, column 1: attempting to parse an empty input; check that your input string or stream contains the expected JSON\n</code></pre> <p>Control character was not escaped:</p> <pre><code>[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\\\; last read: '\"<U+0009>'\"\n</code></pre> <p>String was not closed:</p> <pre><code>[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '\"'\n</code></pre> <p>Invalid number format:</p> <pre><code>[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'\n</code></pre> <p><code>\\u</code> was not be followed by four hex digits:</p> <pre><code>[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\\u' must be followed by 4 hex digits; last read: '\"\\u01\"'\n</code></pre> <p>Invalid UTF-8 surrogate pair:</p> <pre><code>[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uD7FF\\uDC00'\"\n</code></pre> <p>Invalid UTF-8 byte:</p> <pre><code>[json.exception.parse_error.101] parse error at line 3, column 24: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '\"vous \\352t'\n</code></pre> <p>Tip</p> <ul> <li>Make sure the input is correctly read. Try to write the input to standard output to check if, for instance, the input file was successfully opened.</li> <li>Paste the input to a JSON validator like http://jsonlint.com or a tool like jq.</li> </ul>"},{"location":"home/exceptions/#jsonexceptionparse_error102","title":"json.exception.parse_error.102","text":"<p>JSON uses the <code>\\uxxxx</code> format to describe Unicode characters. Code points above 0xFFFF are split into two <code>\\uxxxx</code> entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.</p> <p>Example message</p> <pre><code>parse error at 14: missing or wrong low surrogate\n</code></pre> <p>Note</p> <p>This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.</p>"},{"location":"home/exceptions/#jsonexceptionparse_error103","title":"json.exception.parse_error.103","text":"<p>Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.</p> <p>Example message</p> <pre><code>parse error: code points above 0x10FFFF are invalid\n</code></pre> <p>Note</p> <p>This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.</p>"},{"location":"home/exceptions/#jsonexceptionparse_error104","title":"json.exception.parse_error.104","text":"<p>RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.</p> <p>Example message</p> <pre><code>[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionparse_error105","title":"json.exception.parse_error.105","text":"<p>An operation of a JSON Patch document must contain exactly one \"op\" member, whose value indicates the operation to perform. Its value must be one of \"add\", \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are errors.</p> <p>Example message</p> <p><pre><code>[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'\n</code></pre> <pre><code>[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'\n</code></pre> <pre><code>[json.exception.parse_error.105] parse error: operation value 'foo' is invalid\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptionparse_error106","title":"json.exception.parse_error.106","text":"<p>An array index in a JSON Pointer (RFC 6901) may be <code>0</code> or any number without a leading <code>0</code>.</p> <p>Example message</p> <pre><code>[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionparse_error107","title":"json.exception.parse_error.107","text":"<p>A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a <code>/</code> character.</p> <p>Example message</p> <pre><code>[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionparse_error108","title":"json.exception.parse_error.108","text":"<p>In a JSON Pointer, only <code>~0</code> and <code>~1</code> are valid escape sequences.</p> <p>Example message</p> <pre><code>[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionparse_error109","title":"json.exception.parse_error.109","text":"<p>A JSON Pointer array index must be a number.</p> <p>Example messages</p> <p><pre><code>[json.exception.parse_error.109] parse error: array index 'one' is not a number\n</code></pre> <pre><code>[json.exception.parse_error.109] parse error: array index '+1' is not a number\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptionparse_error110","title":"json.exception.parse_error.110","text":"<p>When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.</p> <p>Example message</p> <p><pre><code>[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input\n</code></pre> <pre><code>[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptionparse_error112","title":"json.exception.parse_error.112","text":"<p>An unexpected byte was read in a binary format or length information is invalid (BSON).</p> <p>Example messages</p> <p><pre><code>[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C\n</code></pre> <pre><code>[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1\n</code></pre> <pre><code>[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02\n</code></pre> <pre><code>[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02\n</code></pre> <pre><code>[json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648\n</code></pre> <pre><code>[json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptionparse_error113","title":"json.exception.parse_error.113","text":"<p>While parsing a map key, a value that is not a string has been read.</p> <p>Example messages</p> <p><pre><code>[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF\n</code></pre> <pre><code>[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack string: expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0xFF\n</code></pre> <pre><code>[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing UBJSON char: byte after 'C' must be in range 0x00..0x7F; last byte: 0x82\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptionparse_error114","title":"json.exception.parse_error.114","text":"<p>The parsing of the corresponding BSON record type is not implemented (yet).</p> <p>Example message</p> <pre><code>[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionparse_error115","title":"json.exception.parse_error.115","text":"<p>A UBJSON high-precision number could not be parsed.</p> <p>Example message</p> <pre><code>[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A\n</code></pre>"},{"location":"home/exceptions/#iterator-errors","title":"Iterator errors","text":"<p>This exception is thrown if iterators passed to a library function do not match the expected semantics.</p> <p>Exceptions have ids 2xx.</p> Example <p>The following code shows how an <code>invalid_iterator</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling iterator::key() on non-object iterator\n json j = \"string\";\n json::iterator it = j.begin();\n auto k = it.key();\n }\n catch (const json::invalid_iterator& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","title":"json.exception.invalid_iterator.201","text":"<p>The iterators passed to constructor <code>basic_json(InputIT first, InputIT last)</code> are not compatible, meaning they do not belong to the same container. Therefore, the range (<code>first</code>, <code>last</code>) is invalid.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.201] iterators are not compatible\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","title":"json.exception.invalid_iterator.202","text":"<p>In the erase or insert function, the passed iterator <code>pos</code> does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.</p> <p>Example messages</p> <p><pre><code>[json.exception.invalid_iterator.202] iterator does not fit current value\n</code></pre> <pre><code>[json.exception.invalid_iterator.202] iterators first and last must point to objects\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","title":"json.exception.invalid_iterator.203","text":"<p>Either iterator passed to function <code>erase(IteratorType first, IteratorType last</code>) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.203] iterators do not fit current value\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","title":"json.exception.invalid_iterator.204","text":"<p>When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (<code>begin(),</code> <code>end()),</code> because this is the only way the single stored value is expressed. All other ranges are invalid.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.204] iterators out of range\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","title":"json.exception.invalid_iterator.205","text":"<p>When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the <code>begin()</code> iterator, because it is the only way to address the stored value. All other iterators are invalid.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.205] iterator out of range\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","title":"json.exception.invalid_iterator.206","text":"<p>The iterators passed to constructor <code>basic_json(InputIT first, InputIT last)</code> belong to a JSON null value and hence to not define a valid range.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.206] cannot construct with iterators from null\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","title":"json.exception.invalid_iterator.207","text":"<p>The <code>key()</code> member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.207] cannot use key() for non-object iterators\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","title":"json.exception.invalid_iterator.208","text":"<p>The <code>operator[]</code> to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.208] cannot use operator[] for object iterators\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","title":"json.exception.invalid_iterator.209","text":"<p>The offset operators (<code>+</code>, <code>-</code>, <code>+=</code>, <code>-=</code>) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.209] cannot use offsets with object iterators\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","title":"json.exception.invalid_iterator.210","text":"<p>The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (<code>first</code>, <code>last</code>) is invalid.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.210] iterators do not fit\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","title":"json.exception.invalid_iterator.211","text":"<p>The iterator range passed to the insert function must not be a subrange of the container to insert to.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.211] passed iterators may not belong to container\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","title":"json.exception.invalid_iterator.212","text":"<p>When two iterators are compared, they must belong to the same container.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.212] cannot compare iterators of different containers\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","title":"json.exception.invalid_iterator.213","text":"<p>The order of object iterators cannot be compared, because JSON objects are unordered.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.213] cannot compare order of object iterators\n</code></pre>"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","title":"json.exception.invalid_iterator.214","text":"<p>Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to <code>begin()</code>.</p> <p>Example message</p> <pre><code>[json.exception.invalid_iterator.214] cannot get value\n</code></pre>"},{"location":"home/exceptions/#type-errors","title":"Type errors","text":"<p>This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.</p> <p>Exceptions have ids 3xx.</p> Example <p>The following code shows how a <code>type_error</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling push_back() on a string value\n json j = \"string\";\n j.push_back(\"another string\");\n }\n catch (const json::type_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error301","title":"json.exception.type_error.301","text":"<p>To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.</p> <p>Example message</p> <pre><code>[json.exception.type_error.301] cannot create object from initializer list\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error302","title":"json.exception.type_error.302","text":"<p>During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.</p> <p>Example messages</p> <p><pre><code>[json.exception.type_error.302] type must be object, but is null\n</code></pre> <pre><code>[json.exception.type_error.302] type must be string, but is object\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptiontype_error303","title":"json.exception.type_error.303","text":"<p>To retrieve a reference to a value stored in a <code>basic_json</code> object with <code>get_ref</code>, the type of the reference must match the value type. For instance, for a JSON array, the <code>ReferenceType</code> must be <code>array_t &</code>.</p> <p>Example messages</p> <p><pre><code>[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object\n</code></pre> <pre><code>[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptiontype_error304","title":"json.exception.type_error.304","text":"<p>The <code>at()</code> member functions can only be executed for certain JSON types.</p> <p>Example messages</p> <p><pre><code>[json.exception.type_error.304] cannot use at() with string\n</code></pre> <pre><code>[json.exception.type_error.304] cannot use at() with number\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptiontype_error305","title":"json.exception.type_error.305","text":"<p>The <code>operator[]</code> member functions can only be executed for certain JSON types.</p> <p>Example messages</p> <p><pre><code>[json.exception.type_error.305] cannot use operator[] with a string argument with array\n</code></pre> <pre><code>[json.exception.type_error.305] cannot use operator[] with a numeric argument with object\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptiontype_error306","title":"json.exception.type_error.306","text":"<p>The <code>value()</code> member functions can only be executed for certain JSON types.</p> <p>Example message</p> <pre><code>[json.exception.type_error.306] cannot use value() with number\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error307","title":"json.exception.type_error.307","text":"<p>The <code>erase()</code> member functions can only be executed for certain JSON types.</p> <p>Example message</p> <pre><code>[json.exception.type_error.307] cannot use erase() with string\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error308","title":"json.exception.type_error.308","text":"<p>The <code>push_back()</code> and <code>operator+=</code> member functions can only be executed for certain JSON types.</p> <p>Example message</p> <pre><code>[json.exception.type_error.308] cannot use push_back() with string\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error309","title":"json.exception.type_error.309","text":"<p>The <code>insert()</code> member functions can only be executed for certain JSON types.</p> <p>Example messages</p> <p><pre><code>[json.exception.type_error.309] cannot use insert() with array\n</code></pre> <pre><code>[json.exception.type_error.309] cannot use insert() with number\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptiontype_error310","title":"json.exception.type_error.310","text":"<p>The <code>swap()</code> member functions can only be executed for certain JSON types.</p> <p>Example message</p> <pre><code>[json.exception.type_error.310] cannot use swap() with number\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error311","title":"json.exception.type_error.311","text":"<p>The <code>emplace()</code> and <code>emplace_back()</code> member functions can only be executed for certain JSON types.</p> <p>Example messages</p> <p><pre><code>[json.exception.type_error.311] cannot use emplace() with number\n</code></pre> <pre><code>[json.exception.type_error.311] cannot use emplace_back() with number\n</code></pre></p>"},{"location":"home/exceptions/#jsonexceptiontype_error312","title":"json.exception.type_error.312","text":"<p>The <code>update()</code> member functions can only be executed for certain JSON types.</p> <p>Example message</p> <pre><code>[json.exception.type_error.312] cannot use update() with array\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error313","title":"json.exception.type_error.313","text":"<p>The <code>unflatten</code> function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined.</p> <p>Example message</p> <pre><code>[json.exception.type_error.313] invalid value to unflatten\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error314","title":"json.exception.type_error.314","text":"<p>The <code>unflatten</code> function only works for an object whose keys are JSON Pointers.</p> <p>Example message</p> <p>Calling <code>unflatten()</code> on an array <code>[1,2,3]</code>:</p> <pre><code>[json.exception.type_error.314] only objects can be unflattened\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error315","title":"json.exception.type_error.315","text":"<p>The <code>unflatten()</code> function only works for an object whose keys are JSON Pointers and whose values are primitive.</p> <p>Example message</p> <p>Calling <code>unflatten()</code> on an object <code>{\"/1\", [1,2,3]}</code>:</p> <pre><code>[json.exception.type_error.315] values in object must be primitive\n</code></pre>"},{"location":"home/exceptions/#jsonexceptiontype_error316","title":"json.exception.type_error.316","text":"<p>The <code>dump()</code> function only works with UTF-8 encoded strings; that is, if you assign a <code>std::string</code> to a JSON value, make sure it is UTF-8 encoded.</p> <p>Example message</p> <p>Calling <code>dump()</code> on a JSON value containing an ISO 8859-1 encoded string: <pre><code>[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F\n</code></pre></p> <p>Tip</p> <ul> <li>Store the source file with UTF-8 encoding.</li> <li>Pass an error handler as last parameter to the <code>dump()</code> function to avoid this exception:<ul> <li><code>json::error_handler_t::replace</code> will replace invalid bytes sequences with <code>U+FFFD</code> </li> <li><code>json::error_handler_t::ignore</code> will silently ignore invalid byte sequences</li> </ul> </li> </ul>"},{"location":"home/exceptions/#jsonexceptiontype_error317","title":"json.exception.type_error.317","text":"<p>The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw <code>true</code> or <code>null</code> JSON object cannot be serialized to BSON)</p> <p>Example messages</p> <p>Serializing <code>null</code> to BSON: <pre><code>[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n</code></pre> Serializing <code>[1,2,3]</code> to BSON: <pre><code>[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n</code></pre></p> <p>Tip</p> <p>Encapsulate the JSON value in an object. That is, instead of serializing <code>true</code>, serialize <code>{\"value\": true}</code></p>"},{"location":"home/exceptions/#out-of-range","title":"Out of range","text":"<p>This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.</p> <p>Exceptions have ids 4xx.</p> Example <p>The following code shows how an <code>out_of_range</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for an invalid index\n json j = {1, 2, 3, 4};\n j.at(4) = 10;\n }\n catch (const json::out_of_range& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range401","title":"json.exception.out_of_range.401","text":"<p>The provided array index <code>i</code> is larger than <code>size-1</code>.</p> <p>Example message</p> <pre><code>array index 3 is out of range\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range402","title":"json.exception.out_of_range.402","text":"<p>The special array index <code>-</code> in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.</p> <p>Example message</p> <pre><code>array index '-' (3) is out of range\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range403","title":"json.exception.out_of_range.403","text":"<p>The provided key was not found in the JSON object.</p> <p>Example message</p> <pre><code>key 'foo' not found\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range404","title":"json.exception.out_of_range.404","text":"<p>A reference token in a JSON Pointer could not be resolved.</p> <p>Example message</p> <pre><code>unresolved reference token 'foo'\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range405","title":"json.exception.out_of_range.405","text":"<p>The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.</p> <p>Example message</p> <pre><code>JSON pointer has no parent\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range406","title":"json.exception.out_of_range.406","text":"<p>A parsed number could not be stored as without changing it to NaN or INF.</p> <p>Example message</p> <pre><code>number overflow parsing '10E1000'\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range407","title":"json.exception.out_of_range.407","text":"<p>UBJSON and BSON only support integer numbers up to 9223372036854775807.</p> <p>Example message</p> <pre><code>number overflow serializing '9223372036854775808'\n</code></pre> <p>Note</p> <p>Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur. </p>"},{"location":"home/exceptions/#jsonexceptionout_of_range408","title":"json.exception.out_of_range.408","text":"<p>The size (following <code>#</code>) of an UBJSON array or object exceeds the maximal capacity.</p> <p>Example message</p> <pre><code>excessive array size: 8658170730974374167\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionout_of_range409","title":"json.exception.out_of_range.409","text":"<p>Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.</p> <p>Example message</p> <pre><code>BSON key cannot contain code point U+0000 (at byte 2)\n</code></pre>"},{"location":"home/exceptions/#further-exceptions","title":"Further exceptions","text":"<p>This exception is thrown in case of errors that cannot be classified with the other exception types.</p> <p>Exceptions have ids 5xx.</p> Example <p>The following code shows how an <code>other_error</code> exception can be caught.</p> <pre><code>#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n try\n {\n // executing a failing JSON Patch operation\n json value = R\"({\n \"best_biscuit\": {\n \"name\": \"Oreo\"\n }\n })\"_json;\n json patch = R\"([{\n \"op\": \"test\",\n \"path\": \"/best_biscuit/name\",\n \"value\": \"Choco Leibniz\"\n }])\"_json;\n value.patch(patch);\n }\n catch (const json::other_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n</code></pre> <p>Output:</p> <pre><code>message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n</code></pre>"},{"location":"home/exceptions/#jsonexceptionother_error501","title":"json.exception.other_error.501","text":"<p>A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.</p> <p>Example message</p> <p>Executing <code>{\"op\":\"test\", \"path\":\"/baz\", \"value\":\"bar\"}</code> on <code>{\"baz\": \"qux\"}</code>:</p> <pre><code>[json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}\n</code></pre>"},{"location":"home/faq/","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"home/faq/#known-bugs","title":"Known bugs","text":""},{"location":"home/faq/#brace-initialization-yields-arrays","title":"Brace initialization yields arrays","text":"<p>Question</p> <p>Why does</p> <pre><code>json j{true};\n</code></pre> <p>and</p> <pre><code>json j(true);\n</code></pre> <p>yield different results (<code>[true]</code> vs. <code>true</code>)?</p> <p>This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like</p> <pre><code>json array = {1, 2, 3, 4};\n</code></pre> <p>for arrays and</p> <pre><code>json object = {{\"one\", 1}, {\"two\", 2}}; \n</code></pre> <p>for objects.</p> <p>Tip</p> <p>To avoid any confusion and ensure portable code, do not use brace initialization with the types <code>basic_json</code>, <code>json</code>, or <code>ordered_json</code> unless you want to create an object or array as shown in the examples above.</p>"},{"location":"home/faq/#limitations","title":"Limitations","text":""},{"location":"home/faq/#relaxed-parsing","title":"Relaxed parsing","text":"<p>Question</p> <p>Can you add an option to ignore trailing commas?</p> <p>This library does not support any feature which would jeopardize interoperability.</p>"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","title":"Parse errors reading non-ASCII characters","text":"<p>Questions</p> <ul> <li>Why is the parser complaining about a Chinese character?</li> <li>Does the library support Unicode?</li> <li>I get an exception <code>[json.exception.parse_error.101] parse error at line 1, column 53: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '\"Test\u00e9$')\"</code></li> </ul> <p>The library supports Unicode input as follows:</p> <ul> <li>Only UTF-8 encoded input is supported which is the default encoding for JSON according to RFC 8259.</li> <li><code>std::u16string</code> and <code>std::u32string</code> can be parsed, assuming UTF-16 and UTF-32 encoding, respectively. These encodings are not supported when reading from files or other input containers.</li> <li>Other encodings such as Latin-1 or ISO 8859-1 are not supported and will yield parse or serialization errors.</li> <li>Unicode noncharacters will not be replaced by the library.</li> <li>Invalid surrogates (e.g., incomplete pairs such as <code>\\uDEAD</code>) will yield parse errors.</li> <li>The strings stored in the library are UTF-8 encoded. When using the default string type (<code>std::string</code>), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.</li> <li>When you store strings with different encodings in the library, calling <code>dump()</code> may throw an exception unless <code>json::error_handler_t::replace</code> or <code>json::error_handler_t::ignore</code> are used as error handlers.</li> </ul> <p>In most cases, the parser is right to complain, because the input is not UTF-8 encoded. This is especially true for Microsoft Windows where Latin-1 or ISO 8859-1 is often the standard encoding.</p>"},{"location":"home/faq/#wide-string-handling","title":"Wide string handling","text":"<p>Question</p> <p>Why are wide strings (e.g., <code>std::wstring</code>) dumped as arrays of numbers?</p> <p>As described above, the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding.</p> <p>Example</p> <pre><code>#include <codecvt> // codecvt_utf8\n#include <locale> // wstring_convert\n\n// encoding function\nstd::string to_utf8(std::wstring& wide_string)\n{\n static std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;\n return utf8_conv.to_bytes(wide_string);\n}\n\njson j;\nstd::wstring ws = L\"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\";\n\nj[\"original\"] = ws;\nj[\"encoded\"] = to_utf8(ws);\n\nstd::cout << j << std::endl;\n</code></pre> <p>The result is:</p> <pre><code>{\n \"encoded\": \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\",\n \"original\": [36554, 66, 49, 50, 51, 52, 32, 12371, 12435, 12395, 12385, 12399]\n}\n</code></pre>"},{"location":"home/faq/#exceptions","title":"Exceptions","text":""},{"location":"home/faq/#parsing-without-exceptions","title":"Parsing without exceptions","text":"<p>Question</p> <p>Is it possible to indicate a parse error without throwing an exception?</p> <p>Yes, see Parsing and exceptions.</p>"},{"location":"home/faq/#key-name-in-exceptions","title":"Key name in exceptions","text":"<p>Question</p> <p>Can I get the key of the object item that caused an exception?</p> <p>Yes, you can. Please define the symbol <code>JSON_DIAGNOSTICS</code> to get extended diagnostics messages.</p>"},{"location":"home/faq/#serialization-issues","title":"Serialization issues","text":""},{"location":"home/faq/#number-precision","title":"Number precision","text":"<p>Question</p> <ul> <li>It seems that precision is lost when serializing a double.</li> <li>Can I change the precision for floating-point serialization?</li> </ul> <p>The library uses <code>std::numeric_limits<number_float_t>::digits10</code> (15 for IEEE <code>double</code>s) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip.</p> <p>cppreference.com</p> <p>The value of <code>std::numeric_limits<T>::digits10</code> is the number of base-10 digits that can be represented by the type T without change, that is, any number with this many significant decimal digits can be converted to a value of type T and back to decimal form, without change due to rounding or overflow. </p> <p>Tip</p> <p>The website https://float.exposed gives a good insight into the internal storage of floating-point numbers.</p> <p>See this section on the library's number handling for more information.</p>"},{"location":"home/faq/#compilation-issues","title":"Compilation issues","text":""},{"location":"home/faq/#android-sdk","title":"Android SDK","text":"<p>Question</p> <p>Why does the code not compile with Android SDK?</p> <p>Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your <code>Application.mk</code>. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.</p> <pre><code>APP_STL := c++_shared\nNDK_TOOLCHAIN_VERSION := clang3.6\nAPP_CPPFLAGS += -frtti -fexceptions\n</code></pre> <p>The code compiles successfully with Android NDK, Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.</p>"},{"location":"home/faq/#missing-stl-function","title":"Missing STL function","text":"<p>Questions</p> <ul> <li>Why do I get a compilation error <code>'to_string' is not a member of 'std'</code> (or similarly, for <code>strtod</code> or <code>strtof</code>)?</li> <li>Why does the code not compile with MinGW or Android SDK?</li> </ul> <p>This is not an issue with the code, but rather with the compiler itself. On Android, see above to build with a newer environment. For MinGW, please refer to this site and this discussion for information on how to fix this bug. For Android NDK using <code>APP_STL := gnustl_static</code>, please refer to this discussion.</p>"},{"location":"home/license/","title":"License","text":"<p>The class is licensed under the MIT License:</p> <p>Copyright \u00a9 2013-2022 Niels Lohmann</p> <p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p> <p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p> <p>THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p> <p>The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de</p> <p>The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch</p> <p>The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0.</p>"},{"location":"home/releases/","title":"Releases","text":""},{"location":"home/releases/#v373","title":"v3.7.3","text":"<p>Files</p> <ul> <li>include.zip (274 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (791 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)</p>"},{"location":"home/releases/#summary","title":"Summary","text":"<p>This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.</p>"},{"location":"home/releases/#bug-fixes","title":"Bug Fixes","text":"<ul> <li>Removed <code>reserve()</code> calls from the destructor which could lead to quadratic complexity. #1837 #1838</li> </ul>"},{"location":"home/releases/#deprecated-functions","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v372","title":"v3.7.2","text":"<p>Files</p> <ul> <li>include.zip (274 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (791 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)</p>"},{"location":"home/releases/#summary_1","title":"Summary","text":"<p>Project bad_json_parsers tested how JSON parser libraries react on deeply nested inputs. It turns out that this library segfaulted at a certain nesting depth. This bug was fixed with this release. Now the parsing is only bounded by the available memory. All changes are backward-compatible.</p>"},{"location":"home/releases/#bug-fixes_1","title":"Bug Fixes","text":"<ul> <li>Fixed a bug that lead to stack overflow for deeply nested JSON values (objects, array) by changing the implementation of the destructor from a recursive to an iterative approach. #832, #1419, #1835</li> </ul>"},{"location":"home/releases/#further-changes","title":"Further Changes","text":"<ul> <li>Added WhiteStone Bolt. #1830</li> </ul>"},{"location":"home/releases/#deprecated-functions_1","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v371","title":"v3.7.1","text":"<p>Files</p> <ul> <li>include.zip (273 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (789 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)</p>"},{"location":"home/releases/#summary_2","title":"Summary","text":"<p>This release fixes several small bugs in the library. All changes are backward-compatible.</p>"},{"location":"home/releases/#bug-fixes_2","title":"Bug Fixes","text":"<ul> <li>Fixed a segmentation fault when serializing <code>std::int64_t</code> minimum value. #1708 #1722</li> <li>Fixed the <code>contains()</code> function for JSON Pointers. #1727 #1741</li> <li>Fixed too lax SFINAE guard for conversion from <code>std::pair</code> and <code>std::tuple</code> to <code>json</code>. #1805 #1806 #1825 #1826</li> <li>Fixed some regressions detected by UBSAN. Updated CI to use Clang-Tidy 7.1.0. #1716 #1728</li> <li>Fixed integer truncation in <code>iteration_proxy</code>. #1797</li> <li>Updated Hedley to v11 to fix a E2512 error in MSVC. #1799</li> <li>Fixed a compile error in enum deserialization of non non-default-constructible types. #1647 #1821</li> <li>Fixed the conversion from <code>json</code> to <code>std::valarray</code>.</li> </ul>"},{"location":"home/releases/#improvements","title":"Improvements","text":"<ul> <li>The <code>items()</code> function can now be used with a custom string type. #1765</li> <li>Made <code>json_pointer::back</code> <code>const</code>. #1764 #1769</li> <li>Meson is part of the release archive. #1672 #1694 </li> <li>Improved documentation on the Meson and Spack package manager. #1694 #1720</li> </ul>"},{"location":"home/releases/#further-changes_1","title":"Further Changes","text":"<ul> <li>Added GitHub Workflow with <code>ubuntu-latest</code>/GCC 7.4.0 as CI step.</li> <li>Added GCC 9 to Travis CI to compile with C++20 support. #1724</li> <li>Added MSVC 2019 to the AppVeyor CI. #1780</li> <li>Added badge to fuzzing status.</li> <li>Fixed some cppcheck warnings. #1760</li> <li>Fixed several typos in the documentation. #1720 #1767 #1803</li> <li>Added documentation on the <code>JSON_THROW_USER</code>, <code>JSON_TRY_USER</code>, and <code>JSON_CATCH_USER</code> macros to control user-defined exception handling.</li> <li>Used GitHub's CODEOWNERS and SECURITY feature.</li> <li>Removed <code>GLOB</code> from CMake files. #1779</li> <li>Updated to Doctest 2.3.5.</li> </ul>"},{"location":"home/releases/#deprecated-functions_2","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v370","title":"v3.7.0","text":"<p>Files</p> <ul> <li>include.zip (143 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (782 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)</p>"},{"location":"home/releases/#summary_3","title":"Summary","text":"<p>This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features","title":"New Features","text":"<ul> <li>Add overload of the <code>contains</code> function to check if a JSON pointer is valid without throwing exceptions, just like its counterpart for object keys. #1600</li> <li>Add a function <code>to_string</code> to allow for generic conversion to strings. #916 #1585</li> <li>Add return value for the <code>emplace_back</code> function, returning a reference to the added element just like C++17 is introducing this for <code>std::vector</code>. #1609</li> <li>Add info how to use the library with the pacman package manager on MSYS2. #1670</li> </ul>"},{"location":"home/releases/#bug-fixes_3","title":"Bug Fixes","text":"<ul> <li>Fix an issue where typedefs with certain names yielded a compilation error. #1642 #1643</li> <li>Fix a conversion to <code>std::string_view</code> in the unit tests. #1634 #1639</li> <li>Fix MSVC Debug build. #1536 #1570 #1608</li> <li>Fix <code>get_to</code> method to clear existing content before writing. #1511 #1555</li> <li>Fix a <code>-Wc++17-extensions</code> warning. <code>nodiscard</code> attributes are now only used with Clang when <code>-std=c++17</code> is used. #1535 #1551</li> </ul>"},{"location":"home/releases/#improvements_1","title":"Improvements","text":"<ul> <li>Switch from Catch to doctest for the unit tests which speeds up compilation and runtime of the 112,112,308 tests.</li> <li>Add an explicit section to the README about the frequently addressed topics character encoding, comments in JSON, and the order of object keys.</li> </ul>"},{"location":"home/releases/#further-changes_2","title":"Further Changes","text":"<ul> <li>Use <code>GNUInstallDirs</code> to set library install directories. #1673</li> <li>Fix links in the README. #1620 #1621 #1622 #1623 #1625</li> <li>Mention <code>json</code> type on the documentation start page. #1616</li> <li>Complete documentation of <code>value()</code> function with respect to <code>type_error.302</code> exception. #1601</li> <li>Fix links in the documentation. #1598</li> <li>Add regression tests for MSVC. #1543 #1570</li> <li>Use CircleCI for continuous integration.</li> <li>Use Doozer for continuous integration on Linux (CentOS, Raspbian, Fedora)</li> <li>Add tests to check each CMake flag (<code>JSON_BuildTests</code>, <code>JSON_Install</code>, <code>JSON_MultipleHeaders</code>, <code>JSON_Sanitizer</code>, <code>JSON_Valgrind</code>, <code>JSON_NoExceptions</code>, <code>JSON_Coverage</code>).</li> <li>Use Hedley to avoid re-inventing several compiler-agnostic feature macros like <code>JSON_DEPRECATED</code>, <code>JSON_NODISCARD</code>, <code>JSON_LIKELY</code>, <code>JSON_UNLIKELY</code>, <code>JSON_HAS_CPP_14</code>, or <code>JSON_HAS_CPP_17</code>. Functions taking or returning pointers are annotated accordingly when a pointer will not be null.</li> <li>Build and run tests on AppVeyor in DEBUG and RELEASE mode.</li> </ul>"},{"location":"home/releases/#deprecated-functions_3","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v361","title":"v3.6.1","text":"<p>Files</p> <ul> <li>include.zip (136 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (711 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)</p>"},{"location":"home/releases/#summary_4","title":"Summary","text":"<p>This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.</p>"},{"location":"home/releases/#bug-fixes_4","title":"Bug Fixes","text":"<ul> <li>Fixed regression of #590 which could lead to compilation errors with GCC 7 and GCC 8. #1530</li> <li>Fixed a compilation error when <code><Windows.h></code> was included. #1531</li> </ul>"},{"location":"home/releases/#further-changes_3","title":"Further Changes","text":"<ul> <li>Fixed a warning for missing field initializers. #1527</li> </ul>"},{"location":"home/releases/#deprecated-functions_4","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v360","title":"v3.6.0","text":"<p>Files</p> <ul> <li>include.zip (136 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (711 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip)</p> <p>\u2139\ufe0f This release introduced a regression. Please update to version 3.6.1!</p>"},{"location":"home/releases/#summary_5","title":"Summary","text":"<p>This release adds some convenience functions for JSON Pointers, introduces a <code>contains</code> function to check if a key is present in an object, and improves the performance of integer serialization. Furthermore, a lot of small bug fixes and improvements have been made. All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features_1","title":"New Features","text":"<ul> <li>Overworked the public interface for JSON Pointers. The creation of JSON Pointers is simplified with <code>operator/</code> and <code>operator/=</code>. JSON Pointers can be inspected with <code>empty</code>, <code>back</code>, and <code>parent_pointer</code>, and manipulated with <code>push_back</code> and <code>pop_back</code>. #1434</li> <li>Added a boolean method <code>contains</code> to check whether an element exists in a JSON object with a given key. Returns false when called on non-object types. #1471 #1474</li> </ul>"},{"location":"home/releases/#bug-fixes_5","title":"Bug Fixes","text":"<ul> <li>Fixed a compilation issues with libc 2.12. #1483 #1514</li> <li>Fixed endian conversion on PPC64. #1489</li> <li>Fixed library to compile with GCC 9. #1472 #1492</li> <li>Fixed a compilation issue with GCC 7 on CentOS. #1496</li> <li>Fixed an integer overflow. #1447</li> <li>Fixed buffer flushing in serializer. #1445 #1446</li> </ul>"},{"location":"home/releases/#improvements_2","title":"Improvements","text":"<ul> <li>The performance of dumping integers has been greatly improved. #1411</li> <li>Added CMake parameter <code>JSON_Install</code> to control whether the library should be installed (default: on). #1330</li> <li>Fixed a lot of compiler and linter warnings. #1400 #1435 #1502</li> <li>Reduced required CMake version from 3.8 to 3.1. #1409 #1428 #1441 #1498</li> <li>Added <code>nodiscard</code> attribute to <code>meta()</code>, <code>array()</code>, <code>object()</code>, <code>from_cbor</code>, <code>from_msgpack</code>, <code>from_ubjson</code>, <code>from_bson</code>, and <code>parse</code>. #1433</li> </ul>"},{"location":"home/releases/#further-changes_4","title":"Further Changes","text":"<ul> <li>Added missing headers. #1500</li> <li>Fixed typos and broken links in README. #1417 #1423 #1425 #1451 #1455 #1491</li> <li>Fixed documentation of parse function. #1473</li> <li>Suppressed warning that cannot be fixed inside the library. #1401 #1468</li> <li>Imroved package manager suppert:<ul> <li>Updated Buckaroo instructions. #1495</li> <li>Improved Meson support. #1463</li> <li>Added Conda package manager documentation. #1430</li> <li>Added NuGet package manager documentation. #1132</li> </ul> </li> <li>Continuous Integration<ul> <li>Removed unstable or deprecated Travis builders (Xcode 6.4 - 8.2) and added Xcode 10.1 builder.</li> <li>Added Clang 7 to Travis CI.</li> <li>Fixed AppVeyor x64 builds. #1374 #1414</li> </ul> </li> <li>Updated thirdparty libraries:<ul> <li>Catch 1.12.0 -> 1.12.2</li> <li>Google Benchmark 1.3.0 -> 1.4.1</li> <li>Doxygen 1.8.15 -> 1.8.16</li> </ul> </li> </ul>"},{"location":"home/releases/#deprecated-functions_5","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v350","title":"v3.5.0","text":"<p>Files</p> <ul> <li>include.zip (133 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (693 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)</p>"},{"location":"home/releases/#summary_6","title":"Summary","text":"<p>This release introduces the support for structured bindings and reading from <code>FILE*</code>. Besides, a few bugs have been fixed. All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features_2","title":"New Features","text":"<ul> <li> <p>Structured bindings are now supported for JSON objects and arrays via the <code>items()</code> member function, so finally this code is possible: <pre><code>for (auto& [key, val] : j.items()) {\n std::cout << key << ':' << val << '\\n';\n}\n</code></pre> #1388 #1391</p> </li> <li> <p>Added support for reading from <code>FILE*</code> to support situations in which streams are nit available or would require too much RAM. #1370 #1392</p> </li> </ul>"},{"location":"home/releases/#bug-fixes_6","title":"Bug Fixes","text":"<ul> <li>The <code>eofbit</code> was not set for input streams when the end of a stream was reached while parsing. #1340 #1343</li> <li>Fixed a bug in the SAX parser for BSON arrays.</li> </ul>"},{"location":"home/releases/#improvements_3","title":"Improvements","text":"<ul> <li>Added support for Clang 5.0.1 (PS4 version). #1341 #1342</li> </ul>"},{"location":"home/releases/#further-changes_5","title":"Further Changes","text":"<ul> <li>Added a warning for implicit conversions to the documentation: It is not recommended to use implicit conversions when reading from a JSON value. Details about this recommendation can be found here. #1363</li> <li>Fixed typos in the documentation. #1329 #1380 #1382</li> <li>Fixed a C4800 warning. #1364</li> <li>Fixed a <code>-Wshadow</code> warning #1346</li> <li>Wrapped <code>std::snprintf</code> calls to avoid error in MSVC. #1337</li> <li>Added code to allow installation via Meson. #1345</li> </ul>"},{"location":"home/releases/#deprecated-functions_6","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v340","title":"v3.4.0","text":"<p>Files</p> <ul> <li>include.zip (132 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (689 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)</p>"},{"location":"home/releases/#summary_7","title":"Summary","text":"<p>This release introduces three new features:</p> <ul> <li>BSON (Binary JSON) is next to CBOR, MessagePack, and UBJSON the fourth binary (de)serialization format supported by the library.</li> <li>Adjustable error handlers for invalid Unicode allows to specify the behavior when invalid byte sequences are serialized.</li> <li>Simplified enum/JSON mapping with a macro in case the default mapping to integers is not desired.</li> </ul> <p>Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features_3","title":"New Features","text":"<ul> <li>The library can read and write a subset of BSON (Binary JSON). All data types known from JSON are supported, whereas other types more tied to MongoDB such as timestamps, object ids, or binary data are currently not implemented. See the README for examples. #1244 #1320</li> <li>The behavior when the library encounters an invalid Unicode sequence during serialization can now be controlled by defining one of three Unicode error handlers: (1) throw an exception (default behavior), (2) replace invalid sequences by the Unicode replacement character (U+FFFD), or (3) ignore/filter invalid sequences. See the documentation of the <code>dump</code> function for examples. #1198 #1314</li> <li>To easily specify a user-defined enum/JSON mapping, a macro <code>NLOHMANN_JSON_SERIALIZE_ENUM</code> has been introduced. See the README section for more information. #1208 #1323</li> </ul>"},{"location":"home/releases/#bug-fixes_7","title":"Bug Fixes","text":"<ul> <li>fixed truncation #1286 #1315</li> <li>fixed an issue with std::pair #1299 #1301</li> <li>fixed an issue with std::variant #1292 #1294</li> <li>fixed a bug in the JSON Pointer parser</li> </ul>"},{"location":"home/releases/#improvements_4","title":"Improvements","text":"<ul> <li>The diagnosis messages for parse errors have been improved: error messages now indicated line/column positions where possible (in addition to a byte count) and also the context in which the error occurred (e.g., \"while parsing a JSON string\"). Example: error <code>parse error at 2: syntax error - invalid string: control character must be escaped; last read: '<U+0009>'</code> is now reported as <code>parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t; last read: '<U+0009>'</code>. #1280 #1288 #1303</li> </ul>"},{"location":"home/releases/#further-changes_6","title":"Further Changes","text":"<ul> <li>improved Meson documentation #1305</li> <li>fixed some more linter warnings #1280</li> <li>fixed Clang detection for third-party Google Benchmark library #1277</li> </ul>"},{"location":"home/releases/#deprecated-functions_7","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v330","title":"v3.3.0","text":"<p>Files</p> <ul> <li>include.zip (123 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (635 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)</p>"},{"location":"home/releases/#summary_8","title":"Summary","text":"<p>This release adds support for GCC 4.8. Furthermore, it adds a function <code>get_to</code> to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented.</p> <p>Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features_4","title":"New Features","text":"<ul> <li>The library can now also built with GCC 4.8. Though this compiler does not fully support C++11, it can successfully compile and run the test suite. Note that bug 57824 in GCC 4.8 still forbids to use multiline raw strings in arguments to macros. #1257</li> <li>Added new function <code>get_to</code> to write a JSON value to a passed reference. The destination type is automatically derived which allows more succinct code compared to the <code>get</code> function. #1227 #1231</li> </ul>"},{"location":"home/releases/#bug-fixes_8","title":"Bug Fixes","text":"<ul> <li>Fixed a bug in the CMake file that made <code>target_link_libraries</code> to not properly include <code>nlohmann_json</code>. #1243 #1245 #1260</li> <li>Fixed a warning in MSVC 2017 complaining about a constexpr if. #1204 #1268 #1272</li> <li>Fixed a bug that prevented compilation with ICPC. #755 #1222</li> <li>Improved the SFINAE correctness to fix a bug in the conversion operator. #1237 #1238</li> <li>Fixed a <code>-Wctor-dtor-privacy</code> warning. #1224</li> <li>Fixed a warning on a lambda in unevaluated context. #1225 #1230</li> <li>Fixed a bug introduced in version 3.2.0 where defining <code>JSON_CATCH_USER</code> led to duplicate macro definition of <code>JSON_INTERNAL_CATCH</code>. #1213 #1214</li> <li>Fixed a bug that prevented compilation with Clang 3.4.2 in RHEL 7. #1179 #1249</li> </ul>"},{"location":"home/releases/#improvements_5","title":"Improvements","text":"<ul> <li>Added documentation on CMake integration of the library. #1270</li> <li>Changed the CMake file to use <code>find_package(nlohmann_json)</code> without installing the library. #1202</li> <li>Improved error messages in case <code>operator[]</code> is used with the wrong combination (json.exception.type_error.305) of JSON container type and argument type. Example: \"cannot use operator[] with a string argument\". #1220 #1221</li> <li>Added a license and version information to the Meson build file. #1252</li> <li>Removed static assertions to indicated missing <code>to_json</code> or <code>from_json</code> functions as such assertions do not play well with SFINAE. These assertions also led to problems with GMock. #960 #1212 #1228</li> <li>The test suite now does not wait forever if run in a wrong directory and input files are not found. #1262</li> <li>The test suite does not show deprecation warnings for deprecated functions which frequently led to confusion. #1271</li> </ul>"},{"location":"home/releases/#further-changes_7","title":"Further Changes","text":"<ul> <li>GCC 4.8 and Xcode 10 were added to the continuous integration suite at Travis.</li> <li>Added lgtm checks to pull requests.</li> <li>Added tests for CMake integration. #1260</li> </ul>"},{"location":"home/releases/#deprecated-functions_8","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v320","title":"v3.2.0","text":"<p>Files</p> <ul> <li>include.zip (124 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (636 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)</p>"},{"location":"home/releases/#summary_9","title":"Summary","text":"<p>This release introduces a SAX interface to the library. While this may be a very special feature used by only few people, it allowed to unify all functions that consumed input and created some kind of JSON value. Internally, now all existing functions like <code>parse</code>, <code>accept</code>, <code>from_cbor</code>, <code>from_msgpack</code>, and <code>from_ubjson</code> use the SAX interface with different event processors. This allowed to separate the input processing from the value generation. Furthermore, throwing an exception in case of a parse error is now optional and up to the event processor. Finally, the JSON parser is now non-recursive (meaning it does not use the call stack, but <code>std::vector<bool></code> to track the hierarchy of structured values) which allows to process nested input more efficiently.</p> <p>Furthermore, the library finally is able to parse from wide string types. This is the first step toward opening the library from UTF-8 to UTF-16 and UTF-32.</p> <p>This release further fixes several bugs in the library. All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features_5","title":"New Features","text":"<ul> <li>added a parser with a SAX interface (#971, #1153)</li> <li>support to parse from wide string types <code>std::wstring</code>, <code>std::u16string</code>, and <code>std::u32string</code>; the input will be converted to UTF-8 (#1031)</li> <li>added support for <code>std::string_view</code> when using C++17 (#1028)</li> <li>allow to roundtrip <code>std::map</code> and <code>std::unordered_map</code> from JSON if key type is not convertible to string; in these cases, values are serialized to arrays of pairs (#1079, #1089, #1133, #1138)</li> </ul>"},{"location":"home/releases/#bug-fixes_9","title":"Bug Fixes","text":"<ul> <li>allow to create <code>nullptr_t</code> from JSON allowing to properly roundtrip <code>null</code> values (#1169)</li> <li>allow compare user-defined string types (#1130)</li> <li>better support for algorithms using iterators from <code>items()</code> (#1045, #1134)</li> <li>added parameter to avoid compilation error with MSVC 2015 debug builds (#1114)</li> <li>re-added accidentally skipped unit tests (#1176)</li> <li>fixed MSVC issue with <code>std::swap</code> (#1168)</li> </ul>"},{"location":"home/releases/#improvements_6","title":"Improvements","text":"<ul> <li><code>key()</code> function for iterators returns a const reference rather than a string copy (#1098)</li> <li>binary formats CBOR, MessagePack, and UBJSON now supports <code>float</code> as type for floating-point numbers (#1021)</li> </ul>"},{"location":"home/releases/#further-changes_8","title":"Further Changes","text":"<ul> <li>changed issue templates</li> <li>improved continuous integration: added builders for Xcode 9.3 and 9.4, added builders for GCC 8 and Clang 6, added builder for MinGW, added builders for MSVC targeting x86</li> <li>required CMake version is now at least 3.8 (#1040)</li> <li>overworked CMake file wrt. packaging (#1048)</li> <li>added package managers: Spack (#1041) and CocoaPods (#1148)</li> <li>fixed Meson include directory (#1142)</li> <li>preprocessor macro <code>JSON_SKIP_UNSUPPORTED_COMPILER_CHECK</code> can skip the rejection of unsupported compilers - use at your own risk! (#1128)</li> <li>preprocessor macro <code>JSON_INTERNAL_CATCH</code>/<code>JSON_INTERNAL_CATCH_USER</code> allows to control the behavior of exception handling inside the library (#1187)</li> <li>added note on <code>char</code> to JSON conversion</li> <li>added note how to send security-related issue via encrypted email</li> <li>removed dependency to <code>std::stringstream</code> (#1117)</li> <li>added SPDX-License-Identifier</li> <li>added updated JSON Parsing Test Suite, described in Parsing JSON is a Minefield \ud83d\udca3</li> <li>updated to Catch 1.12.0</li> </ul>"},{"location":"home/releases/#deprecated-functions_9","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v312","title":"v3.1.2","text":"<p>Files</p> <ul> <li>include.zip (115 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (582 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)</p>"},{"location":"home/releases/#summary_10","title":"Summary","text":"<p>This release fixes several bugs in the library. All changes are backward-compatible.</p>"},{"location":"home/releases/#bug-fixes_10","title":"Bug Fixes","text":"<ul> <li>Fixed a memory leak occurring in the parser callback (#1001).</li> <li>Different specializations of <code>basic_json</code> (e.g., using different template arguments for strings or objects) can now be used in assignments (#972, #977, #986).</li> <li>Fixed a logical error in an iterator range check (#992).</li> </ul>"},{"location":"home/releases/#improvements_7","title":"Improvements","text":"<ul> <li>The parser and the serialization now support user-defined string types (#1006, #1009).</li> </ul>"},{"location":"home/releases/#further-changes_9","title":"Further Changes","text":"<ul> <li>Clang Analyzer is now used as additional static analyzer; see <code>make clang_analyze</code>.</li> <li>Overworked README by adding links to the documentation (#981).</li> </ul>"},{"location":"home/releases/#deprecated-functions_10","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v311","title":"v3.1.1","text":"<p>Files</p> <ul> <li>include.zip (114 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (577 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)</p>"},{"location":"home/releases/#summary_11","title":"Summary","text":"<p>This release fixes several bugs in the library. All changes are backward-compatible.</p>"},{"location":"home/releases/#bug-fixes_11","title":"Bug Fixes","text":"<ul> <li>Fixed parsing of CBOR strings with indefinite length (#961). Earlier versions of this library misinterpreted the CBOR standard and rejected input with the <code>0x7F</code> start byte.</li> <li>Fixed user-defined conversion to vector type (#924, #969). A wrong SFINAE check rejected code though a user-defined conversion was provided.</li> <li>Fixed documentation of the parser behavior for objects with duplicate keys (#963). The exact behavior is not specified by RFC 8259 and the library now also provides no guarantee which object key is stored.</li> <li>Added check to detect memory overflow when parsing UBJSON containers (#962). The optimized UBJSON format allowed for specifying an array with billions of <code>null</code> elements with a few bytes and the library did not check whether this size exceeded <code>max_size()</code>.</li> </ul>"},{"location":"home/releases/#further-changes_10","title":"Further Changes","text":"<ul> <li>Code coverage is now calculated for the individual header files, allowing to find uncovered lines more quickly than by browsing through the single header version (#953, #957).</li> <li>A Makefile target <code>run_benchmarks</code> was added to quickly build and run the benchmark suite.</li> <li>The documentation was harmonized with respect to the header inclusion (#955). Now all examples and the README use <code>#include <nlohmann/json.hpp></code> to allow for selecting <code>single_include</code> or <code>include</code> or whatever installation folder as include directory.</li> <li>Added note on how to use the library with the cget package manager (#954).</li> </ul>"},{"location":"home/releases/#deprecated-functions_11","title":"Deprecated functions","text":"<p>This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li>Function <code>iterator_wrapper</code> are deprecated. Please use the member function <code>items()</code> instead.</li> <li>Functions <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> and <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> are deprecated. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</li> </ul>"},{"location":"home/releases/#v310","title":"v3.1.0","text":"<p>Files</p> <ul> <li>include.zip (114 KB)</li> <li>include.zip.asc (1 KB)</li> <li>json.hpp (577 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)</p>"},{"location":"home/releases/#summary_12","title":"Summary","text":"<p>This release adds support for the UBJSON format and JSON Merge Patch. It also contains some minor changes and bug fixes. All changes are backward-compatible.</p>"},{"location":"home/releases/#new-features_6","title":"New features","text":"<ul> <li>The library now supports UBJSON (Universal Binary JSON Specification) as binary format to read and write JSON values space-efficiently. See the documentation overview for a comparison of the different formats CBOR, MessagePack, and UBJSON.</li> <li>JSON Merge Patch (RFC 7386) offers an intuitive means to describe patches between JSON values (#876, #877). See the documentation of <code>merge_patch</code> for more information.</li> </ul>"},{"location":"home/releases/#improvements_8","title":"Improvements","text":"<ul> <li>The library now uses the Grisu2 algorithm for printing floating-point numbers (based on the reference implementation by Florian Loitsch) which produces a short representation which is guaranteed to round-trip (#360, #935, #936).</li> <li>The UTF-8 handling was further simplified by using the decoder of Bj\u00f6rn Hoehrmann in more scenarios.</li> </ul>"},{"location":"home/releases/#reorganization","title":"Reorganization","text":"<ul> <li>Though the library is released as a single header, its development got more and more complicated. With this release, the header is split into several files and the single-header file <code>json.hpp</code> can be generated from these development sources. In the repository, folder <code>include</code> contains the development sources and <code>single_include</code> contains the single <code>json.hpp</code> header (#700, #906, #907, #910, #911, #915, #920, #924, #925, #928, #944).</li> <li>The split further allowed for a forward declaration header <code>include/nlohmann/json_fwd.hpp</code> to speed up compilation times (#314).</li> </ul>"},{"location":"home/releases/#further-changes_11","title":"Further changes","text":"<ul> <li>Google Benchmark is now used for micro benchmarks (see <code>benchmarks</code> folder, #921).</li> <li>The serialization (JSON and binary formats) now properly work with the libraries string template parameter, allowing for optimized string implementations to be used in constraint environments such as embedded software (#941, #950).</li> <li>The exceptional behavior can now be overridden by defining macros <code>JSON_THROW_USER</code>, <code>JSON_TRY_USER</code>, and <code>JSON_CATCH_USER</code>, defining the behavior of <code>throw</code>, <code>try</code> and <code>catch</code>, respectively. This allows to switch off C++'s exception mechanism yet still execute user-defined code in case an error condition occurs (#938).</li> <li>To facilitate the interplay with flex and Bison, the library does not use the variable name <code>yytext</code> any more as it could clash with macro definitions (#933).</li> <li>The library now defines <code>NLOHMANN_JSON_VERSION_MAJOR</code>, <code>NLOHMANN_JSON_VERSION_MINOR</code>, and <code>NLOHMANN_JSON_VERSION_PATCH</code> to allow for conditional compilation based on the included library version (#943, #948).</li> <li>A compilation error with ICC has been fixed (#947).</li> <li>Typos and links in the documentation have been fixed (#900, #930).</li> <li>A compiler error related to incomplete types has been fixed (#919).</li> <li>The tests form the UTF-8 decoder stress test have been added to the test suite.</li> </ul>"},{"location":"home/releases/#deprecated-functions_12","title":"Deprecated functions","text":"<ul> <li>Function <code>iterator_wrapper</code> has been deprecated (#874). Since its introduction, the name was up for discussion, as it was too technical. We now introduced the member function <code>items()</code> with the same semantics. <code>iterator_wrapper</code> will be removed in the next major version (i.e., 4.0.0).</li> </ul> <p>Furthermore, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li><code>friend std::istream& operator<<(basic_json&, std::istream&)</code></li> <li><code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code></li> </ul> <p>Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</p>"},{"location":"home/releases/#v301","title":"v3.0.1","text":"<p>Files</p> <ul> <li>json.hpp (502 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c</p>"},{"location":"home/releases/#summary_13","title":"Summary","text":"<p>This release fixes small issues in the implementation of JSON Pointer and JSON Patch. All changes are backward-compatible.</p>"},{"location":"home/releases/#changes","title":"Changes","text":"<ul> <li> The \"copy\" operation of JSON Patch (RFC 6902) requests that it is an error if the target path points into a non-existing array or object (see #894 for a detailed description). This release fixes the implementation to detect such invalid target paths and throw an exception.</li> <li> An array index in a JSON Pointer (RFC 6901) must be an integer. This release fixes the implementation to throw an exception in case invalid array indices such as <code>10e2</code> are used.</li> <li> Added the JSON Patch tests from Byron Ruth and Mike McCabe.</li> <li> Fixed the documentation of the <code>at(ptr)</code> function with JSON Pointers to list all possible exceptions (see #888).</li> <li> Updated the container overview documentation (see #883).</li> <li> The CMake files now respect the <code>BUILD_TESTING</code> option (see #846, #885)</li> <li> Fixed some compiler warnings (see #858, #882).</li> </ul>"},{"location":"home/releases/#deprecated-functions_13","title":"Deprecated functions","text":"<p> To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li><code>friend std::istream& operator<<(basic_json&, std::istream&)</code></li> <li><code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code></li> </ul> <p>Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</p>"},{"location":"home/releases/#v300","title":"v3.0.0","text":"<p>Files</p> <ul> <li>json.hpp (501 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462</p>"},{"location":"home/releases/#summary_14","title":"Summary","text":"<p>After almost a year, here is finally a new release of JSON for Modern C++, and it is a major one! As we adhere to semantic versioning, this means the release includes some breaking changes, so please read the next section carefully before you update. But don't worry, we also added a few new features and put a lot of effort into fixing a lot of bugs and straighten out a few inconsistencies.</p>"},{"location":"home/releases/#breaking-changes","title":"Breaking changes","text":"<p>This section describes changes that change the public API of the library and may require changes in code using a previous version of the library. In section \"Moving from 2.x.x to 3.0.0\" at the end of the release notes, we describe in detail how existing code needs to be changed.</p> <ul> <li>The library now uses user-defined exceptions instead of re-using those defined in <code><stdexcept></code> (#244). This not only allows to add more information to the exceptions (every exception now has an identifier, and parse errors contain the position of the error), but also to easily catch all library exceptions with a single <code>catch(json::exception)</code>.</li> <li>When strings with a different encoding as UTF-8 were stored in JSON values, their serialization could not be parsed by the library itself, as only UTF-8 is supported. To enforce this library limitation and improve consistency, non-UTF-8 encoded strings now yield a <code>json::type_error</code> exception during serialization (#838). The check for valid UTF-8 is realized with code from Bj\u00f6rn Hoehrmann.</li> <li>NaN and infinity values can now be stored inside the JSON value without throwing an exception. They are, however, still serialized as <code>null</code> (#388).</li> <li>The library's iterator tag was changed from RandomAccessIterator to BidirectionalIterator (#593). Supporting RandomAccessIterator was incorrect as it assumed an ordering of values in a JSON objects which are unordered by definition.</li> <li>The library does not include the standard headers <code><iostream></code>, <code><ctype></code>, and <code><stdexcept></code> any more. You may need to add these headers to code relying on them.</li> <li>Removed constructor <code>explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr)</code> which was deprecated in version 2.0.0 (#480).</li> </ul>"},{"location":"home/releases/#deprecated-functions_14","title":"Deprecated functions","text":"<p>To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0):</p> <ul> <li><code>friend std::istream& operator<<(basic_json&, std::istream&)</code></li> <li><code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code></li> </ul> <p>Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> and <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</p>"},{"location":"home/releases/#new-features_7","title":"New features","text":"<p>With all this breaking and deprecation out of the way, let's talk about features!</p> <ul> <li>We improved the diagnostic information for syntax errors (#301). Now, an exception <code>json::parse_error</code> is thrown which contains a detailed message on the error, but also a member <code>byte</code> to indicate the byte offset in the input where the error occurred.</li> <li>We added a non-throwing syntax check (#458): The new <code>accept</code> function returns a Boolean indicating whether the input is proper JSON. We also added a Boolean parameter <code>allow_exceptions</code> to the existing <code>parse</code> functions to return a <code>discarded</code> value in case a syntax error occurs instead of throwing an exception.</li> <li>An <code>update</code> function was added to merge two JSON objects (#428). In case you are wondering: the name was inspired by Python.</li> <li>The <code>insert</code> function now also supports an iterator range to add elements to an object.</li> <li>The binary exchange formats CBOR and MessagePack can now be parsed from input streams and written to output streams (#477).</li> <li>Input streams are now only read until the end of a JSON value instead of the end of the input (#367).</li> <li>The serialization function <code>dump</code> now has two optional parameters <code>ensure_ascii</code> to escape all non-ASCII characters with <code>\\uxxxx</code> and an <code>indent_char</code> parameter to choose whether to indent with spaces or tabs (#654). </li> <li>Added built-in type support for C arrays (#502), <code>std::pair</code> and <code>std::tuple</code> (#563, #614), <code>enum</code> and <code>enum class</code> (#545), <code>std::vector<bool></code> (#494). Fixed support for <code>std::valarray</code> (#702), <code>std::array</code> (#553), and <code>std::map<std::string, std::string></code> (#600, #607).</li> </ul>"},{"location":"home/releases/#further-changes_12","title":"Further changes","text":"<p>Furthermore, there have been a lot of changes under the hood:</p> <ul> <li>Replaced the re2c generated scanner by a self-coded version which allows for a better modularization of the parser and better diagnostics. To test the new scanner, we added millions (8,860,608 to be exact) of unit tests to check all valid and invalid byte sequences of the Unicode standard.</li> <li>Google's OSS-Fuzz is still constantly fuzz-testing the library and found several issues that were fixed in this release (#497, #504, #514, #516, #518, #519, #575).</li> <li>We now also ignore UTF-8 byte order marks when parsing from an iterator range (#602).</li> <li>Values can be now moved from initializer lists (#663).</li> <li>Updated to Catch 1.9.7. Unfortunately, Catch2 currently has some performance issues.</li> <li>The non-exceptional paths of the library are now annotated with <code>__builtin_expect</code> to optimize branch prediction as long as no error occurs.</li> <li>MSVC now produces a stack trace in MSVC if a <code>from_json</code> or <code>to_json</code> function was not found for a user-defined type. We also added a debug visualizer <code>nlohmann_json.natvis</code> for better debugging in MSVC (#844).</li> <li>Overworked the documentation and added even more examples.</li> <li>The build workflow now relies on CMake and CTest. Special flags can be chosen with CMake, including coverage (<code>JSON_Coverage</code>), compilation without exceptions (<code>JSON_NoExceptions</code>), LLVM sanitizers (<code>JSON_Sanitizer</code>), or execution with Valgrind (<code>JSON_Valgrind</code>).</li> <li>Added support for package managers Meson (#576), Conan (#566), Hunter (#671, #829), and vcpkg (#753).</li> <li>Added CI builders: Xcode 8.3, 9.0, 9.1, and 9.2; GCC 7.2; Clang 3.8, 3.9, 4.0, and 5.0; Visual Studio 2017. The library is further built with C++17 settings on the latest Clang, GCC, and MSVC version to quickly detect new issues.</li> </ul>"},{"location":"home/releases/#moving-from-2xx-to-300","title":"Moving from 2.x.x to 3.0.0","text":""},{"location":"home/releases/#user-defined-exceptions","title":"User-defined Exceptions","text":"<p>There are five different exceptions inheriting from <code>json::exception</code>:</p> <ul> <li><code>json::parse_error</code> for syntax errors (including the binary formats),</li> <li><code>json::invalid_iterator</code> for errors related to iterators,</li> <li><code>json::type_error</code> for errors where functions were called with the wrong JSON type,</li> <li><code>json::out_of_range</code> for range errors, and</li> <li><code>json::other_error</code> for miscellaneous errors.</li> </ul> <p>To support these exception, the <code>try</code>/<code>catch</code> blocks of your code need to be adjusted:</p> new exception previous exception parse_error.101 invalid_argument parse_error.102 invalid_argument parse_error.103 invalid_argument parse_error.104 invalid_argument parse_error.105 invalid_argument parse_error.106 domain_error parse_error.107 domain_error parse_error.108 domain_error parse_error.109 invalid_argument parse_error.110 out_of_range parse_error.111 invalid_argument parse_error.112 invalid_argument invalid_iterator.201 domain_error invalid_iterator.202 domain_error invalid_iterator.203 domain_error invalid_iterator.204 out_of_range invalid_iterator.205 out_of_range invalid_iterator.206 domain_error invalid_iterator.207 domain_error invalid_iterator.208 domain_error invalid_iterator.209 domain_error invalid_iterator.210 domain_error invalid_iterator.211 domain_error invalid_iterator.212 domain_error invalid_iterator.213 domain_error invalid_iterator.214 out_of_range type_error.301 domain_error type_error.302 domain_error type_error.303 domain_error type_error.304 domain_error type_error.305 domain_error type_error.306 domain_error type_error.307 domain_error type_error.308 domain_error type_error.309 domain_error type_error.310 domain_error type_error.311 domain_error type_error.313 domain_error type_error.314 domain_error type_error.315 domain_error out_of_range.401 out_of_range out_of_range.402 out_of_range out_of_range.403 out_of_range out_of_range.404 out_of_range out_of_range.405 domain_error other_error.501 domain_error"},{"location":"home/releases/#handling-of-nan-and-inf","title":"Handling of NaN and INF","text":"<ul> <li> <p>If an overflow occurs during parsing a number from a JSON text, an exception <code>json::out_of_range</code> is thrown so that the overflow is detected early and roundtripping is guaranteed.</p> </li> <li> <p>NaN and INF floating-point values can be stored in a JSON value and are not replaced by null. That is, the basic_json class behaves like <code>double</code> in this regard (no exception occurs). However, NaN and INF are serialized to <code>null</code>.</p> </li> </ul>"},{"location":"home/releases/#removal-of-deprecated-functions","title":"Removal of deprecated functions","text":"<p>Function <code>explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr)</code> should be replaced by the <code>parse</code> function: Let <code>ss</code> be a stream and <code>cb</code> be a parse callback function.</p> <p>Old code:</p> <pre><code>json j(ss, cb);\n</code></pre> <p>New code:</p> <pre><code>json j = json::parse(ss, cb);\n</code></pre> <p>If no callback function is used, also the following code works:</p> <pre><code>json j;\nj << ss;\n</code></pre> <p>or</p> <pre><code>json j;\nss >> j;\n</code></pre>"},{"location":"home/releases/#v211","title":"v2.1.1","text":"<p>Files</p> <ul> <li>json.hpp (437 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <p>Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57</p>"},{"location":"home/releases/#summary_15","title":"Summary","text":"<p>This release fixes a locale-related bug in the parser. To do so, the whole number handling (lexer, parser, and also the serialization) have been overworked. Furthermore, a lot of small changes added up that were added to this release. All changes are backward-compatible.</p>"},{"location":"home/releases/#changes_1","title":"Changes","text":"<ul> <li> Locales that have a different character than <code>.</code> as decimal separator (e.g., the Norwegian locale <code>nb_NO.UTF-8</code>) led to truncated number parsing or parse errors. The library now has been fixed to work with any locale. Note that <code>.</code> is still the only valid decimal separator for JSON input.</li> <li> Numbers like <code>1.0</code> were correctly parsed as floating-point number, but serialized as integer (<code>1</code>). Now, floating-point numbers correctly round trip.</li> <li> Parsing incorrect JSON numbers with leading 0 (<code>0123</code>) could yield a buffer overflow. This is fixed now by detecting such errors directly by the lexer.</li> <li> Constructing a JSON value from a pointer was incorrectly interpreted as a Boolean; such code will now yield a compiler error.</li> <li> Comparing a JSON number with <code>0</code> led to a comparison with <code>null</code>. This is fixed now.</li> <li> All throw calls are now wrapped in macros.</li> <li> Starting during the preparation of this release (since 8 February 2017), commits and released files are cryptographically signed with this GPG key. Previous releases have also been signed.</li> <li> The parser for MessagePack and CBOR now supports an optional start index parameter to define a byte offset for the parser.</li> <li> Some more warnings have been fixed. With Clang, the code compiles without warnings with <code>-Weverything</code> (well, it needs <code>-Wno-documentation-unknown-command</code> and <code>-Wno-deprecated-declarations</code>, but you get the point).</li> <li> The code can be compiled easier with many Android NDKs by avoiding macros like <code>UINT8_MAX</code> which previously required defining a preprocessor macro for compilation.</li> <li> The unit tests now compile two times faster.</li> <li> Cotire is used to speed up the build.</li> <li> Fixed a lot of typos in the documentation.</li> <li> Added a section to the README file that lists all used third-party code/tools.</li> <li> Added a note on constructing a string value vs. parsing.</li> <li> The test suite now contains 11202597 unit tests.</li> <li> Improved the Doxygen documentation by shortening the template parameters of class <code>basic_json</code>.</li> <li> Removed Doozer.</li> <li> Added Codacity.</li> <li> Upgraded Catch to version 1.7.2.</li> </ul>"},{"location":"home/releases/#v210","title":"v2.1.0","text":"<p>Files</p> <ul> <li>json.hpp (426 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2017-01-28</li> <li>SHA-256: a571dee92515b685784fd527e38405cf3f5e13e96edbfe3f03d6df2e363a767b</li> </ul>"},{"location":"home/releases/#summary_16","title":"Summary","text":"<p>This release introduces a means to convert from/to user-defined types. The release is backwards compatible.</p> <p></p>"},{"location":"home/releases/#changes_2","title":"Changes","text":"<ul> <li> The library now offers an elegant way to convert from and to arbitrary value types. All you need to do is to implement two functions: <code>to_json</code> and <code>from_json</code>. Then, a conversion is as simple as putting a <code>=</code> between variables. See the README for more information and examples.</li> <li> Exceptions can now be switched off. This can be done by defining the preprocessor symbol <code>JSON_NOEXCEPTION</code> or by passing <code>-fno-exceptions</code> to your compiler. In case the code would usually thrown an exception, <code>abort()</code> is now called.</li> <li> Information on the library can be queried with the new (static) function <code>meta()</code> which returns a JSON object with information on the version, compiler, and platform. See the documentation for an example.</li> <li> A bug in the CBOR parser was fixed which led to a buffer overflow.</li> <li> The function <code>type_name()</code> is now public. It allows to query the type of a JSON value as string.</li> <li> Added the Big List of Naughty Strings as test case.</li> <li> Updated to Catch v1.6.0.</li> <li> Some typos in the documentation have been fixed.</li> </ul>"},{"location":"home/releases/#v2010","title":"v2.0.10","text":"<p>Files</p> <ul> <li>json.hpp (409 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2017-01-02</li> <li>SHA-256: ec27d4e74e9ce0f78066389a70724afd07f10761009322dc020656704ad5296d</li> </ul>"},{"location":"home/releases/#summary_17","title":"Summary","text":"<p>This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.</p>"},{"location":"home/releases/#changes_3","title":"Changes","text":"<ul> <li> Fixed a lot of bugs in the CBOR and MesssagePack parsers. These bugs occurred if invalid input was parsed and then could lead in buffer overflows. These bugs were found with Google's OSS-Fuzz, see #405, #407, #408, #409, #411, and #412 for more information.</li> <li> We now also use the Doozer continuous integration platform.</li> <li> The complete test suite is now also run with Clang's address sanitizer and undefined-behavior sanitizer.</li> <li> Overworked fuzz testing; CBOR and MessagePack implementations are now fuzz-tested. Furthermore, all fuzz tests now include a round trip which ensures created output can again be properly parsed and yields the same JSON value.</li> <li> Clarified documentation of <code>find()</code> function to always return <code>end()</code> when called on non-object value types.</li> <li> Moved thirdparty test code to <code>test/thirdparty</code> directory.</li> </ul>"},{"location":"home/releases/#v209","title":"v2.0.9","text":"<p>Files</p> <ul> <li>json.hpp (406 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-12-16</li> <li>SHA-256: fbf3396f13e187d6c214c297bddc742d918ea9b55e10bfb3d9f458b9bfdc22e5</li> </ul>"},{"location":"home/releases/#summary_18","title":"Summary","text":"<p>This release implements with CBOR and MessagePack two binary serialization/deserialization formats. It further contains some small fixes and improvements. The fixes are backwards compatible.</p> <p></p>"},{"location":"home/releases/#changes_4","title":"Changes","text":"<ul> <li> The library can now read and write the binary formats CBOR (Concise Binary Object Representation) and MessagePack. Both formats are aimed to produce a very compact representation of JSON which can be parsed very efficiently. See the README file for more information and examples.</li> <li> simplified the iteration implementation allowing to remove dozens of lines of code</li> <li> fixed an integer overflow error detected by Google's OSS-Fuzz</li> <li> suppressed documentation warnings inside the library to facilitate compilation with <code>-Wdocumentation</code></li> <li> fixed an overflow detection error in the number parser</li> <li> updated contribution guidelines to a list of frequentely asked features that will most likely be never added to the library</li> <li> added a table of contents to the README file to add some structure</li> <li> mentioned the many examples and the documentation in the README file</li> <li> split unit tests into individual independent binaries to speed up compilation and testing</li> <li> the test suite now contains 11201886 tests</li> </ul>"},{"location":"home/releases/#v208","title":"v2.0.8","text":"<p>Files</p> <ul> <li>json.hpp (360 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-12-02</li> <li>SHA-256: b70db0ad34f8e0e61dc3f0cbab88099336c9674c193d8a3439d93d6aca2d7120</li> </ul>"},{"location":"home/releases/#summary_19","title":"Summary","text":"<p>This release combines a lot of small fixes and improvements. The fixes are backwards compatible.</p>"},{"location":"home/releases/#changes_5","title":"Changes","text":"<ul> <li> fixed a bug that froze the parser if a passed file was not found (now, <code>std::invalid_argument</code> is thrown)</li> <li> fixed a bug that lead to an error of a file at EOF was parsed again (now, <code>std::invalid_argument</code> is thrown)</li> <li> the well known functions <code>emplace</code> and <code>emplace_back</code> have been added to JSON values and work as expected</li> <li> improved the performance of the serialization (<code>dump</code> function)</li> <li> improved the performance of the deserialization (parser)</li> <li> some continuous integration images at Travis were added and retired; see here for the current continuous integration setup</li> <li> the Coverity scan works again</li> <li> the benchmarking code has been improved to produce more stable results</li> <li> the README file has been extended and includes more frequently asked examples</li> <li> the test suite now contains 8905518 tests</li> <li> updated Catch to version 1.5.8</li> </ul>"},{"location":"home/releases/#v207","title":"v2.0.7","text":"<p>Files</p> <ul> <li>json.hpp (355 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-11-02</li> <li>SHA-256: 5545c323670f8165bae90b9dc6078825e86ec310d96cc4e5b47233ea43715bbf</li> </ul>"},{"location":"home/releases/#summary_20","title":"Summary","text":"<p>This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible.</p>"},{"location":"home/releases/#changes_6","title":"Changes","text":"<ul> <li>The article Parsing JSON is a Minefield \ud83d\udca3 discusses a lot of pitfalls of the JSON specification. When investigating the published test cases, a few bugs in the library were found and fixed:</li> <li>Files with less than 5 bytes can now be parsed without error.</li> <li>The library now properly rejects any file encoding other than UTF-8. Furthermore, incorrect surrogate pairs are properly detected and rejected.</li> <li>The library now accepts all but one \"yes\" test (y_string_utf16.json): UTF-16 is not supported.</li> <li>The library rejects all but one \"no\" test (n_number_then_00.json): Null bytes are treated as end of file instead of an error. This allows to parse input from null-terminated strings.</li> <li>The string length passed to a user-defined string literal is now exploited to choose a more efficient constructor.</li> <li>A few grammar mistakes in the README file have been fixed.</li> </ul>"},{"location":"home/releases/#v206","title":"v2.0.6","text":"<p>Files</p> <ul> <li>json.hpp (349 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-10-15</li> <li>SHA256: 459cc93d5e2f503e50c6d5876eb86bfea7daf405f5a567c5a2c9abc2383756ae</li> </ul>"},{"location":"home/releases/#summary_21","title":"Summary","text":"<p>This release fixes the semantics of <code>operator[]</code> for JSON Pointers (see below). This fix is backwards compatible.</p>"},{"location":"home/releases/#changes_7","title":"Changes","text":"<ul> <li><code>operator[]</code> for JSON Pointers now behaves like the other versions of <code>operator[]</code> and transforms <code>null</code> values into objects or arrays if required. This allows to created nested structures like <code>j[\"/foo/bar/2\"] = 17</code> (yielding <code>{\"foo\": \"bar\": [null, null, 17]}</code>) without problems.</li> <li>overworked a helper SFINAE function</li> <li>fixed some documentation issues</li> <li>fixed the CMake files to allow to run the test suite outside the main project directory</li> <li>restored test coverage to 100%.</li> </ul>"},{"location":"home/releases/#v205","title":"v2.0.5","text":"<p>Files</p> <ul> <li>json.hpp (347 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-09-14</li> <li>SHA-256: 8b7565263a44e2b7d3b89808bc73d2d639037ff0c1f379e3d56dbd77e00b98d9</li> </ul>"},{"location":"home/releases/#summary_22","title":"Summary","text":"<p>This release fixes a regression bug in the stream parser (function <code>parse()</code> and the <code><<</code>/<code>>></code> operators). This fix is backwards compatible.</p>"},{"location":"home/releases/#changes_8","title":"Changes","text":"<ul> <li>Bug fix: The end of a file stream was not detected properly which led to parse errors. This bug should have been fixed with 2.0.4, but there was still a flaw in the code.</li> </ul>"},{"location":"home/releases/#v204","title":"v2.0.4","text":"<p>Files</p> <ul> <li>json.hpp (347 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-09-11</li> <li>SHA-256: 632ceec4c25c4e2153f71470d3a2b992c8355f6d8b4d627d05dd16095cd3aeda</li> </ul>"},{"location":"home/releases/#summary_23","title":"Summary","text":"<p>This release fixes a bug in the stream parser (function <code>parse()</code> and the <code><<</code>/<code>>></code> operators). This fix is backwards compatible.</p>"},{"location":"home/releases/#changes_9","title":"Changes","text":"<ul> <li>Bug fix: The end of a file stream was not detected properly which led to parse errors.</li> <li>Fixed a compiler warning about an unused variable.</li> </ul>"},{"location":"home/releases/#v203","title":"v2.0.3","text":"<p>Files</p> <ul> <li>json.hpp (347 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-08-31</li> <li>SHA-256: 535b73efe5546fde9e763c14aeadfc7b58183c0b3cd43c29741025aba6cf6bd3</li> </ul>"},{"location":"home/releases/#summary_24","title":"Summary","text":"<p>This release combines a lot of small fixes and improvements. The release is backwards compatible.</p>"},{"location":"home/releases/#changes_10","title":"Changes","text":"<ul> <li>The parser/deserialization functions have been generalized to process any contiguous sequence of 1-byte elements (e.g., <code>char</code>, <code>unsigned char</code>, <code>uint8_t</code>). This includes all kind of string representations (string literals, char arrays, <code>std::string</code>, <code>const char*</code>), contiguous containers (C-style arrays, <code>std::vector</code>, <code>std::array</code>, <code>std::valarray</code>, <code>std::initializer_list</code>). User-defined containers providing random-access iterator access via <code>std::begin</code> and <code>std::end</code> can be used as well. See the documentation (1, 2, 3, 4) for more information. Note that contiguous storage cannot be checked at compile time; if any of the parse functions are called with a noncompliant container, the behavior is undefined and will most likely yield segmentation violation. The preconditions are enforced by an assertion unless the library is compiled with preprocessor symbol <code>NDEBUG</code>.</li> <li>As a general remark on assertions: The library uses assertions to preclude undefined behavior. A prominent example for this is the <code>operator[]</code> for const JSON objects. The behavior of this const version of the operator is undefined if the given key does not exist in the JSON object, because unlike the non-const version, it cannot add a <code>null</code> value at the given key. Assertions can be switched of by defining the preprocessor symbol <code>NDEBUG</code>. See the documentation of <code>assert</code> for more information.</li> <li>In the course of cleaning up the parser/deserialization functions, the constructor <code>basic_json(std::istream&, const parser_callback_t)</code> has been deprecated and will be deleted with the next major release 3.0.0 to unify the interface of the library. Deserialization will be done by stream operators or by calling one of the <code>parse</code> functions. That is, calls like <code>json j(i);</code> for an input stream <code>i</code> need to be replaced by <code>json j = json::parse(i);</code>. Compilers will produce a deprecation warning if client code uses this function.</li> <li>Minor improvements:</li> <li>Improved the performance of the serialization by avoiding the re-creation of a locale object.</li> <li>Fixed two MSVC warnings. Compiling the test suite with <code>/Wall</code> now only warns about non-inlined functions (C4710) and the deprecation of the constructor from input-stream (C4996).</li> <li>Some project internals:</li> <li> The project has qualified for the Core Infrastructure Initiative Best Practices Badge. While most requirements where already satisfied, some led to a more explicit documentation of quality-ensuring procedures. For instance, static analysis is now executed with every commit on the build server. Furthermore, the contribution guidelines document how to communicate security issues privately.</li> <li>The test suite has been overworked and split into several files to allow for faster compilation and analysis. The execute the test suite, simply execute <code>make check</code>.</li> <li>The continuous integration with Travis was extended with Clang versions 3.6.0 to 3.8.1 and now includes 18 different compiler/OS combinations.</li> <li>An 11-day run of American fuzzy lop checked 962 million inputs on the parser and found no issue.</li> </ul>"},{"location":"home/releases/#v202","title":"v2.0.2","text":"<p>Files</p> <ul> <li>json.hpp (338 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-07-31</li> <li>SHA-256: 8e97b7965b4594b00998d6704465412360e1a0ed927badb51ded8b82291a8f3d</li> </ul>"},{"location":"home/releases/#summary_25","title":"Summary","text":"<p>This release combines a lot of small fixes and improvements. The release is backwards compatible.</p>"},{"location":"home/releases/#changes_11","title":"Changes","text":"<ul> <li>The parser has been overworked, and a lot of small issues have been fixed:</li> <li>Improved parser performance by avoiding recursion and using move semantics for the return value.</li> <li>Unescaped control characters <code>\\x10</code>-<code>\\x1f</code> are not accepted any more.</li> <li>Fixed a bug in the parser when reading from an input stream.</li> <li>Improved test case coverage for UTF-8 parsing: now, all valid Unicode code points are tested both escaped and unescaped.</li> <li>The precision of output streams is now preserved by the parser.</li> <li>Started to check the code correctness by proving termination of important loops. Furthermore, individual assertions have been replaced by a more systematic function which checks the class invariants. Note that assertions should be switched off in production by defining the preprocessor macro <code>NDEBUG</code>, see the documentation of <code>assert</code>.</li> <li>A lot of code cleanup: removed unused headers, fixed some compiler warnings, and fixed a build error for Windows-based Clang builds.</li> <li>Added some compile-time checks:</li> <li>Unsupported compilers are rejected during compilation with an <code>#error</code> command.</li> <li>Static assertion prohibits code with incompatible pointer types used in <code>get_ptr()</code>.</li> <li>Improved the documentation, and adjusted the documentation script to choose the correct version of <code>sed</code>.</li> <li>Replaced a lot of \"raw loops\" by STL functions like <code>std::all_of</code>, <code>std::for_each</code>, or <code>std::accumulate</code>. This facilitates reasoning about termination of loops and sometimes allowed to simplify functions to a single return statement.</li> <li>Implemented a <code>value()</code> function for JSON pointers (similar to <code>at</code> function).</li> <li>The Homebrew formula (see Integration) is now tested for all Xcode builds (6.1 - 8.x) with Travis.</li> <li>Avoided output to <code>std::cout</code> in the test cases.</li> </ul>"},{"location":"home/releases/#v201","title":"v2.0.1","text":"<p>Files</p> <ul> <li>json.hpp (321 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-06-28</li> <li>SHA-256: ef550fcd7df572555bf068e9ec4e9d3b9e4cdd441cecb0dcea9ea7fd313f72dd</li> </ul>"},{"location":"home/releases/#summary_26","title":"Summary","text":"<p>This release fixes a performance regression in the JSON serialization (function <code>dump()</code>). This fix is backwards compatible.</p>"},{"location":"home/releases/#changes_12","title":"Changes","text":"<ul> <li>The locale of the output stream (or the internal string stream if a JSON value is serialized to a string) is now adjusted once for the whole serialization instead of for each floating-point number.</li> <li>The locale of an output stream is now correctly reset to the previous value by the JSON library.</li> </ul>"},{"location":"home/releases/#v200","title":"v2.0.0","text":"<p>Files</p> <ul> <li>json.hpp (321 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-06-24</li> <li>SHA-256: ac9e1fb25c2ac9ca5fc501fcd2fe3281fe04f07018a1b48820e7b1b11491bb6c</li> </ul>"},{"location":"home/releases/#summary_27","title":"Summary","text":"<p>This release adds several features such as JSON Pointers, JSON Patch, or support for 64 bit unsigned integers. Furthermore, several (subtle) bugs have been fixed.</p> <p>As <code>noexcept</code> and <code>constexpr</code> specifier have been added to several functions, the public API has effectively been changed in a (potential) non-backwards compatible manner. As we adhere to Semantic Versioning, this calls for a new major version, so say hello to 2\ufe0f\u20e3.0\ufe0f\u20e3.0\ufe0f\u20e3.</p>"},{"location":"home/releases/#changes_13","title":"Changes","text":"<ul> <li>\ud83d\udd1f A JSON value now uses <code>uint64_t</code> (default value for template parameter <code>NumberUnsignedType</code>) as data type for unsigned integer values. This type is used automatically when an unsigned number is parsed. Furthermore, constructors, conversion operators and an <code>is_number_unsigned()</code> test have been added.</li> <li>\ud83d\udc49 JSON Pointer (RFC 6901) support: A JSON Pointer is a string (similar to an XPath expression) to address a value inside a structured JSON value. JSON Pointers can be used in <code>at()</code> and <code>operator[]</code> functions. Furthermore, JSON values can be \u201cflattened\u201d to key/value pairs using <code>flatten()</code> where each key is a JSON Pointer. The original value can be restored by \u201cunflattening\u201d the flattened value using <code>unflatten()</code>.</li> <li>\ud83c\udfe5 JSON Patch (RFC 6902) support. A JSON Patch is a JSON value that describes the required edit operations (add, change, remove, \u2026) to transform a JSON value into another one. A JSON Patch can be created with function <code>diff(const basic_json&)</code> and applied with <code>patch(const basic_json&)</code>. Note the created patches use a rather primitive algorithm so far and leave room for improvement.</li> <li>\ud83c\uddea\ud83c\uddfa The code is now locale-independent: Floating-point numbers are always serialized with a period (<code>.</code>) as decimal separator and ignores different settings from the locale.</li> <li>\ud83c\udf7a Homebrew support: Install the library with <code>brew tap nlohmann/json && brew install nlohmann_json</code>.</li> <li>Added constructor to create a JSON value by parsing a <code>std::istream</code> (e.g., <code>std::stringstream</code> or <code>std::ifstream</code>).</li> <li>Added <code>noexcept</code> specifier to <code>basic_json(boolean_t)</code>, <code>basic_json(const number_integer_t)</code>, <code>basic_json(const int)</code>, <code>basic_json(const number_float_t)</code>, iterator functions (<code>begin()</code>, <code>end()</code>, etc.)</li> <li>When parsing numbers, the sign of <code>0.0</code> (vs. <code>-0.0</code>) is preserved.</li> <li>Improved MSVC 2015, Android, and MinGW support. See README for more information.</li> <li>Improved test coverage (added 2,225,386 tests).</li> <li>Removed some misuses of <code>std::move</code>.</li> <li>Fixed several compiler warnings.</li> <li>Improved error messages from JSON parser.</li> <li>Updated to <code>re2c</code> to version 0.16 to use a minimal DFAs for the lexer.</li> <li>Updated test suite to use Catch version 1.5.6.</li> <li>Made type getters (<code>is_number</code>, etc.) and const value access <code>constexpr</code>.</li> <li>Functions <code>push_back</code> and <code>operator+=</code> now work with key/value pairs passed as initializer list, e.g. <code>j_object += {\"key\", 1}</code>.</li> <li>Overworked <code>CMakeLists.txt</code> to make it easier to integrate the library into other projects.</li> </ul>"},{"location":"home/releases/#notes","title":"Notes","text":"<ul> <li>Parser error messages are still very vague and contain no information on the error location.</li> <li>The implemented <code>diff</code> function is rather primitive and does not create minimal diffs.</li> <li>The name of function <code>iteration_wrapper</code> may change in the future and the function will be deprecated in the next release.</li> <li>Roundtripping (i.e., parsing a JSON value from a string, serializing it, and comparing the strings) of floating-point numbers is not 100% accurate. Note that RFC 8259 defines no format to internally represent numbers and states not requirement for roundtripping. Nevertheless, benchmarks like Native JSON Benchmark treat roundtripping deviations as conformance errors.</li> </ul>"},{"location":"home/releases/#v110","title":"v1.1.0","text":"<p>Files</p> <ul> <li>json.hpp (257 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2016-01-24</li> <li>SHA-256: c0cf0e3017798ca6bb18e757ebc570d21a3bdac877845e2b9e9573d183ed2f05</li> </ul>"},{"location":"home/releases/#summary_28","title":"Summary","text":"<p>This release fixes several small bugs and adds functionality in a backwards-compatible manner. Compared to the last version (1.0.0), the following changes have been made:</p>"},{"location":"home/releases/#changes_14","title":"Changes","text":"<ul> <li>Fixed: Floating-point numbers are now serialized and deserialized properly such that rountripping works in more cases. [#185, #186, #190, #191, #194]</li> <li>Added: The code now contains assertions to detect undefined behavior during development. As the standard function <code>assert</code> is used, the assertions can be switched off by defining the preprocessor symbol <code>NDEBUG</code> during compilation. [#168]</li> <li>Added: It is now possible to get a reference to the stored values via the newly added function <code>get_ref()</code>. [#128, #184]</li> <li>Fixed: Access to object values via keys (<code>operator[]</code>) now works with all kind of string representations. [#171, #189]</li> <li>Fixed: The code now compiles again with Microsoft Visual Studio 2015. [#144, #167, #188]</li> <li>Fixed: All required headers are now included.</li> <li>Fixed: Typos and other small issues. [#162, #166, #175, #177, #179, #180]</li> </ul>"},{"location":"home/releases/#notes_1","title":"Notes","text":"<p>There are still known open issues (#178, #187) which will be fixed in version 2.0.0. However, these fixes will require a small API change and will not be entirely backwards-compatible.</p>"},{"location":"home/releases/#v100","title":"v1.0.0","text":"<p>Files</p> <ul> <li>json.hpp (243 KB)</li> <li>json.hpp.asc (1 KB)</li> </ul> <ul> <li>Release date: 2015-12-28</li> <li>SHA-256: 767dc2fab1819d7b9e19b6e456d61e38d21ef7182606ecf01516e3f5230446de</li> </ul>"},{"location":"home/releases/#summary_29","title":"Summary","text":"<p>This is the first official release. Compared to the prerelease version 1.0.0-rc1, only a few minor improvements have been made:</p>"},{"location":"home/releases/#changes_15","title":"Changes","text":"<ul> <li>Changed: A UTF-8 byte order mark is silently ignored.</li> <li>Changed: <code>sprintf</code> is no longer used.</li> <li>Changed: <code>iterator_wrapper</code> also works for const objects; note: the name may change!</li> <li>Changed: Error messages during deserialization have been improved.</li> <li>Added: The <code>parse</code> function now also works with type <code>std::istream&&</code>.</li> <li>Added: Function <code>value(key, default_value)</code> returns either a copy of an object's element at the specified key or a given default value if no element with the key exists.</li> <li>Added: Public functions are tagged with the version they were introduced. This shall allow for better versioning in the future.</li> <li>Added: All public functions and types are documented (see http://nlohmann.github.io/json/doxygen/) including executable examples.</li> <li>Added: Allocation of all types (in particular arrays, strings, and objects) is now exception-safe.</li> <li>Added: They descriptions of thrown exceptions have been overworked and are part of the tests suite and documentation.</li> </ul>"},{"location":"home/sponsors/","title":"Sponsors","text":"<p>You can sponsor this library at GitHub Sponsors.</p>"},{"location":"home/sponsors/#named-sponsors","title":"Named Sponsors","text":"<ul> <li>Michael Hartmann</li> <li>Stefan Hagen</li> <li>Steve Sperandeo</li> <li>Robert Jefe Lindst\u00e4dt</li> <li>Steve Wagner</li> </ul> <p>Thanks everyone!</p>"},{"location":"integration/","title":"Header only","text":"<p><code>json.hpp</code> is the single required file in <code>single_include/nlohmann</code> or released here. You need to add</p> <pre><code>#include <nlohmann/json.hpp>\n\n// for convenience\nusing json = nlohmann::json;\n</code></pre> <p>to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., <code>-std=c++11</code> for GCC and Clang).</p> <p>You can further use file <code>single_include/nlohmann/json_fwd.hpp</code> for forward declarations.</p>"},{"location":"integration/cmake/","title":"CMake","text":""},{"location":"integration/cmake/#integration","title":"Integration","text":"<p>You can use the <code>nlohmann_json::nlohmann_json</code> interface target in CMake. This target populates the appropriate usage requirements for <code>INTERFACE_INCLUDE_DIRECTORIES</code> to point to the appropriate include directories and <code>INTERFACE_COMPILE_FEATURES</code> for the necessary C++11 flags.</p>"},{"location":"integration/cmake/#external","title":"External","text":"<p>To use this library from a CMake project, you can locate it directly with <code>find_package()</code> and use the namespaced imported target from the generated package configuration:</p> <p>Example</p> CMakeLists.txt<pre><code>cmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\nfind_package(nlohmann_json 3.11.3 REQUIRED)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n</code></pre> <p>The package configuration file, <code>nlohmann_jsonConfig.cmake</code>, can be used either from an install tree or directly out of the build tree.</p>"},{"location":"integration/cmake/#embedded","title":"Embedded","text":"<p>To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call <code>add_subdirectory()</code> in your <code>CMakeLists.txt</code> file.</p> <p>Example</p> CMakeLists.txt<pre><code>cmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\n# If you only include this third party in PRIVATE source files, you do not need to install it\n# when your main project gets installed.\nset(JSON_Install OFF CACHE INTERNAL \"\")\n\nadd_subdirectory(nlohmann_json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n</code></pre> <p>Note</p> <p>Do not use <code>include(nlohmann_json/CMakeLists.txt)</code>, since that carries with it unintended consequences that will break the build. It is generally discouraged (although not necessarily well documented as such) to use <code>include(...)</code> for pulling in other CMake projects anyways.</p>"},{"location":"integration/cmake/#supporting-both","title":"Supporting Both","text":"<p>To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.</p> <p>Example</p> CMakeLists.txt<pre><code>project(ExampleProject LANGUAGES CXX)\n\noption(EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF)\n\nadd_subdirectory(thirdparty)\n\nadd_executable(example example.cpp)\n\n# Note that the namespaced target will always be available regardless of the import method\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n</code></pre> thirdparty/CMakeLists.txt<pre><code>if(EXAMPLE_USE_EXTERNAL_JSON)\n find_package(nlohmann_json 3.11.3 REQUIRED)\nelse()\n set(JSON_BuildTests OFF CACHE INTERNAL \"\")\n add_subdirectory(nlohmann_json)\nendif()\n</code></pre> <p><code>thirdparty/nlohmann_json</code> is then a complete copy of this source tree.</p>"},{"location":"integration/cmake/#fetchcontent","title":"FetchContent","text":"<p>Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type.</p> <p>Example</p> CMakeLists.txt<pre><code>cmake_minimum_required(VERSION 3.11)\nproject(ExampleProject LANGUAGES CXX)\n\ninclude(FetchContent)\n\nFetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)\nFetchContent_MakeAvailable(json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n</code></pre> <p>Note</p> <p>It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like</p> <pre><code>FetchContent_Declare(json\n GIT_REPOSITORY https://github.com/nlohmann/json\n GIT_TAG v3.11.3\n)\n</code></pre> <p>However, the repository https://github.com/nlohmann/json download size is quite large. You might want to depend on a smaller repository. For instance, you might want to replace the URL in the example by https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent.</p>"},{"location":"integration/cmake/#cmake-options","title":"CMake Options","text":""},{"location":"integration/cmake/#json_buildtests","title":"<code>JSON_BuildTests</code>","text":"<p>Build the unit tests when <code>BUILD_TESTING</code> is enabled. This option is <code>ON</code> by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option.</p>"},{"location":"integration/cmake/#json_ci","title":"<code>JSON_CI</code>","text":"<p>Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is <code>OFF</code> by default.</p>"},{"location":"integration/cmake/#json_diagnostics","title":"<code>JSON_Diagnostics</code>","text":"<p>Enable extended diagnostic messages by defining macro <code>JSON_DIAGNOSTICS</code>. This option is <code>OFF</code> by default.</p>"},{"location":"integration/cmake/#json_disableenumserialization","title":"<code>JSON_DisableEnumSerialization</code>","text":"<p>Disable default <code>enum</code> serialization by defining the macro <code>JSON_DISABLE_ENUM_SERIALIZATION</code>. This option is <code>OFF</code> by default.</p>"},{"location":"integration/cmake/#json_fasttests","title":"<code>JSON_FastTests</code>","text":"<p>Skip expensive/slow test suites. This option is <code>OFF</code> by default. Depends on <code>JSON_BuildTests</code>.</p>"},{"location":"integration/cmake/#json_globaludls","title":"<code>JSON_GlobalUDLs</code>","text":"<p>Place user-defined string literals in the global namespace by defining the macro <code>JSON_USE_GLOBAL_UDLS</code>. This option is <code>OFF</code> by default.</p>"},{"location":"integration/cmake/#json_implicitconversions","title":"<code>JSON_ImplicitConversions</code>","text":"<p>Enable implicit conversions by defining macro <code>JSON_USE_IMPLICIT_CONVERSIONS</code>. This option is <code>ON</code> by default.</p>"},{"location":"integration/cmake/#json_install","title":"<code>JSON_Install</code>","text":"<p>Install CMake targets during install step. This option is <code>ON</code> by default if the library's CMake project is the top project.</p>"},{"location":"integration/cmake/#json_multipleheaders","title":"<code>JSON_MultipleHeaders</code>","text":"<p>Use non-amalgamated version of the library. This option is <code>OFF</code> by default.</p>"},{"location":"integration/cmake/#json_systeminclude","title":"<code>JSON_SystemInclude</code>","text":"<p>Treat the library headers like system headers (i.e., adding <code>SYSTEM</code> to the <code>target_include_directories</code> call) to checks for this library by tools like Clang-Tidy. This option is <code>OFF</code> by default.</p>"},{"location":"integration/cmake/#json_valgrind","title":"<code>JSON_Valgrind</code>","text":"<p>Execute test suite with Valgrind. This option is <code>OFF</code> by default. Depends on <code>JSON_BuildTests</code>.</p>"},{"location":"integration/migration_guide/","title":"Migration Guide","text":"<p>This page collects some guidelines on how to future-proof your code for future versions of this library.</p>"},{"location":"integration/migration_guide/#replace-deprecated-functions","title":"Replace deprecated functions","text":"<p>The following functions have been deprecated and will be removed in the next major version (i.e., 4.0.0). All deprecations are annotated with <code>HEDLEY_DEPRECATED_FOR</code> to report which function to use instead.</p>"},{"location":"integration/migration_guide/#parsing","title":"Parsing","text":"<ul> <li> <p>Function <code>friend std::istream& operator<<(basic_json&, std::istream&)</code> is deprecated since 3.0.0. Please use <code>friend std::istream& operator>>(std::istream&, basic_json&)</code> instead.</p> DeprecatedFuture-proof <pre><code>nlohmann::json j;\nstd::stringstream ss(\"[1,2,3]\");\nj << ss;\n</code></pre> <pre><code>nlohmann::json j;\nstd::stringstream ss(\"[1,2,3]\");\nss >> j;\n</code></pre> </li> <li> <p>Passing iterator pairs or pointer/length pairs to parsing functions (<code>parse</code>, <code>accept</code>, <code>sax_parse</code>, <code>from_cbor</code>, <code>from_msgpack</code>, <code>from_ubjson</code>, and <code>from_bson</code> via initializer lists is deprecated since 3.8.0. Instead, pass two iterators; for instance, call <code>from_cbor(ptr, ptr+len)</code> instead of <code>from_cbor({ptr, len})</code>.</p> DeprecatedFuture-proof <pre><code>const char* s = \"[1,2,3]\";\nbool ok = nlohmann::json::accept({s, s + std::strlen(s)});\n</code></pre> <pre><code>const char* s = \"[1,2,3]\";\nbool ok = nlohmann::json::accept(s, s + std::strlen(s));\n</code></pre> </li> </ul>"},{"location":"integration/migration_guide/#json-pointers","title":"JSON Pointers","text":"<ul> <li> <p>Comparing JSON Pointers with strings via <code>operator==</code> and <code>operator!=</code> is deprecated since 3.11.2. To compare a <code>json_pointer</code> <code>p</code> with a string <code>s</code>, convert <code>s</code> to a <code>json_pointer</code> first and use <code>json_pointer::operator==</code> or <code>json_pointer::operator!=</code>.</p> DeprecatedFuture-proof <pre><code>nlohmann::json::json_pointer lhs(\"/foo/bar/1\");\nassert(lhs == \"/foo/bar/1\");\n</code></pre> <pre><code>nlohmann::json::json_pointer lhs(\"/foo/bar/1\");\nassert(lhs == nlohmann::json::json_pointer(\"/foo/bar/1\"));\n</code></pre> </li> <li> <p>The implicit conversion from JSON Pointers to string (<code>json_pointer::operator string_t</code>) is deprecated since 3.11.0. Use <code>json_pointer::to_string</code> instead.</p> DeprecatedFuture-proof <pre><code>nlohmann::json::json_pointer ptr(\"/foo/bar/1\");\nstd::string s = ptr;\n</code></pre> <pre><code>nlohmann::json::json_pointer ptr(\"/foo/bar/1\");\nstd::string s = ptr.to_string();\n</code></pre> </li> <li> <p>Passing a <code>basic_json</code> specialization as template parameter <code>RefStringType</code> to <code>json_pointer</code> is deprecated since 3.11.0. The string type can now be directly provided.</p> DeprecatedFuture-proof <pre><code>using my_json = nlohmann::basic_json<std::map, std::vector, my_string_type>;\nnlohmann::json_pointer<my_json> ptr(\"/foo/bar/1\");\n</code></pre> <pre><code>nlohmann::json_pointer<my_string_type> ptr(\"/foo/bar/1\");\n</code></pre> <p>Thereby, <code>nlohmann::my_json::json_pointer</code> is an alias for <code>nlohmann::json_pointer<my_string_type></code> and is always an alias to the <code>json_pointer</code> with the appropriate string type for all specializations of <code>basic_json</code>.</p> </li> </ul>"},{"location":"integration/migration_guide/#miscellaneous-functions","title":"Miscellaneous functions","text":"<ul> <li> <p>The function <code>iterator_wrapper</code> is deprecated since 3.1.0. Please use the member function <code>items</code> instead.</p> DeprecatedFuture-proof <pre><code>for (auto &x : nlohmann::json::iterator_wrapper(j))\n{\n std::cout << x.key() << \":\" << x.value() << std::endl;\n}\n</code></pre> <pre><code>for (auto &x : j.items())\n{\n std::cout << x.key() << \":\" << x.value() << std::endl;\n}\n</code></pre> </li> <li> <p>Function <code>friend std::ostream& operator>>(const basic_json&, std::ostream&)</code> is deprecated since 3.0.0. Please use <code>friend operator<<(std::ostream&, const basic_json&)</code> instead.</p> DeprecatedFuture-proof <pre><code>j >> std::cout;\n</code></pre> <pre><code>std::cout << j;\n</code></pre> </li> <li> <p>The legacy comparison behavior for discarded values is deprecated since 3.11.0. It is already disabled by default and can still be enabled by defining <code>JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON</code> to <code>1</code>.</p> DeprecatedFuture-proof <pre><code>#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n</code></pre> <pre><code>#include <nlohmann/json.hpp>\n</code></pre> </li> </ul>"},{"location":"integration/migration_guide/#replace-implicit-conversions","title":"Replace implicit conversions","text":"<p>Implicit conversions via <code>operator ValueType</code> will be switched off by default in the next major release of the library.</p> <p>You can prepare existing code by already defining <code>JSON_USE_IMPLICIT_CONVERSIONS</code> to <code>0</code> and replace any implicit conversions with calls to <code>get</code>, <code>get_to</code>, <code>get_ref</code>, or <code>get_ptr</code>.</p> DeprecatedFuture-proofFuture-proof (alternative) <pre><code>nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n</code></pre> <pre><code>nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n</code></pre> <pre><code>nlohmann::json j = \"Hello, world!\";\nstd::string s;\nj.get_to(s);\n</code></pre> <p>You can prepare existing code by already defining <code>JSON_USE_IMPLICIT_CONVERSIONS</code> to <code>0</code> and replace any implicit conversions with calls to <code>get</code>.</p>"},{"location":"integration/migration_guide/#import-namespace-literals-for-udls","title":"Import namespace <code>literals</code> for UDLs","text":"<p>The user-defined string literals <code>operator\"\"_json</code> and <code>operator\"\"_json_pointer</code> will be removed from the global namespace in the next major release of the library.</p> DeprecatedFuture-proof <pre><code>nlohmann::json j = \"[1,2,3]\"_json;\n</code></pre> <pre><code>using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n</code></pre> <p>To prepare existing code, define <code>JSON_USE_GLOBAL_UDLS</code> to <code>0</code> and bring the string literals into scope where needed.</p>"},{"location":"integration/migration_guide/#do-not-hard-code-the-complete-library-namespace","title":"Do not hard-code the complete library namespace","text":"<p>The <code>nlohmann</code> namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use <code>nlohmann</code> as namespace or, when the exact version and configuration is relevant, use macro <code>NLOHMANN_JSON_NAMESPACE</code> to denote the namespace.</p> DangerousFuture-proofFuture-proof (alternative) <pre><code>void to_json(nlohmann::json_abi_v3_11_2::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n</code></pre> <pre><code>void to_json(nlohmann::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n</code></pre> <pre><code>void to_json(NLOHMANN_JSON_NAMESPACE::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n</code></pre>"},{"location":"integration/migration_guide/#do-not-use-the-details-namespace","title":"Do not use the <code>details</code> namespace","text":"<p>The <code>details</code> namespace is not part of the public API of the library and can change in any version without announcement. Do not rely on any function or type in the <code>details</code> namespace.</p>"},{"location":"integration/package_managers/","title":"Package Managers","text":"<p>Throughout this page, we will describe how to compile the example file <code>example.cpp</code> below.</p> <pre><code>#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n</code></pre> <p>When executed, this program should create output similar to</p> <pre><code>{\n \"compiler\": {\n \"c++\": \"201103\",\n \"family\": \"gcc\",\n \"version\": \"12.3.0\"\n },\n \"copyright\": \"(C) 2013-2022 Niels Lohmann\",\n \"name\": \"JSON for Modern C++\",\n \"platform\": \"apple\",\n \"url\": \"https://github.com/nlohmann/json\",\n \"version\": {\n \"major\": 3,\n \"minor\": 11,\n \"patch\": 3,\n \"string\": \"3.11.3\"\n }\n}\n</code></pre>"},{"location":"integration/package_managers/#homebrew","title":"Homebrew","text":"<p>If you are using OS X and Homebrew, just type</p> <pre><code>brew install nlohmann-json\n</code></pre> <p>and you're set. If you want the bleeding edge rather than the latest release, use</p> <pre><code>brew install nlohmann-json --HEAD\n</code></pre> <p>instead. See nlohmann-json for more information.</p> Example <ol> <li> <p>Create the following file:</p> example.cpp<pre><code>#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n</code></pre> </li> <li> <p>Install the package</p> <pre><code>brew install nlohmann-json\n</code></pre> </li> <li> <p>Determine the include path, which defaults to <code>/usr/local/Cellar/nlohmann-json/$version/include</code>, where <code>$version</code> is the version of the library, e.g. <code>3.7.3</code>. The path of the library can be determined with</p> <pre><code>brew list nlohmann-json\n</code></pre> </li> <li> <p>Compile the code. For instance, the code can be compiled using Clang with</p> <pre><code>clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std=c++11 -o example\n</code></pre> </li> </ol> <p> The formula is updated automatically.</p>"},{"location":"integration/package_managers/#meson","title":"Meson","text":"<p>If you are using the Meson Build System, add this source tree as a meson subproject. You may also use the <code>include.zip</code> published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB, or simply use <code>meson wrap install nlohmann_json</code>. Please see the meson project for any issues regarding the packaging.</p> <p>The provided <code>meson.build</code> can also be used as an alternative to cmake for installing <code>nlohmann_json</code> system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the <code>nlohmann_json</code> pkg-config dependency. In Meson, it is preferred to use the <code>dependency()</code> object with a subproject fallback, rather than using the subproject directly.</p>"},{"location":"integration/package_managers/#bazel","title":"Bazel","text":"<p>This repository provides a Bazel <code>WORKSPACE.bazel</code> and a corresponding <code>BUILD.bazel</code> file. Therefore, this repository can be referenced by workspace rules such as <code>http_archive</code>, <code>git_repository</code>, or <code>local_repository</code> from other Bazel workspaces. To use the library you only need to depend on the target <code>@nlohmann_json//:json</code> (e.g. via <code>deps</code> attribute).</p>"},{"location":"integration/package_managers/#conan","title":"Conan","text":"<p>If you are using Conan to manage your dependencies, merely add <code>nlohmann_json/x.y.z</code> to your <code>conanfile</code>'s requires, where <code>x.y.z</code> is the release version you want to use. Please file issues here if you experience problems with the packages.</p> Example <ol> <li> <p>Create the following files:</p> Conanfile.txt<pre><code>[requires]\nnlohmann_json/3.7.3\n\n[generators]\ncmake\n</code></pre> CMakeLists.txt<pre><code>project(json_example)\ncmake_minimum_required(VERSION 2.8.12)\nadd_definitions(\"-std=c++11\")\n\ninclude(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)\nconan_basic_setup()\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example ${CONAN_LIBS})\n</code></pre> example.cpp<pre><code>#include <nlohmann/json.hpp>\n#include <iostream>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << json::meta() << std::endl;\n}\n</code></pre> </li> <li> <p>Build:</p> <pre><code>mkdir build\ncd build\nconan install ..\ncmake ..\ncmake --build .\n</code></pre> </li> </ol> <p> The package is updated automatically.</p>"},{"location":"integration/package_managers/#spack","title":"Spack","text":"<p>If you are using Spack to manage your dependencies, you can use the <code>nlohmann-json</code> package. Please see the spack project for any issues regarding the packaging.</p>"},{"location":"integration/package_managers/#hunter","title":"Hunter","text":"<p>If you are using hunter on your project for external dependencies, then you can use the nlohmann_json package. Please see the hunter project for any issues regarding the packaging.</p>"},{"location":"integration/package_managers/#buckaroo","title":"Buckaroo","text":"<p>If you are using Buckaroo, you can install this library's module with <code>buckaroo add github.com/buckaroo-pm/nlohmann-json</code>. Please file issues here. There is a demo repo here.</p>"},{"location":"integration/package_managers/#vcpkg","title":"vcpkg","text":"<p>If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with <code>vcpkg install nlohmann-json</code> and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging.</p> Example <ol> <li> <p>Create the following files:</p> CMakeLists.txt<pre><code>project(json_example)\ncmake_minimum_required(VERSION 2.8.12)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n</code></pre> example.cpp<pre><code>#include <nlohmann/json.hpp>\n#include <iostream>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << json::meta() << std::endl;\n}\n</code></pre> </li> <li> <p>Install package:</p> <pre><code>vcpkg install nlohmann-json\n</code></pre> </li> <li> <p>Build:</p> <pre><code>mkdir build\ncd build\ncmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake\ncmake --build .\n</code></pre> </li> </ol> <p>Note you need to adjust <code>/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake</code> to your system.</p>"},{"location":"integration/package_managers/#cget","title":"cget","text":"<p>If you are using cget, you can install the latest development version with <code>cget install nlohmann/json</code>. A specific version can be installed with <code>cget install nlohmann/json@v3.1.0</code>. Also, the multiple header version can be installed by adding the <code>-DJSON_MultipleHeaders=ON</code> flag (i.e., <code>cget install nlohmann/json -DJSON_MultipleHeaders=ON</code>).</p> <p> cget reads directly from the GitHub repository and is always up-to-date.</p>"},{"location":"integration/package_managers/#cocoapods","title":"CocoaPods","text":"<p>If you are using CocoaPods, you can use the library by adding pod <code>\"nlohmann_json\", '~>3.1.2'</code> to your podfile (see an example). Please file issues here.</p>"},{"location":"integration/package_managers/#nuget","title":"NuGet","text":"<p>If you are using NuGet, you can use the package nlohmann.json. Please check this extensive description on how to use the package. Please file issues here.</p>"},{"location":"integration/package_managers/#conda","title":"Conda","text":"<p>If you are using conda, you can use the package nlohmann_json from conda-forge executing <code>conda install -c conda-forge nlohmann_json</code>. Please file issues here.</p>"},{"location":"integration/package_managers/#msys2","title":"MSYS2","text":"<p>If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, just type <code>pacman -S mingw-w64-i686-nlohmann-json</code> or <code>pacman -S mingw-w64-x86_64-nlohmann-json</code> for installation. Please file issues here if you experience problems with the packages.</p> <p> The package is updated automatically.</p>"},{"location":"integration/package_managers/#macports","title":"MacPorts","text":"<p>If you are using MacPorts, execute <code>sudo port install nlohmann-json</code> to install the nlohmann-json package.</p> <p> The package is updated automatically.</p>"},{"location":"integration/package_managers/#build2","title":"build2","text":"<p>If you are using <code>build2</code>, you can use the <code>nlohmann-json</code> package from the public repository http://cppget.org or directly from the package's sources repository. In your project's <code>manifest</code> file, just add <code>depends: nlohmann-json</code> (probably with some version constraints). If you are not familiar with using dependencies in <code>build2</code>, please read this introduction. Please file issues here if you experience problems with the packages.</p> <p> The package is updated automatically.</p>"},{"location":"integration/package_managers/#wsjcpp","title":"wsjcpp","text":"<p>If you are using <code>wsjcpp</code>, you can use the command <code>wsjcpp install \"https://github.com/nlohmann/json:develop\"</code> to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch.</p> <p> wsjcpp reads directly from the GitHub repository and is always up-to-date.</p>"},{"location":"integration/package_managers/#cpmcmake","title":"CPM.cmake","text":"<p>If you are using <code>CPM.cmake</code>, you can check this <code>example</code>. After adding CPM script to your project, implement the following snippet to your CMake:</p> <pre><code>CPMAddPackage(\n NAME nlohmann_json\n GITHUB_REPOSITORY nlohmann/json\n VERSION 3.9.1)\n</code></pre>"},{"location":"integration/pkg-config/","title":"Pkg-config","text":"<p>If you are using bare Makefiles, you can use <code>pkg-config</code> to generate the include flags that point to where the library is installed:</p> <pre><code>pkg-config nlohmann_json --cflags\n</code></pre> <p>Users of the Meson build system will also be able to use a system-wide library, which will be found by <code>pkg-config</code>:</p> <pre><code>json = dependency('nlohmann_json', required: true)\n</code></pre>"}]} |