From b014c90f940a0a6fd3b73fbfc88fb6e56fcf1af1 Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Wed, 10 Apr 2024 18:23:02 +0200 Subject: [PATCH] Deployed c883fb0f1 with MkDocs version: 1.5.3 --- api/basic_json/at/index.html | 2 +- api/basic_json/update/index.html | 2 +- api/macros/json_has_static_rtti/index.html | 2 +- examples/at__keytype_const.c++17.cpp | 2 +- features/arbitrary_types/index.html | 4 +- search/search_index.json | 2 +- sitemap.xml | 448 ++++++++++----------- sitemap.xml.gz | Bin 1652 -> 1653 bytes 8 files changed, 231 insertions(+), 231 deletions(-) diff --git a/api/basic_json/at/index.html b/api/basic_json/at/index.html index d6f9e26f6..330c9a4e5 100644 --- a/api/basic_json/at/index.html +++ b/api/basic_json/at/index.html @@ -286,7 +286,7 @@ // try to read from a nonexisting key using string_view std::cout << object.at("the fast"sv) << '\n'; } - catch (const json::out_of_range) + catch (const json::out_of_range& e) { std::cout << "out of range" << '\n'; } diff --git a/api/basic_json/update/index.html b/api/basic_json/update/index.html index 94c98380d..edf9c3956 100644 --- a/api/basic_json/update/index.html +++ b/api/basic_json/update/index.html @@ -110,4 +110,4 @@ "active": true, "name": {"de": "Maus", "en": "mouse", "es": "ratón"} } -

Version history


Last update: September 17, 2022
\ No newline at end of file +

Version history


Last update: March 15, 2024
\ No newline at end of file diff --git a/api/macros/json_has_static_rtti/index.html b/api/macros/json_has_static_rtti/index.html index 08f91cc5c..38e6838a8 100644 --- a/api/macros/json_has_static_rtti/index.html +++ b/api/macros/json_has_static_rtti/index.html @@ -3,4 +3,4 @@ #include <nlohmann/json.hpp> ... -

Version history


Last update: September 24, 2023
\ No newline at end of file +

Version history


Last update: January 18, 2024
\ No newline at end of file diff --git a/examples/at__keytype_const.c++17.cpp b/examples/at__keytype_const.c++17.cpp index b08cd17b5..712d456e6 100644 --- a/examples/at__keytype_const.c++17.cpp +++ b/examples/at__keytype_const.c++17.cpp @@ -36,7 +36,7 @@ int main() // try to read from a nonexisting key using string_view std::cout << object.at("the fast"sv) << '\n'; } - catch (const json::out_of_range) + catch (const json::out_of_range& e) { std::cout << "out of range" << '\n'; } diff --git a/features/arbitrary_types/index.html b/features/arbitrary_types/index.html index 811496df8..0a0f7939c 100644 --- a/features/arbitrary_types/index.html +++ b/features/arbitrary_types/index.html @@ -153,10 +153,10 @@ } template <typename BasicJsonType> - static void to_json(const BasicJsonType& j, T& value) { + static void from_json(const BasicJsonType& j, T& value) { // this calls BasicJsonType::json_serializer<T>::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j.template template get<T>(); // oops! } }; -
Last update: June 11, 2023
\ No newline at end of file +
Last update: April 10, 2024
\ No newline at end of file diff --git a/search/search_index.json b/search/search_index.json index ae6a48fd4..aa43b7598 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"JSON for Modern C++","text":""},{"location":"api/json/","title":"nlohmann::json","text":"
using json = basic_json<>;\n

This type is the default specialization of the basic_json class which uses the standard template types.

"},{"location":"api/json/#examples","title":"Examples","text":"Example

The example below demonstrates how to use the type nlohmann::json.

#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

Output:

{\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
"},{"location":"api/json/#version-history","title":"Version history","text":"

Since version 1.0.0.

"},{"location":"api/operator_gtgt/","title":"nlohmann::operator>>(basic_json)","text":"
std::istream& operator>>(std::istream& i, basic_json& j);\n

Deserializes an input stream to a JSON value.

"},{"location":"api/operator_gtgt/#parameters","title":"Parameters","text":"i (in, out) input stream to read a serialized JSON value from j (in, out) JSON value to write the deserialized input to"},{"location":"api/operator_gtgt/#return-value","title":"Return value","text":"

the stream i

"},{"location":"api/operator_gtgt/#exceptions","title":"Exceptions","text":""},{"location":"api/operator_gtgt/#complexity","title":"Complexity","text":"

Linear in the length of the input. The parser is a predictive LL(1) parser.

"},{"location":"api/operator_gtgt/#notes","title":"Notes","text":"

A UTF-8 byte order mark is silently ignored.

Deprecation

This function replaces function std::istream& operator<<(basic_json& j, std::istream& i) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i; with i >> j;.

"},{"location":"api/operator_gtgt/#examples","title":"Examples","text":"Example

The example below shows how a JSON value is constructed by reading a serialization from a stream.

#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

Output:

{\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
"},{"location":"api/operator_gtgt/#see-also","title":"See also","text":""},{"location":"api/operator_gtgt/#version-history","title":"Version history","text":""},{"location":"api/operator_literal_json/","title":"nlohmann::operator\"\"_json","text":"
json operator \"\"_json(const char* s, std::size_t n);\n

This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred.

It is recommended to bring the operator into scope using any of the following lines:

using nlohmann::literals::operator \"\"_json;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n

This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.

"},{"location":"api/operator_literal_json/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON object n (in) length of string s"},{"location":"api/operator_literal_json/#return-value","title":"Return value","text":"

json value parsed from s

"},{"location":"api/operator_literal_json/#exceptions","title":"Exceptions","text":"

The function can throw anything that parse(s, s+n) would throw.

"},{"location":"api/operator_literal_json/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/operator_literal_json/#examples","title":"Examples","text":"Example

The following code shows how to create JSON values from string literals.

#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

Output:

{\n  \"answer\": 42,\n  \"hello\": \"world\"\n}\n
"},{"location":"api/operator_literal_json/#version-history","title":"Version history","text":""},{"location":"api/operator_literal_json_pointer/","title":"nlohmann::operator\"\"_json_pointer","text":"
json_pointer operator \"\"_json_pointer(const char* s, std::size_t n);\n

This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred.

It is recommended to bring the operator into scope using any of the following lines:

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
This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.

"},{"location":"api/operator_literal_json_pointer/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON Pointer n (in) length of string s"},{"location":"api/operator_literal_json_pointer/#return-value","title":"Return value","text":"

json_pointer value parsed from s

"},{"location":"api/operator_literal_json_pointer/#exceptions","title":"Exceptions","text":"

The function can throw anything that json_pointer::json_pointer would throw.

"},{"location":"api/operator_literal_json_pointer/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/operator_literal_json_pointer/#examples","title":"Examples","text":"Example

The following code shows how to create JSON Pointers from string literals.

#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

Output:

\"world\"\n
"},{"location":"api/operator_literal_json_pointer/#see-also","title":"See also","text":""},{"location":"api/operator_literal_json_pointer/#version-history","title":"Version history","text":""},{"location":"api/operator_ltlt/","title":"nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)","text":"
std::ostream& operator<<(std::ostream& o, const basic_json& j);      // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr);  // (2)\n
  1. Serialize the given JSON value j to the output stream o. The JSON value will be serialized using the dump member function.
    • The indentation of the output can be controlled with the member variable width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).
    • The indentation character can be controlled with the member variable fill of the output stream o. For instance, the manipulator std::setfill('\\\\t') sets indentation to use a tab character rather than the default space character.
  2. Write a string representation of the given JSON pointer ptr to the output stream o. The string representation is obtained using the to_string member function.
"},{"location":"api/operator_ltlt/#parameters","title":"Parameters","text":"o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write"},{"location":"api/operator_ltlt/#return-value","title":"Return value","text":"

the stream o

"},{"location":"api/operator_ltlt/#exceptions","title":"Exceptions","text":"
  1. Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike the dump member functions, no error_handler can be set.
  2. None.
"},{"location":"api/operator_ltlt/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/operator_ltlt/#notes","title":"Notes","text":"

Deprecation

Function std::ostream& operator<<(std::ostream& o, const basic_json& j) replaces function std::ostream& operator>>(const basic_json& j, std::ostream& o) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o; with o << j;.

"},{"location":"api/operator_ltlt/#examples","title":"Examples","text":"Example: (1) serialize JSON value to stream

The example below shows the serialization with different parameters to width to adjust the indentation level.

#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

Output:

{\"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
Example: (2) write JSON pointer to stream

The example below shows how to write a JSON pointer to a stream.

#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

Output:

/foo/bar/baz\n
"},{"location":"api/operator_ltlt/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added support for indentation character and deprecated std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.
  2. Added in version 3.11.0.
"},{"location":"api/ordered_json/","title":"nlohmann::ordered_json","text":"
using ordered_json = basic_json<ordered_map>;\n

This type preserves the insertion order of object keys.

"},{"location":"api/ordered_json/#examples","title":"Examples","text":"Example

The example below demonstrates how ordered_json preserves the insertion order of object keys.

#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

Output:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n
"},{"location":"api/ordered_json/#see-also","title":"See also","text":""},{"location":"api/ordered_json/#version-history","title":"Version history","text":"

Since version 3.9.0.

"},{"location":"api/ordered_map/","title":"nlohmann::ordered_map","text":"
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

A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json (nlohmann::basic_json<ordered_map>).

"},{"location":"api/ordered_map/#template-parameters","title":"Template parameters","text":"Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std::map) Allocator allocator type"},{"location":"api/ordered_map/#member-types","title":"Member types","text":""},{"location":"api/ordered_map/#member-functions","title":"Member functions","text":""},{"location":"api/ordered_map/#examples","title":"Examples","text":"Example

The example shows the different behavior of std::map and nlohmann::ordered_map.

#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

Output:

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
"},{"location":"api/ordered_map/#see-also","title":"See also","text":""},{"location":"api/ordered_map/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/","title":"nlohmann::adl_serializer","text":"
template<typename, typename>\nstruct adl_serializer;\n

Serializer that uses ADL (Argument-Dependent Lookup) to choose to_json/from_json functions from the types' namespaces.

It is implemented similar to

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
"},{"location":"api/adl_serializer/#member-functions","title":"Member functions","text":""},{"location":"api/adl_serializer/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/from_json/","title":"nlohmann::adl_serializer::from_json","text":"
// (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

This function is usually called by the get() function of the basic_json class (either explicitly or via the conversion operators).

  1. This function is chosen for default-constructible value types.
  2. This function is chosen for value types which are not default-constructible.
"},{"location":"api/adl_serializer/from_json/#parameters","title":"Parameters","text":"j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"

Copy of the JSON value, converted to ValueType

"},{"location":"api/adl_serializer/from_json/#examples","title":"Examples","text":"Example: (1) Default-constructible type

The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when template get<ns::person>() is called.

#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

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
Example: (2) Non-default-constructible type

The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.

#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

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
"},{"location":"api/adl_serializer/from_json/#see-also","title":"See also","text":""},{"location":"api/adl_serializer/from_json/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/to_json/","title":"nlohmann::adl_serializer::to_json","text":"
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

This function is usually called by the constructors of the basic_json class.

"},{"location":"api/adl_serializer/to_json/#parameters","title":"Parameters","text":"j (out) JSON value to write to val (in) value to read from"},{"location":"api/adl_serializer/to_json/#examples","title":"Examples","text":"Example

The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called.

#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

Output:

{\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n
"},{"location":"api/adl_serializer/to_json/#see-also","title":"See also","text":""},{"location":"api/adl_serializer/to_json/#version-history","title":"Version history","text":""},{"location":"api/basic_json/","title":"nlohmann::basic_json","text":"

Defined in header <nlohmann/json.hpp>

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
"},{"location":"api/basic_json/#template-parameters","title":"Template parameters","text":"Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t"},{"location":"api/basic_json/#specializations","title":"Specializations","text":""},{"location":"api/basic_json/#iterator-invalidation","title":"Iterator invalidation","text":"

Todo

"},{"location":"api/basic_json/#requirements","title":"Requirements","text":"

The class satisfies the following concept requirements:

"},{"location":"api/basic_json/#basic","title":"Basic","text":""},{"location":"api/basic_json/#layout","title":"Layout","text":""},{"location":"api/basic_json/#library-wide","title":"Library-wide","text":""},{"location":"api/basic_json/#container","title":"Container","text":""},{"location":"api/basic_json/#member-types","title":"Member types","text":""},{"location":"api/basic_json/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/#container-types","title":"Container types","text":"Type Definition value_type basic_json reference value_type& const_reference const value_type& difference_type std::ptrdiff_t size_type std::size_t allocator_type AllocatorType<basic_json> pointer std::allocator_traits<allocator_type>::pointer const_pointer std::allocator_traits<allocator_type>::const_pointer iterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iterator const_reverse_iterator reverse iterator, derived from const_iterator iteration_proxy helper type for items function"},{"location":"api/basic_json/#json-value-data-types","title":"JSON value data types","text":""},{"location":"api/basic_json/#parser-callback","title":"Parser callback","text":""},{"location":"api/basic_json/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/#object-inspection","title":"Object inspection","text":"

Functions to inspect the type of a JSON value.

"},{"location":"api/basic_json/#value-access","title":"Value access","text":"

Direct access to the stored value of a JSON value.

"},{"location":"api/basic_json/#element-access","title":"Element access","text":"

Access to the JSON value

"},{"location":"api/basic_json/#lookup","title":"Lookup","text":""},{"location":"api/basic_json/#iterators","title":"Iterators","text":""},{"location":"api/basic_json/#capacity","title":"Capacity","text":""},{"location":"api/basic_json/#modifiers","title":"Modifiers","text":""},{"location":"api/basic_json/#lexicographical-comparison-operators","title":"Lexicographical comparison operators","text":""},{"location":"api/basic_json/#serialization-dumping","title":"Serialization / Dumping","text":""},{"location":"api/basic_json/#deserialization-parsing","title":"Deserialization / Parsing","text":""},{"location":"api/basic_json/#json-pointer-functions","title":"JSON Pointer functions","text":""},{"location":"api/basic_json/#json-patch-functions","title":"JSON Patch functions","text":""},{"location":"api/basic_json/#json-merge-patch-functions","title":"JSON Merge Patch functions","text":""},{"location":"api/basic_json/#static-functions","title":"Static functions","text":""},{"location":"api/basic_json/#binary-formats","title":"Binary formats","text":""},{"location":"api/basic_json/#non-member-functions","title":"Non-member functions","text":""},{"location":"api/basic_json/#literals","title":"Literals","text":""},{"location":"api/basic_json/#helper-classes","title":"Helper classes","text":""},{"location":"api/basic_json/#examples","title":"Examples","text":"Example

The example shows how the library is used.

#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

Output:

{\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
"},{"location":"api/basic_json/#see-also","title":"See also","text":""},{"location":"api/basic_json/#version-history","title":"Version history","text":""},{"location":"api/basic_json/accept/","title":"nlohmann::basic_json::accept","text":"
// (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

Checks whether the input is valid JSON.

  1. Reads from a compatible input.
  2. Reads from a pair of character iterators

    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.

Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.

"},{"location":"api/basic_json/accept/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType

a compatible iterator type, for instance.

"},{"location":"api/basic_json/accept/#parameters","title":"Parameters","text":"i (in) Input to parse from. ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"

Whether the input is valid JSON.

"},{"location":"api/basic_json/accept/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/accept/#complexity","title":"Complexity","text":"

Linear in the length of the input. The parser is a predictive LL(1) parser.

"},{"location":"api/basic_json/accept/#notes","title":"Notes","text":"

(1) A UTF-8 byte order mark is silently ignored.

Runtime assertion

The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion.

"},{"location":"api/basic_json/accept/#examples","title":"Examples","text":"Example

The example below demonstrates the accept() function reading from a string.

#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

Output:

true false\n
"},{"location":"api/basic_json/accept/#see-also","title":"See also","text":""},{"location":"api/basic_json/accept/#version-history","title":"Version history","text":"

Deprecation

Overload (2) replaces calls to accept 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 accept({ptr, ptr+len}, ...); with accept(ptr, ptr+len, ...);.

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/array/","title":"nlohmann::basic_json::array","text":"
static basic_json array(initializer_list_t init = {});\n

Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.

"},{"location":"api/basic_json/array/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an array from (optional)"},{"location":"api/basic_json/array/#return-value","title":"Return value","text":"

JSON array value

"},{"location":"api/basic_json/array/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/array/#complexity","title":"Complexity","text":"

Linear in the size of init.

"},{"location":"api/basic_json/array/#notes","title":"Notes","text":"

This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (basic_json(initializer_list_t, bool, value_t)). These cases are:

  1. 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
  2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
"},{"location":"api/basic_json/array/#examples","title":"Examples","text":"Example

The following code shows an example for the array function.

#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

Output:

[]\n[]\n[1,2,3,4]\n[[\"one\",1],[\"two\",2]]\n
"},{"location":"api/basic_json/array/#see-also","title":"See also","text":""},{"location":"api/basic_json/array/#version-history","title":"Version history","text":""},{"location":"api/basic_json/array_t/","title":"nlohmann::basic_json::array_t","text":"
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n

The type used to store JSON arrays.

RFC 8259 describes JSON arrays as follows:

An array is an ordered sequence of zero or more values.

To store objects in C++, a type is defined by the template parameters explained below.

"},{"location":"api/basic_json/array_t/#template-parameters","title":"Template parameters","text":"ArrayType container type to store arrays (e.g., std::vector or std::list) AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/array_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/array_t/#default-type","title":"Default type","text":"

With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:

std::vector<\n  basic_json, // value_type\n  std::allocator<basic_json> // allocator_type\n>\n
"},{"location":"api/basic_json/array_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON array.

"},{"location":"api/basic_json/array_t/#storage","title":"Storage","text":"

Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.

"},{"location":"api/basic_json/array_t/#examples","title":"Examples","text":"Example

The following code shows that array_t is by default, a typedef to std::vector<nlohmann::json>.

#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

Output:

true\n
"},{"location":"api/basic_json/array_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/at/","title":"nlohmann::basic_json::at","text":"
// (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
  1. Returns a reference to the array element at specified location idx, with bounds checking.
  2. Returns a reference to the object element with specified key key, with bounds checking.
  3. See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
  4. Returns a reference to the element at specified JSON pointer ptr, with bounds checking.
"},{"location":"api/basic_json/at/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/at/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the elements to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/at/#return-value","title":"Return value","text":"
  1. reference to the element at index idx
  2. reference to the element at key key
  3. reference to the element at key key
  4. reference to the element pointed to by ptr
"},{"location":"api/basic_json/at/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/at/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.
    • Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.
  2. The function can throw the following exceptions:
    • Throws type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.
    • Throws out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.
  3. See 2.
  4. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.
    • Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.
    • Throws out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.
    • Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.
    • Throws out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.
    • Throws out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.
"},{"location":"api/basic_json/at/#complexity","title":"Complexity","text":"
  1. Constant.
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
  4. Logarithmic in the size of the container.
"},{"location":"api/basic_json/at/#examples","title":"Examples","text":"Example: (1) access specified array element with bounds checking

The example below shows how array elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (1) access specified array element with bounds checking

The example below shows how array elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (2) access specified object element with bounds checking

The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (2) access specified object element with bounds checking

The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"il brutto\"\n[json.exception.type_error.304] cannot use at() with string\nout of range\n
Example: (3) access specified object element using string_view with bounds checking

The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (3) access specified object element using string_view with bounds checking

The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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)\n    {\n        std::cout << \"out of range\" << '\\n';\n    }\n}\n

Output:

\"il brutto\"\n[json.exception.type_error.304] cannot use at() with string\nout of range\n
Example: (4) access specified element via JSON Pointer

The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

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
Example: (4) access specified element via JSON Pointer

The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

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
"},{"location":"api/basic_json/at/#see-also","title":"See also","text":""},{"location":"api/basic_json/at/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0.
  3. Added in version 3.11.0.
  4. Added in version 2.0.0.
"},{"location":"api/basic_json/back/","title":"nlohmann::basic_json::back","text":"
reference back();\n\nconst_reference back() const;\n

Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to

auto tmp = c.end();\n--tmp;\nreturn *tmp;\n
"},{"location":"api/basic_json/back/#return-value","title":"Return value","text":"

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.

"},{"location":"api/basic_json/back/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/back/#exceptions","title":"Exceptions","text":"

If the JSON value is null, exception invalid_iterator.214 is thrown.

"},{"location":"api/basic_json/back/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/back/#notes","title":"Notes","text":"

Precondition

The array or object must not be empty. Calling back on an empty array or object yields undefined behavior.

"},{"location":"api/basic_json/back/#examples","title":"Examples","text":"Example

The following code shows an example for back().

#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

Output:

true\n17\n23.42\n2\n16\n\"Hello, world\"\n[json.exception.invalid_iterator.214] cannot get value\n
"},{"location":"api/basic_json/back/#see-also","title":"See also","text":""},{"location":"api/basic_json/back/#version-history","title":"Version history","text":""},{"location":"api/basic_json/basic_json/","title":"nlohmann::basic_json::basic_json","text":"
// (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
  1. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:

    Value type initial value null null boolean false string \"\" number 0 object {} array [] binary empty array

    The postcondition of this constructor can be restored by calling clear().

  2. Create a null JSON value. It either takes a null pointer as parameter (explicitly creating null) or no parameter (implicitly creating null). The passed null pointer itself is not read -- it is only used to choose the right constructor.

  3. This is a \"catch all\" constructor for all compatible JSON types; that is, types for which a to_json() method exists. The constructor forwards the parameter val to that method (to json_serializer<U>::to_json method with U = uncvref_t<CompatibleType>, to be exact).

    Template type CompatibleType includes, but is not limited to, the following types:

    • arrays: array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.
    • objects: object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.
    • strings: string_t, string literals, and all compatible string containers can be used.
    • numbers: number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.
    • boolean: boolean_t / bool can be used.
    • binary: binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* 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.

    See the examples below.

  4. This is a constructor for existing basic_json types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones.

    The constructor tries to convert the internal m_value of the parameter.

  5. Creates a JSON value of type array or object from the passed initializer list init. In case type_deduction is true (default), the type of the JSON value to be created is deducted from the initializer list init according to the following rules:

    1. If the list is empty, an empty JSON object value {} is created.
    2. 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.
    3. In all other cases, an array is created.

    The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:

    1. The empty initializer list is written as {} which is exactly an empty JSON object.
    2. 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.
    3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe.

    With the rules described above, the following JSON values cannot be expressed by an initializer list:

    • the empty array ([]): use array(initializer_list_t) with an empty initializer list in this case
    • arrays whose elements satisfy rule 2: use array(initializer_list_t) with the same initializer list in this case

    Function array() and object() force array and object creation from initializer lists, respectively.

  6. Constructs a JSON array value by creating cnt copies of a passed value. In case cnt is 0, an empty array is created.

  7. Constructs the JSON value with the contents of the range [first, last). The semantics depends on the different types a JSON value can have:

    • In case of a null type, invalid_iterator.206 is thrown.
    • In case of other primitive types (number, boolean, or string), first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.
    • In case of structured types (array, object), the constructor behaves as similar versions for std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.
  8. Creates a copy of a given JSON value.

  9. Move constructor. Constructs a JSON value with the contents of the given value other using move semantics. It \"steals\" the resources from other and leaves it as JSON null value.

"},{"location":"api/basic_json/basic_json/#template-parameters","title":"Template parameters","text":"CompatibleType

a type such that:

BasicJsonType:

a type such that:

U: uncvref_t<CompatibleType>"},{"location":"api/basic_json/basic_json/#parameters","title":"Parameters","text":"v (in) the type of the value to create val (in) the value to be forwarded to the respective constructor init (in) initializer list with JSON values type_deduction (in) internal parameter; when set to true, the type of the JSON value is deducted from the initializer list init; when set to false, the type provided via manual_type is forced. This mode is used by the functions array(initializer_list_t) and object(initializer_list_t). manual_type (in) internal parameter; when type_deduction is set to false, the created JSON value will use the provided type (only value_t::array and value_t::object are valid); when type_deduction is set to true, this parameter has no effect cnt (in) the number of JSON copies of val to create first (in) begin of the range to copy from (included) last (in) end of the range to copy from (excluded) other (in) the JSON value to copy/move"},{"location":"api/basic_json/basic_json/#exception-safety","title":"Exception safety","text":"
  1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  2. No-throw guarantee: this constructor never throws exceptions.
  3. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
  4. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
  5. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  6. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  7. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  8. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  9. No-throw guarantee: this constructor never throws exceptions.
"},{"location":"api/basic_json/basic_json/#exceptions","title":"Exceptions","text":"
  1. (none)
  2. The function does not throw exceptions.
  3. (none)
  4. (none)
  5. The function can throw the following exceptions:
    • Throws type_error.301 if type_deduction is false, manual_type is value_t::object, but init 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 type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.
  6. (none)
  7. The function can throw the following exceptions:
    • Throws invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.
    • Throws invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.
    • Throws invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.
  8. (none)
  9. The function does not throw exceptions.
"},{"location":"api/basic_json/basic_json/#complexity","title":"Complexity","text":"
  1. Constant.
  2. Constant.
  3. Usually linear in the size of the passed val, also depending on the implementation of the called to_json() method.
  4. Usually linear in the size of the passed val, also depending on the implementation of the called to_json() method.
  5. Linear in the size of the initializer list init.
  6. Linear in cnt.
  7. Linear in distance between first and last.
  8. Linear in the size of other.
  9. Constant.
"},{"location":"api/basic_json/basic_json/#notes","title":"Notes","text":""},{"location":"api/basic_json/basic_json/#examples","title":"Examples","text":"Example: (1) create an empty value with a given type

The following code shows the constructor for different value_t values.

#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

Output:

null\nfalse\n0\n0.0\n{}\n[]\n\"\"\n
Example: (2) create a null object

The following code shows the constructor with and without a null pointer parameter.

#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

Output:

null\nnull\n
Example: (3) create a JSON value from compatible types

The following code shows the constructor with several compatible types.

#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

Output:

{\"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

Note the output is platform-dependent.

Example: (5) create a container (array or object) from an initializer list

The example below shows how JSON values are created from initializer lists.

#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

Output:

{}\n{\"one\":1,\"two\":2}\n[1,2,3,4]\n{\"one\":[1],\"two\":[1,2]}\n[[[1],\"one\"],[[1,2],\"two\"]]\n
Example: (6) construct an array with count copies of given value

The following code shows examples for creating arrays with several copies of a given value.

#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

Output:

[]\n[\"Hello\"]\n[\"Hello\",\"Hello\",\"Hello\",\"Hello\",\"Hello\"]\n
Example: (7) construct a JSON container given an iterator range

The example below shows several ways to create JSON values by specifying a subrange with iterators.

#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

Output:

[\"bravo\",\"charly\"]\n42\n{\"one\":\"eins\"}\n[json.exception.invalid_iterator.204] iterators out of range\n
Example: (8) copy constructor

The following code shows an example for the copy constructor.

#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

Output:

[\"one\",\"two\",3,4.5,false] = [\"one\",\"two\",3,4.5,false]\ntrue\n
Example: (9) move constructor

The code below shows the move constructor explicitly called via std::move.

#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

Output:

null\n23\n
"},{"location":"api/basic_json/basic_json/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.1.0.
  4. Since version 3.2.0.
  5. Since version 1.0.0.
  6. Since version 1.0.0.
  7. Since version 1.0.0.
  8. Since version 1.0.0.
  9. Since version 1.0.0.
"},{"location":"api/basic_json/begin/","title":"nlohmann::basic_json::begin","text":"
iterator begin() noexcept;\nconst_iterator begin() const noexcept;\n

Returns an iterator to the first element.

"},{"location":"api/basic_json/begin/#return-value","title":"Return value","text":"

iterator to the first element

"},{"location":"api/basic_json/begin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/begin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/begin/#examples","title":"Examples","text":"Example

The following code shows an example for begin().

#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

Output:

1\n
"},{"location":"api/basic_json/begin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/binary/","title":"nlohmann::basic_json::binary","text":"
// (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
  1. Creates a JSON binary array value from a given binary container.
  2. Creates a JSON binary array value from a given binary container with subtype.

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.

"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"

JSON binary array value

"},{"location":"api/basic_json/binary/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/binary/#complexity","title":"Complexity","text":"

Linear in the size of init; constant for typename binary_t::container_type&& init versions.

"},{"location":"api/basic_json/binary/#notes","title":"Notes","text":"

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 std::vector. 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.

"},{"location":"api/basic_json/binary/#examples","title":"Examples","text":"Example

The following code shows how to create a binary value.

#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

Output:

type: binary, subtype: 42\n
"},{"location":"api/basic_json/binary/#version-history","title":"Version history","text":""},{"location":"api/basic_json/binary_t/","title":"nlohmann::basic_json::binary_t","text":"
using binary_t = byte_container_with_subtype<BinaryType>;\n

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.

Additionally, as an implementation detail, the subtype of the binary data is carried around as a std::uint64_t, 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 BinaryType via the helper type byte_container_with_subtype.

CBOR's RFC 7049 describes this type as:

Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).

MessagePack's documentation on the bin type family describes this type as:

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.

BSON's specifications describe several binary types; however, this type is intended to represent the generic binary type which has the description:

Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.

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.

The default representation of this binary format is a std::vector<std::uint8_t>, which is a very common way to represent a byte array in modern C++.

"},{"location":"api/basic_json/binary_t/#template-parameters","title":"Template parameters","text":"BinaryType 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":"

The default values for BinaryType is std::vector<std::uint8_t>.

"},{"location":"api/basic_json/binary_t/#storage","title":"Storage","text":"

Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t* must be dereferenced.

"},{"location":"api/basic_json/binary_t/#notes-on-subtypes","title":"Notes on subtypes","text":""},{"location":"api/basic_json/binary_t/#examples","title":"Examples","text":"Example

The following code shows that binary_t is by default, a typedef to nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>.

#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

Output:

true\n
"},{"location":"api/basic_json/binary_t/#see-also","title":"See also","text":""},{"location":"api/basic_json/binary_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/boolean_t/","title":"nlohmann::basic_json::boolean_t","text":"
using boolean_t = BooleanType;\n

The type used to store JSON booleans.

RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.

To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.

"},{"location":"api/basic_json/boolean_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/boolean_t/#default-type","title":"Default type","text":"

With the default values for BooleanType (bool), the default value for boolean_t is bool.

"},{"location":"api/basic_json/boolean_t/#storage","title":"Storage","text":"

Boolean values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/boolean_t/#examples","title":"Examples","text":"Example

The following code shows that boolean_t is by default, a typedef to bool.

#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

Output:

true\n
"},{"location":"api/basic_json/boolean_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cbegin/","title":"nlohmann::basic_json::cbegin","text":"
const_iterator cbegin() const noexcept;\n

Returns an iterator to the first element.

"},{"location":"api/basic_json/cbegin/#return-value","title":"Return value","text":"

iterator to the first element

"},{"location":"api/basic_json/cbegin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/cbegin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/cbegin/#examples","title":"Examples","text":"Example

The following code shows an example for cbegin().

#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

Output:

1\n
"},{"location":"api/basic_json/cbegin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cbor_tag_handler_t/","title":"nlohmann::basic_json::cbor_tag_handler_t","text":"
enum class cbor_tag_handler_t\n{\n    error,\n    ignore,\n    store\n};\n

This enumeration is used in the from_cbor function to choose how to treat tags:

error throw a parse_error 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

The example below shows how the different values of the cbor_tag_handler_t influence the behavior of from_cbor when reading a tagged byte string.

#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

Output:

[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
"},{"location":"api/basic_json/cbor_tag_handler_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cend/","title":"nlohmann::basic_json::cend","text":"
const_iterator cend() const noexcept;\n

Returns an iterator to one past the last element.

"},{"location":"api/basic_json/cend/#return-value","title":"Return value","text":"

iterator one past the last element

"},{"location":"api/basic_json/cend/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/cend/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/cend/#examples","title":"Examples","text":"Example

The following code shows an example for cend().

#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

Output:

5\n
"},{"location":"api/basic_json/cend/#version-history","title":"Version history","text":""},{"location":"api/basic_json/clear/","title":"nlohmann::basic_json::clear","text":"
void clear() noexcept;\n

Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type():

Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array []

Has the same effect as calling

*this = basic_json(type());\n
"},{"location":"api/basic_json/clear/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/clear/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value.

"},{"location":"api/basic_json/clear/#notes","title":"Notes","text":"

All iterators, pointers and references related to this container are invalidated.

"},{"location":"api/basic_json/clear/#examples","title":"Examples","text":"Example

The example below shows the effect of clear() to different JSON types.

#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

Output:

null\nfalse\n0\n0.0\n{}\n[]\n\"\"\n
"},{"location":"api/basic_json/clear/#version-history","title":"Version history","text":""},{"location":"api/basic_json/contains/","title":"nlohmann::basic_json::contains","text":"
// (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
  1. Check whether an element exists in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, false is returned.
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
  3. Check whether the given JSON pointer ptr can be resolved in the current JSON value.
"},{"location":"api/basic_json/contains/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/contains/#parameters","title":"Parameters","text":"key (in) key value to check its existence. ptr (in) JSON pointer to check its existence."},{"location":"api/basic_json/contains/#return-value","title":"Return value","text":"
  1. true if an element with specified key exists. If no such element with such key is found or the JSON value is not an object, false is returned.
  2. See 1.
  3. true if the JSON pointer can be resolved to a stored value, false otherwise.
"},{"location":"api/basic_json/contains/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/contains/#exceptions","title":"Exceptions","text":"
  1. The function does not throw exceptions.
  2. The function does not throw exceptions.
  3. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index begins with 0.
    • Throws parse_error.109 if an array index was not a number.
"},{"location":"api/basic_json/contains/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

"},{"location":"api/basic_json/contains/#notes","title":"Notes","text":"

Postconditions

If j.contains(x) returns true for a key or JSON pointer x, then it is safe to call j[x].

"},{"location":"api/basic_json/contains/#examples","title":"Examples","text":"Example: (1) check with key

The example shows how contains() is used.

#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

Output:

j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n
Example: (2) check with key using string_view

The example shows how contains() is used.

#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

Output:

j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n
Example: (3) check with JSON pointer

The example shows how contains() is used.

#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

Output:

true\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/contains/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0.
  3. Added in version 3.7.0.
"},{"location":"api/basic_json/count/","title":"nlohmann::basic_json::count","text":"
// (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
  1. Returns the number of elements with key key. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/count/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/count/#parameters","title":"Parameters","text":"key (in) key value of the element to count."},{"location":"api/basic_json/count/#return-value","title":"Return value","text":"

Number of elements with key key. If the JSON value is not an object, the return value will be 0.

"},{"location":"api/basic_json/count/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/count/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

"},{"location":"api/basic_json/count/#notes","title":"Notes","text":"

This method always returns 0 when executed on a JSON type that is not an object.

"},{"location":"api/basic_json/count/#examples","title":"Examples","text":"Example: (1) count number of elements

The example shows how count() is used.

#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

Output:

number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n
Example: (2) count number of elements using string_view

The example shows how count() is used.

#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

Output:

number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n
"},{"location":"api/basic_json/count/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0.
"},{"location":"api/basic_json/crbegin/","title":"nlohmann::basic_json::crbegin","text":"
const_reverse_iterator crbegin() const noexcept;\n

Returns an iterator to the reverse-beginning; that is, the last element.

"},{"location":"api/basic_json/crbegin/#return-value","title":"Return value","text":"

reverse iterator to the first element

"},{"location":"api/basic_json/crbegin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/crbegin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/crbegin/#examples","title":"Examples","text":"Example

The following code shows an example for crbegin().

#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

Output:

5\n
"},{"location":"api/basic_json/crbegin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/crend/","title":"nlohmann::basic_json::crend","text":"
const_reverse_iterator crend() const noexcept;\n

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.

"},{"location":"api/basic_json/crend/#return-value","title":"Return value","text":"

reverse iterator to the element following the last element

"},{"location":"api/basic_json/crend/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/crend/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/crend/#examples","title":"Examples","text":"Example

The following code shows an example for eend().

#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

Output:

1\n
"},{"location":"api/basic_json/crend/#version-history","title":"Version history","text":""},{"location":"api/basic_json/default_object_comparator_t/","title":"nlohmann::basic_json::default_object_comparator_t","text":"
using default_object_comparator_t = std::less<StringType>;  // until C++14\n\nusing default_object_comparator_t = std::less<>;            // since C++14\n

The default comparator used by object_t.

Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object.

The actual comparator used depends on object_t and can be obtained via object_comparator_t.

"},{"location":"api/basic_json/default_object_comparator_t/#examples","title":"Examples","text":"Example

The example below demonstrates the default comparator.

#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

Output:

one < two : true\nthree < four : false\n
"},{"location":"api/basic_json/default_object_comparator_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/diff/","title":"nlohmann::basic_json::diff","text":"
static basic_json diff(const basic_json& source,\n                       const basic_json& target);\n

Creates a JSON Patch so that value source can be changed into the value target by calling patch function.

For two JSON values source and target, the following code yields always true:

source.patch(diff(source, target)) == target;\n

"},{"location":"api/basic_json/diff/#parameters","title":"Parameters","text":"source (in) JSON value to compare from target (in) JSON value to compare against"},{"location":"api/basic_json/diff/#return-value","title":"Return value","text":"

a JSON patch to convert the source to target

"},{"location":"api/basic_json/diff/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/diff/#complexity","title":"Complexity","text":"

Linear in the lengths of source and target.

"},{"location":"api/basic_json/diff/#notes","title":"Notes","text":"

Currently, only remove, add, and replace operations are generated.

"},{"location":"api/basic_json/diff/#examples","title":"Examples","text":"Example

The following code shows how a JSON patch is created as a diff for two JSON values.

#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

Output:

[\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
"},{"location":"api/basic_json/diff/#see-also","title":"See also","text":""},{"location":"api/basic_json/diff/#version-history","title":"Version history","text":""},{"location":"api/basic_json/dump/","title":"nlohmann::basic_json::dump","text":"
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

Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent and ensure_ascii parameters.

"},{"location":"api/basic_json/dump/#parameters","title":"Parameters","text":"indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are three possible values (see error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (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":"

string containing the serialization of the JSON value

"},{"location":"api/basic_json/dump/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/dump/#exceptions","title":"Exceptions","text":"

Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict

"},{"location":"api/basic_json/dump/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/dump/#notes","title":"Notes","text":"

Binary values are serialized as object containing two keys:

"},{"location":"api/basic_json/dump/#examples","title":"Examples","text":"Example

The following example shows the effect of different indent, indent_char, and ensure_ascii parameters to the result of the serialization.

#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

Output:

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
"},{"location":"api/basic_json/dump/#version-history","title":"Version history","text":""},{"location":"api/basic_json/emplace/","title":"nlohmann::basic_json::emplace","text":"
template<class... Args>\nstd::pair<iterator, bool> emplace(Args&& ... args);\n

Inserts a new element into a JSON object constructed in-place with the given args 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 args.

"},{"location":"api/basic_json/emplace/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace/#return-value","title":"Return value","text":"

a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.

"},{"location":"api/basic_json/emplace/#exceptions","title":"Exceptions","text":"

Throws type_error.311 when called on a type other than JSON object or null; example: \"cannot use emplace() with number\"

"},{"location":"api/basic_json/emplace/#complexity","title":"Complexity","text":"

Logarithmic in the size of the container, O(log(size())).

"},{"location":"api/basic_json/emplace/#examples","title":"Examples","text":"Example

The example shows how emplace() can be used to add elements to a JSON object. Note how the null 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.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"one\":1,\"three\":3,\"two\":2}\n3 true\n{\"A\":\"a\",\"B\":\"b\"}\n\"b\" false\n
"},{"location":"api/basic_json/emplace/#version-history","title":"Version history","text":""},{"location":"api/basic_json/emplace_back/","title":"nlohmann::basic_json::emplace_back","text":"
template<class... Args>\nreference emplace_back(Args&& ... args);\n

Creates a JSON value from the passed parameters args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from args.

"},{"location":"api/basic_json/emplace_back/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace_back/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace_back/#return-value","title":"Return value","text":"

reference to the inserted element

"},{"location":"api/basic_json/emplace_back/#exceptions","title":"Exceptions","text":"

Throws type_error.311 when called on a type other than JSON array or null; example: \"cannot use emplace_back() with number\"

"},{"location":"api/basic_json/emplace_back/#complexity","title":"Complexity","text":"

Amortized constant.

"},{"location":"api/basic_json/emplace_back/#examples","title":"Examples","text":"Example

The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.

#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

Output:

[1,2,3,4,5]\nnull\n[1,2,3,4,5,6]\n[\"first\",[\"second\",\"second\",\"second\"]]\n
"},{"location":"api/basic_json/emplace_back/#version-history","title":"Version history","text":""},{"location":"api/basic_json/empty/","title":"nlohmann::basic_json::empty","text":"
bool empty() const noexcept;\n

Checks if a JSON value has no elements (i.e. whether its size() is 0).

"},{"location":"api/basic_json/empty/#return-value","title":"Return value","text":"

The return value depends on the different types and is defined as follows:

Value type return value null true boolean false string false number false binary false object result of function object_t::empty() array result of function array_t::empty()"},{"location":"api/basic_json/empty/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/empty/#complexity","title":"Complexity","text":"

Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity.

"},{"location":"api/basic_json/empty/#possible-implementation","title":"Possible implementation","text":"
bool empty() const noexcept\n{\n    return size() == 0;\n}\n
"},{"location":"api/basic_json/empty/#notes","title":"Notes","text":"

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 false in the case of a string.

"},{"location":"api/basic_json/empty/#examples","title":"Examples","text":"Example

The following code uses empty() to check if a JSON object contains any elements.

#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

Output:

true\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\ntrue\nfalse\n
"},{"location":"api/basic_json/empty/#version-history","title":"Version history","text":""},{"location":"api/basic_json/end/","title":"nlohmann::basic_json::end","text":"
iterator end() noexcept;\nconst_iterator end() const noexcept;\n

Returns an iterator to one past the last element.

"},{"location":"api/basic_json/end/#return-value","title":"Return value","text":"

iterator one past the last element

"},{"location":"api/basic_json/end/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/end/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/end/#examples","title":"Examples","text":"Example

The following code shows an example for end().

#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

Output:

5\n
"},{"location":"api/basic_json/end/#version-history","title":"Version history","text":""},{"location":"api/basic_json/erase/","title":"nlohmann::basic_json::erase","text":"
// (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
  1. Removes an element from a JSON value specified by iterator pos. The iterator pos must be valid and dereferenceable. Thus, the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

    If called on a primitive type other than null, the resulting JSON value will be null.

  2. Remove an element range specified by [first; last) from a JSON value. The iterator first does not need to be dereferenceable if first == last: erasing an empty range is a no-op.

    If called on a primitive type other than null, the resulting JSON value will be null.

  3. Removes an element from a JSON object by key.

  4. See 3. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.

  5. Removes an element from a JSON array by index.

"},{"location":"api/basic_json/erase/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/erase/#parameters","title":"Parameters","text":"pos (in) iterator to the element to remove first (in) iterator to the beginning of the range to remove last (in) iterator past the end of the range to remove key (in) object key of the elements to remove idx (in) array index of the element to remove"},{"location":"api/basic_json/erase/#return-value","title":"Return value","text":"
  1. Iterator following the last removed element. If the iterator pos refers to the last element, the end() iterator is returned.
  2. Iterator following the last removed element. If the iterator last refers to the last element, the end() iterator is returned.
  3. Number of elements removed. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
  4. See 3.
  5. (none)
"},{"location":"api/basic_json/erase/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/erase/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: \"iterator out of range\"
  2. The function can throw the following exceptions:
    • Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
    • Throws invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: \"iterators do not fit current value\"
    • Throws invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: \"iterators out of range\"
  3. The function can throw the following exceptions:
    • Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
  4. See 3.
  5. The function can throw the following exceptions:
    • Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
    • Throws out_of_range.401 when idx >= size(); example: \"array index 17 is out of range\"
"},{"location":"api/basic_json/erase/#complexity","title":"Complexity","text":"
  1. The complexity depends on the type:
    • objects: amortized constant
    • arrays: linear in distance between pos and the end of the container
    • strings and binary: linear in the length of the member
    • other types: constant
  2. The complexity depends on the type:
    • objects: log(size()) + std::distance(first, last)
    • arrays: linear in the distance between first and last, plus linear in the distance between last and end of the container
    • strings and binary: linear in the length of the member
    • other types: constant
  3. log(size()) + count(key)
  4. log(size()) + count(key)
  5. Linear in distance between idx and the end of the container.
"},{"location":"api/basic_json/erase/#notes","title":"Notes","text":"
  1. Invalidates iterators and references at or after the point of the erase, including the end() iterator.
  2. (none)
  3. References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
  4. See 3.
  5. (none)
"},{"location":"api/basic_json/erase/#examples","title":"Examples","text":"Example: (1) remove element given an iterator

The example shows the effect of erase() for different JSON types using an iterator.

#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

Output:

null\nnull\nnull\n{\"one\":1}\n[1,2,8,16]\nnull\n
Example: (2) remove elements given an iterator range

The example shows the effect of erase() for different JSON types using an iterator range.

#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

Output:

null\nnull\nnull\n{\"one\":1}\n[1,8,16]\nnull\n
Example: (3) remove element from a JSON object given a key

The example shows the effect of erase() for different JSON types using an object key.

#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

Output:

{\"two\":2}\n1 0\n
Example: (4) remove element from a JSON object given a key using string_view

The example shows the effect of erase() for different JSON types using an object key.

#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

Output:

{\"two\":2}\n1 0\n
Example: (5) remove element from a JSON array given an index

The example shows the effect of erase() using an array index.

#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

Output:

[0,1,3,4,5]\n
"},{"location":"api/basic_json/erase/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added support for binary types in version 3.8.0.
  2. Added in version 1.0.0. Added support for binary types in version 3.8.0.
  3. Added in version 1.0.0.
  4. Added in version 3.11.0.
  5. Added in version 1.0.0.
"},{"location":"api/basic_json/error_handler_t/","title":"nlohmann::basic_json::error_handler_t","text":"
enum class error_handler_t {\n    strict,\n    replace,\n    ignore\n};\n

This enumeration is used in the dump function to choose how to treat decoding errors while serializing a basic_json value. Three values are differentiated:

strict throw a type_error 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

The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.

#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

Output:

[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
"},{"location":"api/basic_json/error_handler_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/exception/","title":"nlohmann::basic_json::exception","text":"
class exception : public std::exception;\n

This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions, see example below.

Subclasses:

"},{"location":"api/basic_json/exception/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/exception/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/exception/#notes","title":"Notes","text":"

To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.

"},{"location":"api/basic_json/exception/#examples","title":"Examples","text":"Example

The following code shows how arbitrary library exceptions can be caught.

#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

Output:

message: [json.exception.out_of_range.403] key 'non-existing' not found\nexception id: 403\n
"},{"location":"api/basic_json/exception/#see-also","title":"See also","text":"

List of exceptions

"},{"location":"api/basic_json/exception/#version-history","title":"Version history","text":""},{"location":"api/basic_json/find/","title":"nlohmann::basic_json::find","text":"
// (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
  1. Finds an element in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, end() is returned.
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/find/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/find/#parameters","title":"Parameters","text":"key (in) key value of the element to search for."},{"location":"api/basic_json/find/#return-value","title":"Return value","text":"

Iterator to an element with a key equivalent to key. If no such element is found or the JSON value is not an object, a past-the-end iterator (see end()) is returned.

"},{"location":"api/basic_json/find/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/find/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

"},{"location":"api/basic_json/find/#notes","title":"Notes","text":"

This method always returns end() when executed on a JSON type that is not an object.

"},{"location":"api/basic_json/find/#examples","title":"Examples","text":"Example: (1) find object element by key

The example shows how find() is used.

#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

Output:

\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n
Example: (2) find object element by key using string_view

The example shows how find() is used.

#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

Output:

\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n
"},{"location":"api/basic_json/find/#see-also","title":"See also","text":""},{"location":"api/basic_json/find/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.
"},{"location":"api/basic_json/flatten/","title":"nlohmann::basic_json::flatten","text":"
basic_json flatten() const;\n

The function creates a JSON object whose keys are JSON pointers (see RFC 6901) and whose values are all primitive (see is_primitive() for more information). The original JSON value can be restored using the unflatten() function.

"},{"location":"api/basic_json/flatten/#return-value","title":"Return value","text":"

an object that maps JSON pointers to primitive values

"},{"location":"api/basic_json/flatten/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/flatten/#complexity","title":"Complexity","text":"

Linear in the size the JSON value.

"},{"location":"api/basic_json/flatten/#notes","title":"Notes","text":"

Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.

"},{"location":"api/basic_json/flatten/#examples","title":"Examples","text":"Example

The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.

#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

Output:

{\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
"},{"location":"api/basic_json/flatten/#see-also","title":"See also","text":""},{"location":"api/basic_json/flatten/#version-history","title":"Version history","text":""},{"location":"api/basic_json/from_bjdata/","title":"nlohmann::basic_json::from_bjdata","text":"
// (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

Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_bjdata/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bjdata/#parameters","title":"Parameters","text":"i (in) an input in BJData format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bjdata/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_bjdata/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_bjdata/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_bjdata/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_bjdata/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in BJData format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_bjdata/#version-history","title":"Version history","text":""},{"location":"api/basic_json/from_bson/","title":"nlohmann::basic_json::from_bson","text":"
// (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

Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_bson/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bson/#parameters","title":"Parameters","text":"i (in) an input in BSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bson/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_bson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_bson/#exceptions","title":"Exceptions","text":"

Throws parse_error.114 if an unsupported BSON record type is encountered.

"},{"location":"api/basic_json/from_bson/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_bson/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in BSON format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_bson/#see-also","title":"See also","text":""},{"location":"api/basic_json/from_bson/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/from_cbor/","title":"nlohmann::basic_json::from_cbor","text":"
// (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

Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_cbor/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_cbor/#parameters","title":"Parameters","text":"i (in) an input in CBOR format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) tag_handler (in) how to treat CBOR tags (optional, error by default); see cbor_tag_handler_t for more information"},{"location":"api/basic_json/from_cbor/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_cbor/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_cbor/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_cbor/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_cbor/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in CBOR format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_cbor/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/from_msgpack/","title":"nlohmann::basic_json::from_msgpack","text":"
// (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

Deserializes a given input to a JSON value using the MessagePack serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_msgpack/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_msgpack/#parameters","title":"Parameters","text":"i (in) an input in MessagePack format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_msgpack/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_msgpack/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_msgpack/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_msgpack/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_msgpack/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in MessagePack format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_msgpack/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/from_ubjson/","title":"nlohmann::basic_json::from_ubjson","text":"
// (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

Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_ubjson/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_ubjson/#parameters","title":"Parameters","text":"i (in) an input in UBJSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_ubjson/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_ubjson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_ubjson/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_ubjson/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_ubjson/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in UBJSON format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_ubjson/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/front/","title":"nlohmann::basic_json::front","text":"
reference front();\nconst_reference front() const;\n

Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().

"},{"location":"api/basic_json/front/#return-value","title":"Return value","text":"

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.

"},{"location":"api/basic_json/front/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/front/#exceptions","title":"Exceptions","text":"

If the JSON value is null, exception invalid_iterator.214 is thrown.

"},{"location":"api/basic_json/front/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/front/#notes","title":"Notes","text":"

Precondition

The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.

"},{"location":"api/basic_json/front/#examples","title":"Examples","text":"Example

The following code shows an example for front().

#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

Output:

true\n17\n23.42\n1\n1\n\"Hello, world\"\n
"},{"location":"api/basic_json/front/#see-also","title":"See also","text":""},{"location":"api/basic_json/front/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get/","title":"nlohmann::basic_json::get","text":"
// (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
  1. Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.

    The function is equivalent to executing

    ValueType ret;\nJSONSerializer<ValueType>::from_json(*this, ret);\nreturn ret;\n

    This overload is chosen if:

    • ValueType is not basic_json,
    • json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&), and
    • json_serializer<ValueType> does not have a from_json() method of the form ValueType from_json(const basic_json&)

    If the type is not CopyConstructible and not DefaultConstructible, the value is converted by calling the json_serializer<ValueType> from_json() method.

    The function is then equivalent to executing

    return JSONSerializer<ValueTypeCV>::from_json(*this);\n

    This overload is chosen if:

    • ValueType is not basic_json and
    • json_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)

    If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.

  2. Overload for basic_json specializations. The function is equivalent to executing

    return *this;\n

  3. Explicit pointer access to the internally stored JSON value. No copies are made.

"},{"location":"api/basic_json/get/#template-parameters","title":"Template parameters","text":"ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get/#return-value","title":"Return value","text":"
  1. copy of the JSON value, converted to ValueType
  2. a copy of *this, converted into BasicJsonType
  3. pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
"},{"location":"api/basic_json/get/#exceptions","title":"Exceptions","text":"

Depends on what json_serializer<ValueType> from_json() method throws

"},{"location":"api/basic_json/get/#notes","title":"Notes","text":"

Undefined behavior

Writing data to the pointee (overload 3) of the result yields an undefined state.

"},{"location":"api/basic_json/get/#examples","title":"Examples","text":"Example

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 std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.

#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

Output:

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
Example

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 #cpp nullptr is returned if the value and the requested pointer type does not match.

#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

Output:

17 17 17 17\ntrue\n
"},{"location":"api/basic_json/get/#version-history","title":"Version history","text":"
  1. Since version 2.1.0.
  2. Since version 2.1.0. Extended to work with other specializations of basic_json in version 3.2.0.
  3. Since version 1.0.0.
"},{"location":"api/basic_json/get_allocator/","title":"nlohmann::basic_json::get_allocator","text":"
static allocator_type get_allocator();\n

Returns the allocator associated with the container.

"},{"location":"api/basic_json/get_allocator/#return-value","title":"Return value","text":"

associated allocator

"},{"location":"api/basic_json/get_allocator/#examples","title":"Examples","text":"Example

The example shows how get_allocator() is used to created json values.

#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

Output:

\"Hello, world!\"\n
"},{"location":"api/basic_json/get_allocator/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_binary/","title":"nlohmann::basic_json::get_binary","text":"
binary_t& get_binary();\n\nconst binary_t& get_binary() const;\n

Returns a reference to the stored binary value.

"},{"location":"api/basic_json/get_binary/#return-value","title":"Return value","text":"

Reference to binary value.

"},{"location":"api/basic_json/get_binary/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/get_binary/#exceptions","title":"Exceptions","text":"

Throws type_error.302 if the value is not binary

"},{"location":"api/basic_json/get_binary/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/get_binary/#examples","title":"Examples","text":"Example

The following code shows how to query a binary value.

#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

Output:

type: binary, subtype: 42\n
"},{"location":"api/basic_json/get_binary/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_ptr/","title":"nlohmann::basic_json::get_ptr","text":"
template<typename PointerType>\nPointerType get_ptr() noexcept;\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n

Implicit pointer access to the internally stored JSON value. No copies are made.

"},{"location":"api/basic_json/get_ptr/#template-parameters","title":"Template parameters","text":"PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get_ptr/#return-value","title":"Return value","text":"

pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise

"},{"location":"api/basic_json/get_ptr/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/get_ptr/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/get_ptr/#notes","title":"Notes","text":"

Undefined behavior

Writing data to the pointee of the result yields an undefined state.

"},{"location":"api/basic_json/get_ptr/#examples","title":"Examples","text":"Example

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 nullptr is returned if the value and the requested pointer type does not match.

#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

Output:

17 17 17 17\ntrue\n
"},{"location":"api/basic_json/get_ptr/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_ref/","title":"nlohmann::basic_json::get_ref","text":"
template<typename ReferenceType>\nReferenceType get_ref();\n\ntemplate<typename ReferenceType>\nconst ReferenceType get_ref() const;\n

Implicit reference access to the internally stored JSON value. No copies are made.

"},{"location":"api/basic_json/get_ref/#template-parameters","title":"Template parameters","text":"ReferenceType reference type; must be a reference to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Enforced by a static assertion."},{"location":"api/basic_json/get_ref/#return-value","title":"Return value","text":"

reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise

"},{"location":"api/basic_json/get_ref/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/get_ref/#exceptions","title":"Exceptions","text":"

Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: \"incompatible ReferenceType for get_ref, actual type is binary\".

"},{"location":"api/basic_json/get_ref/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/get_ref/#notes","title":"Notes","text":"

Undefined behavior

Writing data to the referee of the result yields an undefined state.

"},{"location":"api/basic_json/get_ref/#examples","title":"Examples","text":"Example

The example shows several calls to get_ref().

#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

Output:

17 17\n[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\n
"},{"location":"api/basic_json/get_ref/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_to/","title":"nlohmann::basic_json::get_to","text":"
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

Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer<ValueType> from_json() method.

The function is equivalent to executing

ValueType v;\nJSONSerializer<ValueType>::from_json(*this, v);\n

This overload is chosen if:

"},{"location":"api/basic_json/get_to/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"

the input parameter, allowing chaining calls

"},{"location":"api/basic_json/get_to/#exceptions","title":"Exceptions","text":"

Depends on what json_serializer<ValueType> from_json() method throws

"},{"location":"api/basic_json/get_to/#examples","title":"Examples","text":"Example

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 std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map<std::string, json>.

#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

Output:

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
"},{"location":"api/basic_json/get_to/#version-history","title":"Version history","text":""},{"location":"api/basic_json/input_format_t/","title":"nlohmann::basic_json::input_format_t","text":"
enum class input_format_t {\n    json,\n    cbor,\n    msgpack,\n    ubjson,\n    bson,\n    bjdata\n};\n

This enumeration is used in the sax_parse function to choose the input format to parse:

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

The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR.

#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

Output:

binary(val=[...])\n\nresult: true\n
"},{"location":"api/basic_json/input_format_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/insert/","title":"nlohmann::basic_json::insert","text":"
// (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
  1. Inserts element val into array before iterator pos.
  2. Inserts cnt copies of val into array before iterator pos.
  3. Inserts elements from range [first, last) into array before iterator pos.
  4. Inserts elements from initializer list ilist into array before iterator pos.
  5. Inserts elements from range [first, last) into object.
"},{"location":"api/basic_json/insert/#parameters","title":"Parameters","text":"pos (in) iterator before which the content will be inserted; may be the end() iterator val (in) value to insert cnt (in) number of copies of val to insert first (in) begin of the range of elements to insert last (in) end of the range of elements to insert ilist (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"
  1. iterator pointing to the inserted val.
  2. iterator pointing to the first element inserted, or pos if cnt==0
  3. iterator pointing to the first element inserted, or pos if first==last
  4. iterator pointing to the first element inserted, or pos if ilist is empty
  5. (none)
"},{"location":"api/basic_json/insert/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/insert/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
  2. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
  3. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
    • Throws invalid_iterator.211 if first or last are iterators into container for which insert is called; example: \"passed iterators may not belong to container\"
  4. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
  5. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than objects; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
"},{"location":"api/basic_json/insert/#complexity","title":"Complexity","text":"
  1. Constant plus linear in the distance between pos and end of the container.
  2. Linear in cnt plus linear in the distance between pos and end of the container.
  3. Linear in std::distance(first, last) plus linear in the distance between pos and end of the container.
  4. Linear in ilist.size() plus linear in the distance between pos and end of the container.
  5. Logarithmic: O(N*log(size() + N)), where N is the number of elements to insert.
"},{"location":"api/basic_json/insert/#examples","title":"Examples","text":"Example (1): insert element into array

The example shows how insert() is used.

#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

Output:

10\n[1,2,10,3,4]\n
Example (2): insert copies of element into array

The example shows how insert() is used.

#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

Output:

7\n[1,2,7,7,7,7,7,7,7,3,4]\n
Example (3): insert range of elements into array

The example shows how insert() is used.

#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

Output:

\"one\"\n[1,2,3,4,\"one\",\"two\",\"three\",\"four\"]\n
Example (4): insert elements from initializer list into array

The example shows how insert() is used.

#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

Output:

7\n[1,2,3,4,7,8,9]\n
Example (5): insert range of elements into object

The example shows how insert() is used.

#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

Output:

{\"one\":\"eins\",\"two\":\"zwei\"}\n{\"eleven\":\"elf\",\"seventeen\":\"siebzehn\"}\n{\"eleven\":\"elf\",\"one\":\"eins\",\"seventeen\":\"siebzehn\",\"two\":\"zwei\"}\n
"},{"location":"api/basic_json/insert/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0.
  3. Added in version 1.0.0.
  4. Added in version 1.0.0.
  5. Added in version 3.0.0.
"},{"location":"api/basic_json/invalid_iterator/","title":"nlohmann::basic_json::invalid_iterator","text":"
class invalid_iterator : public exception;\n

This exception is thrown if iterators passed to a library function do not match the expected semantics.

Exceptions have ids 2xx (see list of iterator errors).

"},{"location":"api/basic_json/invalid_iterator/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/invalid_iterator/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/invalid_iterator/#examples","title":"Examples","text":"Example

The following code shows how a invalid_iterator exception can be caught.

#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

Output:

message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n
"},{"location":"api/basic_json/invalid_iterator/#see-also","title":"See also","text":""},{"location":"api/basic_json/invalid_iterator/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_array/","title":"nlohmann::basic_json::is_array","text":"
constexpr bool is_array() const noexcept;\n

This function returns true if and only if the JSON value is an array.

"},{"location":"api/basic_json/is_array/#return-value","title":"Return value","text":"

true if type is an array, false otherwise.

"},{"location":"api/basic_json/is_array/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_array/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_array/#examples","title":"Examples","text":"Example

The following code exemplifies is_array() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\n
"},{"location":"api/basic_json/is_array/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_binary/","title":"nlohmann::basic_json::is_binary","text":"
constexpr bool is_binary() const noexcept;\n

This function returns true if and only if the JSON value is binary array.

"},{"location":"api/basic_json/is_binary/#return-value","title":"Return value","text":"

true if type is binary, false otherwise.

"},{"location":"api/basic_json/is_binary/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_binary/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_binary/#examples","title":"Examples","text":"Example

The following code exemplifies is_binary() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\n
"},{"location":"api/basic_json/is_binary/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_boolean/","title":"nlohmann::basic_json::is_boolean","text":"
constexpr bool is_boolean() const noexcept;\n

This function returns true if and only if the JSON value is true or false.

"},{"location":"api/basic_json/is_boolean/#return-value","title":"Return value","text":"

true if type is boolean, false otherwise.

"},{"location":"api/basic_json/is_boolean/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_boolean/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_boolean/#examples","title":"Examples","text":"Example

The following code exemplifies is_boolean() for all JSON types.

#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

Output:

false\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_boolean/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_discarded/","title":"nlohmann::basic_json::is_discarded","text":"
constexpr bool is_discarded() const noexcept;\n

This function returns true for a JSON value if either:

"},{"location":"api/basic_json/is_discarded/#return-value","title":"Return value","text":"

true if type is discarded, false otherwise.

"},{"location":"api/basic_json/is_discarded/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_discarded/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_discarded/#notes","title":"Notes","text":"

Comparisons

Discarded values are never compared equal with operator==. That is, checking whether a JSON value j is discarded will only work via:

j.is_discarded()\n

because

j == json::value_t::discarded\n

will always be false.

Removal during parsing with callback functions

When a value is discarded by a callback function (see parser_callback_t) 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 [null, discarded, false], the array [null, false] is returned. Only if the top-level value is discarded, the return value of the parse call is discarded.

This function will always be false 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.

"},{"location":"api/basic_json/is_discarded/#examples","title":"Examples","text":"Example

The following code exemplifies is_discarded() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_discarded/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_null/","title":"nlohmann::basic_json::is_null","text":"
constexpr bool is_null() const noexcept;\n

This function returns true if and only if the JSON value is null.

"},{"location":"api/basic_json/is_null/#return-value","title":"Return value","text":"

true if type is null, false otherwise.

"},{"location":"api/basic_json/is_null/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_null/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_null/#examples","title":"Examples","text":"Example

The following code exemplifies is_null() for all JSON types.

#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

Output:

true\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_null/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number/","title":"nlohmann::basic_json::is_number","text":"
constexpr bool is_number() const noexcept;\n

This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.

"},{"location":"api/basic_json/is_number/#return-value","title":"Return value","text":"

true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.

"},{"location":"api/basic_json/is_number/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number/#possible-implementation","title":"Possible implementation","text":"
constexpr bool is_number() const noexcept\n{\n    return is_number_integer() || is_number_float();\n}\n
"},{"location":"api/basic_json/is_number/#examples","title":"Examples","text":"Example

The following code exemplifies is_number() for all JSON types.

#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

Output:

false\nfalse\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number_float/","title":"nlohmann::basic_json::is_number_float","text":"
constexpr bool is_number_float() const noexcept;\n

This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.

"},{"location":"api/basic_json/is_number_float/#return-value","title":"Return value","text":"

true if type is a floating-point number, false otherwise.

"},{"location":"api/basic_json/is_number_float/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number_float/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number_float/#examples","title":"Examples","text":"Example

The following code exemplifies is_number_float() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number_float/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number_float/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number_integer/","title":"nlohmann::basic_json::is_number_integer","text":"
constexpr bool is_number_integer() const noexcept;\n

This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.

"},{"location":"api/basic_json/is_number_integer/#return-value","title":"Return value","text":"

true if type is an integer or unsigned integer number, false otherwise.

"},{"location":"api/basic_json/is_number_integer/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number_integer/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number_integer/#examples","title":"Examples","text":"Example

The following code exemplifies is_number_integer() for all JSON types.

#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

Output:

false\nfalse\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number_integer/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number_integer/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number_unsigned/","title":"nlohmann::basic_json::is_number_unsigned","text":"
constexpr bool is_number_unsigned() const noexcept;\n

This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.

"},{"location":"api/basic_json/is_number_unsigned/#return-value","title":"Return value","text":"

true if type is an unsigned integer number, false otherwise.

"},{"location":"api/basic_json/is_number_unsigned/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number_unsigned/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number_unsigned/#examples","title":"Examples","text":"Example

The following code exemplifies is_number_unsigned() for all JSON types.

#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

Output:

false\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number_unsigned/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number_unsigned/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_object/","title":"nlohmann::basic_json::is_object","text":"
constexpr bool is_object() const noexcept;\n

This function returns true if and only if the JSON value is an object.

"},{"location":"api/basic_json/is_object/#return-value","title":"Return value","text":"

true if type is an object, false otherwise.

"},{"location":"api/basic_json/is_object/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_object/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_object/#examples","title":"Examples","text":"Example

The following code exemplifies is_object() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_object/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_primitive/","title":"nlohmann::basic_json::is_primitive","text":"
constexpr bool is_primitive() const noexcept;\n

This function returns true if and only if the JSON type is primitive (string, number, boolean, null, binary).

"},{"location":"api/basic_json/is_primitive/#return-value","title":"Return value","text":"

true if type is primitive (string, number, boolean, null, or binary), false otherwise.

"},{"location":"api/basic_json/is_primitive/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_primitive/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_primitive/#possible-implementation","title":"Possible implementation","text":"
constexpr bool is_primitive() const noexcept\n{\n    return is_null() || is_string() || is_boolean() || is_number() || is_binary();\n}\n
"},{"location":"api/basic_json/is_primitive/#notes","title":"Notes","text":"

The term primitive stems from RFC 8259:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.

"},{"location":"api/basic_json/is_primitive/#examples","title":"Examples","text":"Example

The following code exemplifies is_primitive() for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\nfalse\nfalse\ntrue\ntrue\n
"},{"location":"api/basic_json/is_primitive/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_primitive/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_string/","title":"nlohmann::basic_json::is_string","text":"
constexpr bool is_string() const noexcept;\n

This function returns true if and only if the JSON value is a string.

"},{"location":"api/basic_json/is_string/#return-value","title":"Return value","text":"

true if type is a string, false otherwise.

"},{"location":"api/basic_json/is_string/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_string/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_string/#examples","title":"Examples","text":"Example

The following code exemplifies is_string() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\n
"},{"location":"api/basic_json/is_string/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_structured/","title":"nlohmann::basic_json::is_structured","text":"
constexpr bool is_structured() const noexcept;\n

This function returns true if and only if the JSON type is structured (array or object).

"},{"location":"api/basic_json/is_structured/#return-value","title":"Return value","text":"

true if type is structured (array or object), false otherwise.

"},{"location":"api/basic_json/is_structured/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_structured/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_structured/#possible-implementation","title":"Possible implementation","text":"
constexpr bool is_primitive() const noexcept\n{\n    return is_array() || is_object();\n}\n
"},{"location":"api/basic_json/is_structured/#notes","title":"Notes","text":"

The term structured stems from RFC 8259:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

Note that though strings are containers in C++, they are treated as primitive values in JSON.

"},{"location":"api/basic_json/is_structured/#examples","title":"Examples","text":"Example

The following code exemplifies is_structured() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\ntrue\ntrue\nfalse\nfalse\n
"},{"location":"api/basic_json/is_structured/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_structured/#version-history","title":"Version history","text":""},{"location":"api/basic_json/items/","title":"nlohmann::basic_json::items","text":"
iteration_proxy<iterator> items() noexcept;\niteration_proxy<const_iterator> items() const noexcept;\n

This function allows accessing iterator::key() and iterator::value() 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.

For loop without items() function:

for (auto it = j_object.begin(); it != j_object.end(); ++it)\n{\n    std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n}\n

Range-based for loop without items() function:

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

Range-based for loop with items() function:

for (auto& el : j_object.items())\n{\n    std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n

The items() function also allows using structured bindings (C++17):

for (auto& [key, val] : j_object.items())\n{\n    std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n
"},{"location":"api/basic_json/items/#return-value","title":"Return value","text":"

iteration proxy object wrapping the current value with an interface to use in range-based for loops

"},{"location":"api/basic_json/items/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/items/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/items/#notes","title":"Notes","text":"

When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string.

Lifetime issues

Using items() 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.

"},{"location":"api/basic_json/items/#examples","title":"Examples","text":"Example

The following code shows an example for items().

#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

Output:

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
"},{"location":"api/basic_json/items/#version-history","title":"Version history","text":"

Deprecation

This function replaces the static function iterator_wrapper which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function iterator_wrapper will be removed in version 4.0.0. Please replace all occurrences of iterator_wrapper(j) with j.items().

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/json_base_class_t/","title":"nlohmann::basic_json::json_base_class_t","text":"
using json_base_class_t = detail::json_base_class<CustomBaseClass>;\n

The base class used to inject custom functionality into each instance of basic_json. Examples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.

"},{"location":"api/basic_json/json_base_class_t/#template-parameters","title":"Template parameters","text":"CustomBaseClass the base class to be added to basic_json"},{"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":"

The default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.

"},{"location":"api/basic_json/json_base_class_t/#limitations","title":"Limitations","text":"

The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.

"},{"location":"api/basic_json/json_base_class_t/#examples","title":"Examples","text":"Example

The following code shows how to inject custom data and methods for each node.

#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

Output:

/ - 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
"},{"location":"api/basic_json/json_base_class_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/json_serializer/","title":"nlohmann::basic_json::json_serializer","text":"
template<typename T, typename SFINAE>\nusing json_serializer = JSONSerializer<T, SFINAE>;\n
"},{"location":"api/basic_json/json_serializer/#template-parameters","title":"Template parameters","text":"T type to convert; will be used in the to_json/from_json functions SFINAE type to add compile type checks via SFINAE; usually void"},{"location":"api/basic_json/json_serializer/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_serializer/#default-type","title":"Default type","text":"

The default values for json_serializer is adl_serializer.

"},{"location":"api/basic_json/json_serializer/#examples","title":"Examples","text":"Example

The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer.

#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

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
"},{"location":"api/basic_json/json_serializer/#version-history","title":"Version history","text":""},{"location":"api/basic_json/max_size/","title":"nlohmann::basic_json::max_size","text":"
size_type max_size() const noexcept;\n

Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the JSON value.

"},{"location":"api/basic_json/max_size/#return-value","title":"Return value","text":"

The return value depends on the different types and is defined as follows:

Value type return value null 0 (same as size()) boolean 1 (same as size()) string 1 (same as size()) number 1 (same as size()) binary 1 (same as size()) object result of function object_t::max_size() array result of function array_t::max_size()"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/max_size/#complexity","title":"Complexity","text":"

Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.

"},{"location":"api/basic_json/max_size/#notes","title":"Notes","text":"

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 1.

"},{"location":"api/basic_json/max_size/#examples","title":"Examples","text":"Example

The following code calls max_size() on the different value types.

#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

Output:

0\n1\n1\n1\n115292150460684697\n576460752303423487\n1\n

Note the output is platform-dependent.

"},{"location":"api/basic_json/max_size/#version-history","title":"Version history","text":""},{"location":"api/basic_json/merge_patch/","title":"nlohmann::basic_json::merge_patch","text":"
void merge_patch(const basic_json& apply_patch);\n

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.

The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):

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

Thereby, Target is the current object; that is, the patch is applied to the current value.

"},{"location":"api/basic_json/merge_patch/#parameters","title":"Parameters","text":"apply_patch (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"

Linear in the lengths of apply_patch.

"},{"location":"api/basic_json/merge_patch/#examples","title":"Examples","text":"Example

The following code shows how a JSON Merge Patch is applied to a JSON document.

#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

Output:

{\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
"},{"location":"api/basic_json/merge_patch/#see-also","title":"See also","text":""},{"location":"api/basic_json/merge_patch/#version-history","title":"Version history","text":""},{"location":"api/basic_json/meta/","title":"nlohmann::basic_json::meta","text":"
static basic_json meta();\n

This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.

"},{"location":"api/basic_json/meta/#return-value","title":"Return value","text":"

JSON object holding version information

key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown. url The URL of the project as string. version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/meta/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/meta/#examples","title":"Examples","text":"Example

The following code shows an example output of the meta() function.

#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

Output:

{\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

Note the output is platform-dependent.

"},{"location":"api/basic_json/meta/#see-also","title":"See also","text":""},{"location":"api/basic_json/meta/#version-history","title":"Version history","text":""},{"location":"api/basic_json/number_float_t/","title":"nlohmann::basic_json::number_float_t","text":"
using number_float_t = NumberFloatType;\n

The type used to store JSON numbers (floating-point).

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t and number_float_t are used.

To store floating-point numbers in C++, a type is defined by the template parameter NumberFloatType which chooses the type to use.

"},{"location":"api/basic_json/number_float_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_float_t/#default-type","title":"Default type","text":"

With the default values for NumberFloatType (double), the default value for number_float_t is double.

"},{"location":"api/basic_json/number_float_t/#default-behavior","title":"Default behavior","text":""},{"location":"api/basic_json/number_float_t/#limits","title":"Limits","text":"

RFC 8259 states:

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.

This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.

"},{"location":"api/basic_json/number_float_t/#storage","title":"Storage","text":"

Floating-point number values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/number_float_t/#examples","title":"Examples","text":"Example

The following code shows that number_float_t is by default, a typedef to double.

#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

Output:

true\n
"},{"location":"api/basic_json/number_float_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/number_integer_t/","title":"nlohmann::basic_json::number_integer_t","text":"
using number_integer_t = NumberIntegerType;\n

The type used to store JSON numbers (integers).

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t and number_float_t are used.

To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.

"},{"location":"api/basic_json/number_integer_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_integer_t/#default-type","title":"Default type","text":"

With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t.

"},{"location":"api/basic_json/number_integer_t/#default-behavior","title":"Default behavior","text":""},{"location":"api/basic_json/number_integer_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (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 number_unsigned_t or number_float_t.

RFC 8259 further states:

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.

As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.

"},{"location":"api/basic_json/number_integer_t/#storage","title":"Storage","text":"

Integer number values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/number_integer_t/#examples","title":"Examples","text":"Example

The following code shows that number_integer_t is by default, a typedef to std::int64_t.

#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

Output:

true\n
"},{"location":"api/basic_json/number_integer_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/number_unsigned_t/","title":"nlohmann::basic_json::number_unsigned_t","text":"
using number_unsigned_t = NumberUnsignedType;\n

The type used to store JSON numbers (unsigned).

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t and number_float_t are used.

To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.

"},{"location":"api/basic_json/number_unsigned_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_unsigned_t/#default-type","title":"Default type","text":"

With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t.

"},{"location":"api/basic_json/number_unsigned_t/#default-behavior","title":"Default behavior","text":""},{"location":"api/basic_json/number_unsigned_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. 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 number_integer_t or number_float_t.

RFC 8259 further states:

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.

As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.

"},{"location":"api/basic_json/number_unsigned_t/#storage","title":"Storage","text":"

Integer number values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/number_unsigned_t/#examples","title":"Examples","text":"Example

The following code shows that number_unsigned_t is by default, a typedef to std::uint64_t.

#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

Output:

true\n
"},{"location":"api/basic_json/number_unsigned_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/object/","title":"nlohmann::basic_json::object","text":"
static basic_json object(initializer_list_t init = {});\n

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 {} is created.

"},{"location":"api/basic_json/object/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"

JSON object value

"},{"location":"api/basic_json/object/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/object/#exceptions","title":"Exceptions","text":"

Throws type_error.301 if init 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 basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list init. See example below.

"},{"location":"api/basic_json/object/#complexity","title":"Complexity","text":"

Linear in the size of init.

"},{"location":"api/basic_json/object/#notes","title":"Notes","text":"

This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t).

"},{"location":"api/basic_json/object/#examples","title":"Examples","text":"Example

The following code shows an example for the object function.

#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

Output:

{}\n{}\n{\"one\":1,\"two\":2}\n[json.exception.type_error.301] cannot create object from initializer list\n
"},{"location":"api/basic_json/object/#see-also","title":"See also","text":""},{"location":"api/basic_json/object/#version-history","title":"Version history","text":""},{"location":"api/basic_json/object_comparator_t/","title":"nlohmann::basic_json::object_comparator_t","text":"
using object_comparator_t = typename object_t::key_compare;\n// or\nusing object_comparator_t = default_object_comparator_t;\n

The comparator used by object_t. Defined as typename object_t::key_compare if available, and default_object_comparator_t otherwise.

"},{"location":"api/basic_json/object_comparator_t/#examples","title":"Examples","text":"Example

The example below demonstrates the used object comparator.

#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

Output:

json::object_comparator_t(\"one\", \"two\") = true\njson::object_comparator_t(\"three\", \"four\") = false\n
"},{"location":"api/basic_json/object_comparator_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/object_t/","title":"nlohmann::basic_json::object_t","text":"
using object_t = ObjectType<StringType,\n                            basic_json,\n                            default_object_comparator_t,\n                            AllocatorType<std::pair<const StringType, basic_json>>>;\n

The type used to store JSON objects.

RFC 8259 describes JSON objects as follows:

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.

To store objects in C++, a type is defined by the template parameters described below.

"},{"location":"api/basic_json/object_t/#template-parameters","title":"Template parameters","text":"ObjectType the container to store objects (e.g., std::map or std::unordered_map) StringType the type of the keys or names (e.g., std::string). The comparison function std::less<StringType> is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/object_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/object_t/#default-type","title":"Default type","text":"

With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:

// 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

See default_object_comparator_t for more information.

"},{"location":"api/basic_json/object_t/#behavior","title":"Behavior","text":"

The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:

"},{"location":"api/basic_json/object_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON object.

"},{"location":"api/basic_json/object_t/#storage","title":"Storage","text":"

Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.

"},{"location":"api/basic_json/object_t/#object-key-order","title":"Object key order","text":"

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 std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.

"},{"location":"api/basic_json/object_t/#examples","title":"Examples","text":"Example

The following code shows that object_t is by default, a typedef to std::map<json::string_t, json>.

#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

Output:

true\n
"},{"location":"api/basic_json/object_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/operator%2B%3D/","title":"nlohmann::basic_json::operator+=","text":"
// (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
  1. Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.

  2. Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.

  3. This function allows using operator+= with an initializer list. In case

    1. the current value is an object,
    2. the initializer list init contains only two elements, and
    3. the first element of init is a string,

    init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).

"},{"location":"api/basic_json/operator%2B%3D/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"

*this

"},{"location":"api/basic_json/operator%2B%3D/#exceptions","title":"Exceptions","text":"

All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use operator+=() with number\"

"},{"location":"api/basic_json/operator%2B%3D/#complexity","title":"Complexity","text":"
  1. Amortized constant.
  2. Logarithmic in the size of the container, O(log(size())).
  3. Linear in the size of the initializer list init.
"},{"location":"api/basic_json/operator%2B%3D/#notes","title":"Notes","text":"

(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.

"},{"location":"api/basic_json/operator%2B%3D/#examples","title":"Examples","text":"Example: (1) add element to array

The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.

#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

Output:

[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n
Example: (2) add element to object

The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n
Example: (3) add to object from initializer list

The example shows how initializer lists are treated as objects when possible.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n
"},{"location":"api/basic_json/operator%2B%3D/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.0.0.
"},{"location":"api/basic_json/operator%3D/","title":"nlohmann::basic_json::operator=","text":"
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

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 swap() member function.

"},{"location":"api/basic_json/operator%3D/#parameters","title":"Parameters","text":"other (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator%3D/#examples","title":"Examples","text":"Example

The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.

#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

Output:

23\n23\n
"},{"location":"api/basic_json/operator%3D/#version-history","title":"Version history","text":""},{"location":"api/basic_json/operator%5B%5D/","title":"nlohmann::basic_json::operator[]","text":"
// (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
  1. Returns a reference to the array element at specified location idx.
  2. Returns a reference to the object element with specified key key. The non-const qualified overload takes the key by value.
  3. See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
  4. Returns a reference to the element with specified JSON pointer ptr.
"},{"location":"api/basic_json/operator%5B%5D/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the element to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"
  1. (const) reference to the element at index idx
  2. (const) reference to the element at key key
  3. (const) reference to the element at key key
  4. (const) reference to the element pointed to by ptr
"},{"location":"api/basic_json/operator%5B%5D/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/operator%5B%5D/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense.
  2. The function can throw the following exceptions:
    • Throws type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense.
  3. See 2.
  4. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'.
    • Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number.
    • Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version.
    • Throws out_of_range.404 if the JSON pointer ptr can not be resolved.
"},{"location":"api/basic_json/operator%5B%5D/#complexity","title":"Complexity","text":"
  1. Constant if idx is in the range of the array. Otherwise, linear in idx - size().
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
  4. Logarithmic in the size of the container.
"},{"location":"api/basic_json/operator%5B%5D/#notes","title":"Notes","text":"

Undefined behavior and runtime assertions

  1. If the element with key idx does not exist, the behavior is undefined.
  2. If the element with key key does not exist, the behavior is undefined and is guarded by a runtime assertion!
  1. The non-const version may add values: If idx is beyond the range of the array (i.e., idx >= size()), then the array is silently filled up with null values to make idx a valid reference to the last stored element. In case the value was null before, it is converted to an array.

  2. If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.

  3. See 2.

  4. null values are created in arrays and objects if necessary.

    In particular:

    • If the JSON pointer points to an object key that does not exist, it is created and filled with a null value before a reference to it is returned.
    • If the JSON pointer points to an array index that does not exist, it is created and filled with a null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.
    • The special value - is treated as a synonym for the index past the end.
"},{"location":"api/basic_json/operator%5B%5D/#examples","title":"Examples","text":"Example: (1) access specified array element

The example below shows how array elements can be read and written using [] operator. Note the addition of null values.

#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

Output:

4\n[1,2,3,4,6]\n[1,2,3,4,6,null,null,null,null,null,11]\n
Example: (1) access specified array element (const)

The example below shows how array elements can be read using the [] operator.

#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

Output:

\"third\"\n
Example: (2) access specified object element

The example below shows how object elements can be read and written using the [] operator.

#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

Output:

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
Example: (2) access specified object element (const)

The example below shows how object elements can be read using the [] operator.

#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

Output:

2\n
Example: (3) access specified object element using string_view

The example below shows how object elements can be read using the [] operator.

#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

Output:

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
Example: (3) access specified object element using string_view (const)

The example below shows how object elements can be read using the [] operator.

#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

Output:

2\n
Example: (4) access specified element via JSON Pointer

The example below shows how values can be read and written using JSON Pointers.

#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

Output:

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
Example: (4) access specified element via JSON Pointer (const)

The example below shows how values can be read using JSON Pointers.

#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

Output:

1\n\"foo\"\n[1,2]\n2\n
"},{"location":"api/basic_json/operator%5B%5D/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator%5B%5D/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0. Added overloads for T* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0.
  3. Added in version 3.11.0.
  4. Added in version 2.0.0.
"},{"location":"api/basic_json/operator_ValueType/","title":"nlohmann::basic_json::operator ValueType","text":"
template<typename ValueType>\nJSON_EXPLICIT operator ValueType() const;\n

Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.

"},{"location":"api/basic_json/operator_ValueType/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"

copy of the JSON value, converted to ValueType

"},{"location":"api/basic_json/operator_ValueType/#exceptions","title":"Exceptions","text":"

Depends on what json_serializer<ValueType> from_json() method throws

"},{"location":"api/basic_json/operator_ValueType/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value.

"},{"location":"api/basic_json/operator_ValueType/#notes","title":"Notes","text":"

Definition of JSON_EXPLICIT

By default JSON_EXPLICIT is defined to the empty string, so the signature is:

template<typename ValueType>\noperator ValueType() const;\n

If JSON_USE_IMPLICIT_CONVERSIONS is set to 0, JSON_EXPLICIT is defined to explicit:

template<typename ValueType>\nexplicit operator ValueType() const;\n

That is, implicit conversions can be switched off by defining JSON_USE_IMPLICIT_CONVERSIONS to 0.

Future behavior change

Implicit conversions will be switched off by default in the next major release of the library. That is, JSON_EXPLICIT will be set to explicit by default.

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.

"},{"location":"api/basic_json/operator_ValueType/#examples","title":"Examples","text":"Example

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 std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.

#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

Output:

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
"},{"location":"api/basic_json/operator_ValueType/#version-history","title":"Version history","text":""},{"location":"api/basic_json/operator_eq/","title":"nlohmann::basic_json::operator==","text":"
// 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
  1. Compares two JSON values for equality according to the following rules:

    • 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 operator==.
    • Integer and floating-point numbers are automatically converted before comparison.
  2. 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.

"},{"location":"api/basic_json/operator_eq/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are equal

"},{"location":"api/basic_json/operator_eq/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_eq/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_eq/#notes","title":"Notes","text":"

Comparing special values

Comparing floating-point numbers

Floating-point numbers inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default. To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance

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

Or you can self-defined operator equal function like this:

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

Comparing different basic_json specializations

Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects

{\n   \"version\": 1,\n   \"type\": \"integer\"\n}\n

and

{\n   \"type\": \"integer\",\n   \"version\": 1\n}\n

depends on whether nlohmann::json or nlohmann::ordered_json is used:

#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

Output:

true\nfalse\n
"},{"location":"api/basic_json/operator_eq/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
Example

The example demonstrates comparing several JSON types against the null pointer (JSON null).

#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

Output:

[1,2,3] == nullptr false\n{\"A\":\"a\",\"B\":\"b\"} == nullptr false\n17 == nullptr false\n\"foo\" == nullptr false\nnull == nullptr true\n
"},{"location":"api/basic_json/operator_eq/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
  2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
"},{"location":"api/basic_json/operator_ge/","title":"nlohmann::basic_json::operator>=","text":"
// 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
  1. Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(lhs < rhs) (see operator<).
  2. 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.

"},{"location":"api/basic_json/operator_ge/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"

whether lhs is less than or equal to rhs

"},{"location":"api/basic_json/operator_ge/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_ge/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_ge/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_ge/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_ge/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_ge/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_gt/","title":"nlohmann::basic_json::operator>","text":"
// 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
  1. Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(lhs <= rhs) (see operator<=).
  2. 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.

"},{"location":"api/basic_json/operator_gt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"

whether lhs is greater than rhs

"},{"location":"api/basic_json/operator_gt/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_gt/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_gt/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_gt/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_gt/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_gt/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_le/","title":"nlohmann::basic_json::operator<=","text":"
// 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
  1. Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(rhs < lhs) (see operator<).
  2. 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.

"},{"location":"api/basic_json/operator_le/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"

whether lhs is less than or equal to rhs

"},{"location":"api/basic_json/operator_le/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_le/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_le/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_le/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_le/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_le/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_lt/","title":"nlohmann::basic_json::operator<","text":"
// 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
  1. Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:

    • If either operand is discarded, the comparison yields false.
    • If both operands have the same type, the values are compared using their respective operator<.
    • Integer and floating-point numbers are automatically converted before comparison.
    • In case lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:
      1. null
      2. boolean
      3. number (all types)
      4. object
      5. array
      6. string
      7. binary For instance, any boolean value is considered less than any string.
  2. 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.

"},{"location":"api/basic_json/operator_lt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"

whether lhs is less than rhs

"},{"location":"api/basic_json/operator_lt/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_lt/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_lt/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_lt/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_lt/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_lt/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_ne/","title":"nlohmann::basic_json::operator!=","text":"
// 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
  1. Compares two JSON values for inequality according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).
  2. 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.

"},{"location":"api/basic_json/operator_ne/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are not equal

"},{"location":"api/basic_json/operator_ne/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_ne/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_ne/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

"},{"location":"api/basic_json/operator_ne/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
Example

The example demonstrates comparing several JSON types against the null pointer (JSON null).

#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

Output:

[1,2,3] != nullptr true\n{\"A\":\"a\",\"B\":\"b\"} != nullptr true\n17 != nullptr true\n\"foo\" != nullptr true\nnull != nullptr false\n
"},{"location":"api/basic_json/operator_ne/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
  2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
"},{"location":"api/basic_json/operator_spaceship/","title":"nlohmann::basic_json::operator<=>","text":"
// 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
  1. 3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:

    • Two JSON values compare with a result of std::partial_ordering::unordered if either value is discarded.
    • If both JSON values are of the same type, the result is produced by 3-way comparing their stored values using their respective operator<=>.
    • Integer and floating-point numbers are converted to their common type and then 3-way compared using their respective operator<=>. 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.
    • Otherwise, yields a result by comparing the type (see value_t).
  2. 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).

"},{"location":"api/basic_json/operator_spaceship/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"rhs (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"

the std::partial_ordering of the 3-way comparison of *this and rhs

"},{"location":"api/basic_json/operator_spaceship/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_spaceship/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_spaceship/#notes","title":"Notes","text":"

Comparing NaN

"},{"location":"api/basic_json/operator_spaceship/#examples","title":"Examples","text":"Example: (1) comparing JSON values

The example demonstrates comparing several JSON values.

#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

Output:

[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
Example: (2) comparing JSON values and scalars

The example demonstrates comparing several JSON values and scalars.

#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

Output:

false <=> true := less\n17 <=> 17.000000 := equivalent\n17 <=> nan := unordered\n\"17\" <=> 17 := greater\n
"},{"location":"api/basic_json/operator_spaceship/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_spaceship/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 3.11.0.
"},{"location":"api/basic_json/operator_value_t/","title":"nlohmann::basic_json::operator value_t","text":"
constexpr operator value_t() const noexcept;\n

Return the type of the JSON value as a value from the value_t enumeration.

"},{"location":"api/basic_json/operator_value_t/#return-value","title":"Return value","text":"

the type of the JSON value

Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/operator_value_t/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/operator_value_t/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/operator_value_t/#examples","title":"Examples","text":"Example

The following code exemplifies operator value_t() for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n
"},{"location":"api/basic_json/operator_value_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/other_error/","title":"nlohmann::basic_json::other_error","text":"
class other_error : public exception;\n

This exception is thrown in case of errors that cannot be classified with the other exception types.

Exceptions have ids 5xx (see list of other errors).

"},{"location":"api/basic_json/other_error/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/other_error/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/other_error/#examples","title":"Examples","text":"Example

The following code shows how a other_error exception can be caught.

#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

Output:

message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n
"},{"location":"api/basic_json/other_error/#see-also","title":"See also","text":""},{"location":"api/basic_json/other_error/#version-history","title":"Version history","text":""},{"location":"api/basic_json/out_of_range/","title":"nlohmann::basic_json::out_of_range","text":"
class out_of_range : public exception;\n

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.

Exceptions have ids 4xx (see list of out-of-range errors).

"},{"location":"api/basic_json/out_of_range/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/out_of_range/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/out_of_range/#examples","title":"Examples","text":"Example

The following code shows how a out_of_range exception can be caught.

#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

Output:

message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n
"},{"location":"api/basic_json/out_of_range/#see-also","title":"See also","text":""},{"location":"api/basic_json/out_of_range/#version-history","title":"Version history","text":""},{"location":"api/basic_json/parse/","title":"nlohmann::basic_json::parse","text":"
// (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
  1. Deserialize from a compatible input.
  2. Deserialize from a pair of character iterators

    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.

"},{"location":"api/basic_json/parse/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType

a compatible iterator type, for instance.

"},{"location":"api/basic_json/parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. cb (in) a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"

Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/parse/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/parse/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/parse/#complexity","title":"Complexity","text":"

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 cb or reading from (1) the input i or (2) the iterator range [first, last] has a super-linear complexity.

"},{"location":"api/basic_json/parse/#notes","title":"Notes","text":"

(1) A UTF-8 byte order mark is silently ignored.

Runtime assertion

The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion.

"},{"location":"api/basic_json/parse/#examples","title":"Examples","text":"Parsing from a character array

The example below demonstrates the parse() function reading from an array.

#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

Output:

{\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
Parsing from a string

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
Parsing from an input stream

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
Parsing from a contiguous container

The example below demonstrates the parse() function reading from a contiguous container.

#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

Output:

[\n    1,\n    2,\n    3\n]\n
Parsing from a non null-terminated string

The example below demonstrates the parse() function reading from a string that is not null-terminated.

#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

Output:

[\n    1,\n    2,\n    3\n]\n
Parsing from an iterator pair

The example below demonstrates the parse() function reading from an iterator pair.

#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

Output:

[\n    1,\n    2,\n    3\n]\n
Effect of allow_exceptions parameter

The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function.

#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

Output:

[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
"},{"location":"api/basic_json/parse/#see-also","title":"See also","text":""},{"location":"api/basic_json/parse/#version-history","title":"Version history","text":"

Deprecation

Overload (2) replaces calls to parse 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 parse({ptr, ptr+len}, ...); with parse(ptr, ptr+len, ...);.

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/parse_error/","title":"nlohmann::basic_json::parse_error","text":"
class parse_error : public exception;\n

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.

Member byte holds the byte index of the last read character in the input file (see note below).

Exceptions have ids 1xx (see list of parse errors).

"},{"location":"api/basic_json/parse_error/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/parse_error/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/parse_error/#notes","title":"Notes","text":"

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.

"},{"location":"api/basic_json/parse_error/#examples","title":"Examples","text":"Example

The following code shows how a parse_error exception can be caught.

#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

Output:

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
"},{"location":"api/basic_json/parse_error/#see-also","title":"See also","text":""},{"location":"api/basic_json/parse_error/#version-history","title":"Version history","text":""},{"location":"api/basic_json/parse_event_t/","title":"nlohmann::basic_json::parse_event_t","text":"
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

The parser callback distinguishes the following events:

"},{"location":"api/basic_json/parse_event_t/#examples","title":"Examples","text":""},{"location":"api/basic_json/parse_event_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/parser_callback_t/","title":"nlohmann::basic_json::parser_callback_t","text":"
template<typename BasicJsonType>\nusing parser_callback_t =\n    std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n

With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.

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 depth, event, and parsed.

parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value

Discarding a value (i.e., returning false) has different effects depending on the context in which function was called:

"},{"location":"api/basic_json/parser_callback_t/#parameters","title":"Parameters","text":"depth (in) the depth of the recursion during parsing event (in) an event of type parse_event_t indicating the context in the callback function has been called parsed (in, out) the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"

Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.

"},{"location":"api/basic_json/parser_callback_t/#examples","title":"Examples","text":"Example

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
"},{"location":"api/basic_json/parser_callback_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/patch/","title":"nlohmann::basic_json::patch","text":"
basic_json patch(const basic_json& json_patch) const;\n

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.

"},{"location":"api/basic_json/patch/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch/#return-value","title":"Return value","text":"

patched document

"},{"location":"api/basic_json/patch/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/patch/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/patch/#complexity","title":"Complexity","text":"

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.

"},{"location":"api/basic_json/patch/#notes","title":"Notes","text":"

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.

"},{"location":"api/basic_json/patch/#examples","title":"Examples","text":"Example

The following code shows how a JSON patch is applied to a value.

#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

Output:

{\n    \"baz\": \"qux\",\n    \"foo\": \"bar\"\n}\n\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"api/basic_json/patch/#see-also","title":"See also","text":""},{"location":"api/basic_json/patch/#version-history","title":"Version history","text":""},{"location":"api/basic_json/patch_inplace/","title":"nlohmann::basic_json::patch_inplace","text":"
void patch_inplace(const basic_json& json_patch) const;\n

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.

"},{"location":"api/basic_json/patch_inplace/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch_inplace/#exception-safety","title":"Exception safety","text":"

No guarantees, value may be corrupted by an unsuccessful patch operation.

"},{"location":"api/basic_json/patch_inplace/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/patch_inplace/#complexity","title":"Complexity","text":"

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.

"},{"location":"api/basic_json/patch_inplace/#notes","title":"Notes","text":"

Unlike patch, patch_inplace 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.

"},{"location":"api/basic_json/patch_inplace/#examples","title":"Examples","text":"Example

The following code shows how a JSON patch is applied to a value.

#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

Output:

Before\n{\n    \"baz\": \"qux\",\n    \"foo\": \"bar\"\n}\n\nAfter\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"api/basic_json/patch_inplace/#see-also","title":"See also","text":""},{"location":"api/basic_json/patch_inplace/#version-history","title":"Version history","text":""},{"location":"api/basic_json/push_back/","title":"nlohmann::basic_json::push_back","text":"
// (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
  1. Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.

  2. Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.

  3. This function allows using push_back with an initializer list. In case

    1. the current value is an object,
    2. the initializer list init contains only two elements, and
    3. the first element of init is a string,

    init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).

"},{"location":"api/basic_json/push_back/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"

All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use push_back() with number\"

"},{"location":"api/basic_json/push_back/#complexity","title":"Complexity","text":"
  1. Amortized constant.
  2. Logarithmic in the size of the container, O(log(size())).
  3. Linear in the size of the initializer list init.
"},{"location":"api/basic_json/push_back/#notes","title":"Notes","text":"

(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.

"},{"location":"api/basic_json/push_back/#examples","title":"Examples","text":"Example: (1) add element to array

The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.

#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

Output:

[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n
Example: (2) add element to object

The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n
Example: (3) add to object from initializer list

The example shows how initializer lists are treated as objects when possible.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n
"},{"location":"api/basic_json/push_back/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.0.0.
"},{"location":"api/basic_json/rbegin/","title":"nlohmann::basic_json::rbegin","text":"
reverse_iterator rbegin() noexcept;\nconst_reverse_iterator rbegin() const noexcept;\n

Returns an iterator to the reverse-beginning; that is, the last element.

"},{"location":"api/basic_json/rbegin/#return-value","title":"Return value","text":"

reverse iterator to the first element

"},{"location":"api/basic_json/rbegin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/rbegin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/rbegin/#examples","title":"Examples","text":"Example

The following code shows an example for rbegin().

#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

Output:

5\n
"},{"location":"api/basic_json/rbegin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/rend/","title":"nlohmann::basic_json::rend","text":"
reverse_iterator rend() noexcept;\nconst_reverse_iterator rend() const noexcept;\n

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.

"},{"location":"api/basic_json/rend/#return-value","title":"Return value","text":"

reverse iterator to the element following the last element

"},{"location":"api/basic_json/rend/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/rend/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/rend/#examples","title":"Examples","text":"Example

The following code shows an example for eend().

#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

Output:

1\n
"},{"location":"api/basic_json/rend/#version-history","title":"Version history","text":""},{"location":"api/basic_json/sax_parse/","title":"nlohmann::basic_json::sax_parse","text":"
// (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

Read from input and generate SAX events

  1. Read from a compatible input.
  2. Read from a pair of character iterators

    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.

The SAX event lister must follow the interface of json_sax.

"},{"location":"api/basic_json/sax_parse/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType Description SAX Description"},{"location":"api/basic_json/sax_parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. sax (in) SAX event listener format (in) the format to parse (JSON, CBOR, MessagePack, or UBJSON) (optional, input_format_t::json by default), see input_format_t for more information strict (in) whether the input has to be consumed completely (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/sax_parse/#return-value","title":"Return value","text":"

return value of the last processed SAX event

"},{"location":"api/basic_json/sax_parse/#exception-safety","title":"Exception safety","text":""},{"location":"api/basic_json/sax_parse/#complexity","title":"Complexity","text":"

Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.

"},{"location":"api/basic_json/sax_parse/#notes","title":"Notes","text":"

A UTF-8 byte order mark is silently ignored.

"},{"location":"api/basic_json/sax_parse/#examples","title":"Examples","text":"Example

The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer.

#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

Output:

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
"},{"location":"api/basic_json/sax_parse/#version-history","title":"Version history","text":"

Deprecation

Overload (2) replaces calls to sax_parse 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 sax_parse({ptr, ptr+len}); with sax_parse(ptr, ptr+len);.

"},{"location":"api/basic_json/size/","title":"nlohmann::basic_json::size","text":"
size_type size() const noexcept;\n

Returns the number of elements in a JSON value.

"},{"location":"api/basic_json/size/#return-value","title":"Return value","text":"

The return value depends on the different types and is defined as follows:

Value type return value null 0 boolean 1 string 1 number 1 binary 1 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":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/size/#complexity","title":"Complexity","text":"

Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.

"},{"location":"api/basic_json/size/#notes","title":"Notes","text":"

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 1 in the case of a string.

"},{"location":"api/basic_json/size/#examples","title":"Examples","text":"Example

The following code calls size() on the different value types.

#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

Output:

0\n1\n1\n1\n2\n0\n5\n0\n1\n
"},{"location":"api/basic_json/size/#version-history","title":"Version history","text":""},{"location":"api/basic_json/std_hash/","title":"std::hash<nlohmann::basic_json>","text":"
namespace std {\n    struct hash<nlohmann::basic_json>;\n}\n

Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.

"},{"location":"api/basic_json/std_hash/#examples","title":"Examples","text":"Example

The example shows how to calculate hash values for different JSON values.

#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

Output:

hash(null) = 2654435769\nhash(false) = 2654436030\nhash(0) = 2654436095\nhash(0U) = 2654436156\nhash(\"\") = 6142509191626859748\nhash({}) = 2654435832\nhash([]) = 2654435899\nhash({\"hello\": \"world\"}) = 4469488738203676328\n

Note the output is platform-dependent.

"},{"location":"api/basic_json/std_hash/#version-history","title":"Version history","text":""},{"location":"api/basic_json/std_swap/","title":"std::swap<basic_json>","text":"
namespace std {\n    void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2);\n}\n

Exchanges the values of two JSON objects.

"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"
void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2)\n{\n    j1.swap(j2);\n}\n
"},{"location":"api/basic_json/std_swap/#examples","title":"Examples","text":"Example

The following code shows how two values are swapped with std::swap.

#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

Output:

j1 = {\"one\":1,\"two\":2} | j2 = [1,2,4,8,16]\nj1 = [1,2,4,8,16] | j2 = {\"one\":1,\"two\":2}\n
"},{"location":"api/basic_json/std_swap/#see-also","title":"See also","text":""},{"location":"api/basic_json/std_swap/#version-history","title":"Version history","text":""},{"location":"api/basic_json/string_t/","title":"nlohmann::basic_json::string_t","text":"
using string_t = StringType;\n

The type used to store JSON strings.

RFC 8259 describes JSON strings as follows:

A string is a sequence of zero or more Unicode characters.

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.

"},{"location":"api/basic_json/string_t/#template-parameters","title":"Template parameters","text":"StringType the container to store strings (e.g., std::string). 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":"

With the default values for StringType (std::string), the default value for string_t is std::string.

"},{"location":"api/basic_json/string_t/#encoding","title":"Encoding","text":"

Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.

"},{"location":"api/basic_json/string_t/#string-comparison","title":"String comparison","text":"

RFC 8259 states:

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 \"a\\\\b\" and \"a\\u005Cb\" are not equal.

This implementation is interoperable as it does compare strings code unit by code unit.

"},{"location":"api/basic_json/string_t/#storage","title":"Storage","text":"

String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.

"},{"location":"api/basic_json/string_t/#examples","title":"Examples","text":"Example

The following code shows that string_t is by default, a typedef to std::string.

#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

Output:

true\n
"},{"location":"api/basic_json/string_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/swap/","title":"nlohmann::basic_json::swap","text":"
// (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
  1. Exchanges the contents of the JSON value with those of other. 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.
  2. Exchanges the contents of the JSON value from left with those of right. 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.
  3. Exchanges the contents of a JSON array with those of other. 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.
  4. Exchanges the contents of a JSON object with those of other. 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.
  5. Exchanges the contents of a JSON string with those of other. 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.
  6. Exchanges the contents of a binary value with those of other. 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.
  7. Exchanges the contents of a binary value with those of other. 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.
"},{"location":"api/basic_json/swap/#parameters","title":"Parameters","text":"other (in, out) value to exchange the contents with left (in, out) value to exchange the contents with right (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"
  1. No-throw guarantee: this function never throws exceptions.
  2. No-throw guarantee: this function never throws exceptions.
  3. Throws type_error.310 if called on JSON values other than arrays; example: \"cannot use swap() with boolean\"
  4. Throws type_error.310 if called on JSON values other than objects; example: \"cannot use swap() with boolean\"
  5. Throws type_error.310 if called on JSON values other than strings; example: \"cannot use swap() with boolean\"
  6. Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
  7. Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
"},{"location":"api/basic_json/swap/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/swap/#examples","title":"Examples","text":"Example: Swap JSON value (1, 2)

The example below shows how JSON values can be swapped with swap().

#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

Output:

j1 = {\"e\":2.718281828459045,\"pi\":3.141592653589793}\nj2 = [1,2,3,4,5]\n
Example: Swap array (3)

The example below shows how arrays can be swapped with swap().

#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

Output:

value = {\"array\":[\"Snap\",\"Crackle\",\"Pop\"]}\narray = [1,2,3,4]\n
Example: Swap object (4)

The example below shows how objects can be swapped with swap().

#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

Output:

value = {\"translation\":{\"cow\":\"Kuh\",\"dog\":\"Hund\"}}\nobject = {\"one\":\"eins\",\"two\":\"zwei\"}\n
Example: Swap string (5)

The example below shows how strings can be swapped with swap().

#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

Output:

value = [\"the good\",\"the fast\",\"the ugly\"]\nstring = the bad\n
Example: Swap string (6)

The example below shows how binary values can be swapped with swap().

#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

Output:

value = {\"bytes\":[4,5,6],\"subtype\":null}\nbinary = {\"bytes\":[1,2,3],\"subtype\":null}\n
"},{"location":"api/basic_json/swap/#see-also","title":"See also","text":""},{"location":"api/basic_json/swap/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 1.0.0.
  4. Since version 1.0.0.
  5. Since version 1.0.0.
  6. Since version 3.8.0.
  7. Since version 3.8.0.
"},{"location":"api/basic_json/to_bjdata/","title":"nlohmann::basic_json::to_bjdata","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the BJData serialization.
  2. Writes the BJData serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"
  1. BJData serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_bjdata/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_bjdata/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_bjdata/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in BJData format.

#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"api/basic_json/to_bjdata/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_bson/","title":"nlohmann::basic_json::to_bson","text":"
// (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

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).

  1. Returns a byte vector containing the BSON serialization.
  2. Writes the BSON serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"
  1. BSON serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_bson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_bson/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_bson/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in BSON format.

#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

Output:

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
"},{"location":"api/basic_json/to_bson/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_cbor/","title":"nlohmann::basic_json::to_cbor","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the CBOR serialization.
  2. Writes the CBOR serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"
  1. CBOR serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_cbor/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_cbor/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_cbor/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in CBOR format.

#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

Output:

0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"api/basic_json/to_cbor/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_msgpack/","title":"nlohmann::basic_json::to_msgpack","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the MessagePack serialization.
  2. Writes the MessagePack serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"
  1. MessagePack serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_msgpack/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_msgpack/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_msgpack/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in MessagePack format.

#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

Output:

0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"api/basic_json/to_msgpack/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_string/","title":"to_string(basic_json)","text":"
template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j);\n

This function implements a user-defined to_string for JSON objects.

"},{"location":"api/basic_json/to_string/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/basic_json/to_string/#return-value","title":"Return value","text":"

string containing the serialization of the JSON value

"},{"location":"api/basic_json/to_string/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/to_string/#exceptions","title":"Exceptions","text":"

Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded

"},{"location":"api/basic_json/to_string/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/to_string/#possible-implementation","title":"Possible implementation","text":"
template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j)\n{\n    return j.dump();\n}\n
"},{"location":"api/basic_json/to_string/#examples","title":"Examples","text":"Example

The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup.

#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

Output:

{\"one\":1,\"two\":2}\n\n42\n
"},{"location":"api/basic_json/to_string/#see-also","title":"See also","text":""},{"location":"api/basic_json/to_string/#version-history","title":"Version history","text":"

Added in version 3.7.0.

"},{"location":"api/basic_json/to_ubjson/","title":"nlohmann::basic_json::to_ubjson","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the UBJSON serialization.
  2. Writes the UBJSON serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"
  1. UBJSON serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_ubjson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_ubjson/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_ubjson/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in UBJSON format.

#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"api/basic_json/to_ubjson/#version-history","title":"Version history","text":""},{"location":"api/basic_json/type/","title":"nlohmann::basic_json::type","text":"
constexpr value_t type() const noexcept;\n

Return the type of the JSON value as a value from the value_t enumeration.

"},{"location":"api/basic_json/type/#return-value","title":"Return value","text":"

the type of the JSON value

Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/type/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/type/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/type/#examples","title":"Examples","text":"Example

The following code exemplifies type() for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n
"},{"location":"api/basic_json/type/#version-history","title":"Version history","text":""},{"location":"api/basic_json/type_error/","title":"nlohmann::basic_json::type_error","text":"
class type_error : public exception;\n

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.

Exceptions have ids 3xx (see list of type errors).

"},{"location":"api/basic_json/type_error/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/type_error/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/type_error/#examples","title":"Examples","text":"Example

The following code shows how a type_error exception can be caught.

#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

Output:

message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n
"},{"location":"api/basic_json/type_error/#see-also","title":"See also","text":""},{"location":"api/basic_json/type_error/#version-history","title":"Version history","text":""},{"location":"api/basic_json/type_name/","title":"nlohmann::basic_json::type_name","text":"
const char* type_name() const noexcept;\n

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.

"},{"location":"api/basic_json/type_name/#return-value","title":"Return value","text":"

a string representation of the type (value_t):

Value type return value null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\""},{"location":"api/basic_json/type_name/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/type_name/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/type_name/#examples","title":"Examples","text":"Example

The following code exemplifies type_name() for all JSON types.

#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

Output:

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
"},{"location":"api/basic_json/type_name/#version-history","title":"Version history","text":""},{"location":"api/basic_json/unflatten/","title":"nlohmann::basic_json::unflatten","text":"
basic_json unflatten() const;\n

The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints:

  1. The value must be an object.
  2. The keys must be JSON pointers (see RFC 6901)
  3. The mapped values must be primitive JSON types.
"},{"location":"api/basic_json/unflatten/#return-value","title":"Return value","text":"

the original JSON from a flattened version

"},{"location":"api/basic_json/unflatten/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/unflatten/#exceptions","title":"Exceptions","text":"

The function can throw the following exceptions:

"},{"location":"api/basic_json/unflatten/#complexity","title":"Complexity","text":"

Linear in the size the JSON value.

"},{"location":"api/basic_json/unflatten/#notes","title":"Notes","text":"

Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j, the following is always true: j == j.flatten().unflatten().

"},{"location":"api/basic_json/unflatten/#examples","title":"Examples","text":"Example

The following code shows how a flattened JSON object is unflattened into the original nested JSON object.

#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

Output:

{\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
"},{"location":"api/basic_json/unflatten/#see-also","title":"See also","text":""},{"location":"api/basic_json/unflatten/#version-history","title":"Version history","text":""},{"location":"api/basic_json/update/","title":"nlohmann::basic_json::update","text":"
// (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
  1. Inserts all values from JSON object j.
  2. Inserts all values from range [first, last)

When merge_objects is false (default), existing keys are overwritten. When merge_objects is true, recursively merges objects with common keys.

The function is motivated by Python's dict.update function.

"},{"location":"api/basic_json/update/#parameters","title":"Parameters","text":"j (in) JSON object to read values from merge_objects (in) when true, existing keys are not overwritten, but contents of objects are merged recursively (default: false) first (in) begin of the range of elements to insert last (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
  2. The function can throw the following exceptions:
    • Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
"},{"location":"api/basic_json/update/#complexity","title":"Complexity","text":"
  1. O(N*log(size() + N)), where N is the number of elements to insert.
  2. O(N*log(size() + N)), where N is the number of elements to insert.
"},{"location":"api/basic_json/update/#examples","title":"Examples","text":"Example

The example shows how update() is used.

#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

Output:

{\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
Example

The example shows how update() is used.

#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

Output:

{\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
Example

One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects:

{\n    \"color\": \"red\",\n    \"active\": true,\n    \"name\": {\"de\": \"Maus\", \"en\": \"mouse\"}\n}\n

The user may override the default settings selectively:

{\n    \"color\": \"blue\",\n    \"name\": {\"es\": \"rat\u00f3n\"},\n}\n

Then update manages the merging of default settings and user settings:

auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings);\n

Now effective_settings contains the default settings, but those keys set by the user are overwritten:

{\n    \"color\": \"blue\",\n    \"active\": true,\n    \"name\": {\"es\": \"rat\u00f3n\"}\n}\n

Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true:

auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings, true);\n
{\n    \"color\": \"blue\",\n    \"active\": true,\n    \"name\": {\"de\": \"Maus\", \"en\": \"mouse\", \"es\": \"rat\u00f3n\"}\n}\n
"},{"location":"api/basic_json/update/#version-history","title":"Version history","text":""},{"location":"api/basic_json/value/","title":"nlohmann::basic_json::value","text":"
// (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
  1. Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.

    The function is basically equivalent to executing

    try {\n   return at(key);\n} catch(out_of_range) {\n   return default_value;\n}\n

  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.

  3. Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists.

    The function is basically equivalent to executing

    try {\n   return at(ptr);\n} catch(out_of_range) {\n   return default_value;\n}\n

Differences to at and operator[]

"},{"location":"api/basic_json/value/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17). ValueType type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"key (in) key of the element to access default_value (in) the value to return if key/ptr found no value ptr (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"
  1. copy of the element at key key or default_value if key is not found
  2. copy of the element at key key or default_value if key is not found
  3. copy of the element at JSON Pointer ptr or default_value if no value for ptr is found
"},{"location":"api/basic_json/value/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/value/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.302 if default_value does not match the type of the value at key
    • Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.
  2. See 1.
  3. The function can throw the following exceptions:
    • Throws type_error.302 if default_value does not match the type of the value at ptr
    • Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.
"},{"location":"api/basic_json/value/#complexity","title":"Complexity","text":"
  1. Logarithmic in the size of the container.
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
"},{"location":"api/basic_json/value/#examples","title":"Examples","text":"Example: (1) access specified object element with default value

The example below shows how object elements can be queried with a default value.

#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

Output:

1 42.23 oops false\n
Example: (2) access specified object element using string_view with default value

The example below shows how object elements can be queried with a default value.

#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

Output:

1 42.23 oops false\n
Example: (3) access specified object element via JSON Pointer with default value

The example below shows how object elements can be queried with a default value.

#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

Output:

1 42.23 oops false\n
"},{"location":"api/basic_json/value/#see-also","title":"See also","text":""},{"location":"api/basic_json/value/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Changed parameter default_value type from const ValueType& to ValueType&& in version 3.11.0.
  2. Added in version 3.11.0. Made ValueType the first template parameter in version 3.11.2.
  3. Added in version 2.0.2.
"},{"location":"api/basic_json/value_t/","title":"nlohmann::basic_json::value_t","text":"
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

This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions is_null, is_object, is_array, is_string, is_boolean, is_number (with is_number_integer, is_number_unsigned, and is_number_float), is_discarded, is_binary, is_primitive, and is_structured rely on it.

"},{"location":"api/basic_json/value_t/#notes","title":"Notes","text":"

Ordering

The order of types is as follows:

  1. null
  2. boolean
  3. number_integer, number_unsigned, number_float
  4. object
  5. array
  6. string
  7. binary

discarded is unordered.

Types of numbers

There are three enumerators for numbers (number_integer, number_unsigned, and number_float) to distinguish between different types of numbers:

Comparison operators

operator< and operator<=> (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 operator<=> during overload resolution, while others do not. For predictable and portable behavior use:

"},{"location":"api/basic_json/value_t/#examples","title":"Examples","text":"Example

The following code how type() queries the value_t for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n
"},{"location":"api/basic_json/value_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/~basic_json/","title":"nlohmann::basic_json::~basic_json","text":"
~basic_json() noexcept;\n

Destroys the JSON value and frees all allocated memory.

"},{"location":"api/basic_json/~basic_json/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/~basic_json/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/~basic_json/#version-history","title":"Version history","text":""},{"location":"api/byte_container_with_subtype/","title":"nlohmann::byte_container_with_subtype","text":"
template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n

This type extends the template parameter BinaryType provided to basic_json 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.

"},{"location":"api/byte_container_with_subtype/#template-parameters","title":"Template parameters","text":"BinaryType container to store bytes (std::vector<std::uint8_t> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":""},{"location":"api/byte_container_with_subtype/#member-functions","title":"Member functions","text":""},{"location":"api/byte_container_with_subtype/#version-history","title":"Version history","text":""},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/","title":"nlohmann::byte_container_with_subtype::byte_container_with_subtype","text":"
// (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
  1. Create empty binary container without subtype.
  2. Create binary container without subtype.
  3. Create binary container with subtype.
"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#parameters","title":"Parameters","text":"container (in) binary container subtype (in) subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how byte containers can be created.

#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

Output:

{\"bytes\":[],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":42}\n
"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/clear_subtype/","title":"nlohmann::byte_container_with_subtype::clear_subtype","text":"
void clear_subtype() noexcept;\n

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.

"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how clear_subtype can remove subtypes.

#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

Output:

before calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":42}\nafter calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":null}\n
"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/has_subtype/","title":"nlohmann::byte_container_with_subtype::has_subtype","text":"
constexpr bool has_subtype() const noexcept;\n

Returns whether the value has a subtype.

"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","title":"Return value","text":"

whether the value has a subtype

"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how has_subtype can check whether a subtype was set.

#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

Output:

c1.has_subtype() = false\nc2.has_subtype() = true\n
"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/set_subtype/","title":"nlohmann::byte_container_with_subtype::set_subtype","text":"
void set_subtype(subtype_type subtype) noexcept;\n

Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.

"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","title":"Parameters","text":"subtype (in) subtype to set"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how a subtype can be set with set_subtype.

#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

Output:

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
"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/subtype/","title":"nlohmann::byte_container_with_subtype::subtype","text":"
constexpr subtype_type subtype() const noexcept;\n

Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return subtype_type(-1) as a sentinel value.

"},{"location":"api/byte_container_with_subtype/subtype/#return-value","title":"Return value","text":"

the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set

"},{"location":"api/byte_container_with_subtype/subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how the subtype can be retrieved with subtype. Note how subtype_type(-1) is returned for container c1.

#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

Output:

c1.subtype() = 18446744073709551615\nc2.subtype() = 42\n
"},{"location":"api/byte_container_with_subtype/subtype/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/","title":"nlohmann::json_pointer","text":"
template<typename RefStringType>\nclass json_pointer;\n

A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.

"},{"location":"api/json_pointer/#template-parameters","title":"Template parameters","text":"RefStringType the string type used for the reference tokens making up the JSON pointer

Deprecation

For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.

"},{"location":"api/json_pointer/#member-types","title":"Member types","text":""},{"location":"api/json_pointer/#member-functions","title":"Member functions","text":""},{"location":"api/json_pointer/#literals","title":"Literals","text":""},{"location":"api/json_pointer/#see-also","title":"See also","text":""},{"location":"api/json_pointer/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/back/","title":"nlohmann::json_pointer::back","text":"
const string_t& back() const;\n

Return last reference token.

"},{"location":"api/json_pointer/back/#return-value","title":"Return value","text":"

Last reference token.

"},{"location":"api/json_pointer/back/#exceptions","title":"Exceptions","text":"

Throws out_of_range.405 if JSON pointer has no parent.

"},{"location":"api/json_pointer/back/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/json_pointer/back/#examples","title":"Examples","text":"Example

The example shows the usage of back.

#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

Output:

last reference token of \"/foo\" is \"foo\"\nlast reference token of \"/foo/0\" is \"0\"\n
"},{"location":"api/json_pointer/back/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/empty/","title":"nlohmann::json_pointer::empty","text":"
bool empty() const noexcept;\n

Return whether pointer points to the root document.

"},{"location":"api/json_pointer/empty/#return-value","title":"Return value","text":"

true iff the JSON pointer points to the root document.

"},{"location":"api/json_pointer/empty/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/json_pointer/empty/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/json_pointer/empty/#examples","title":"Examples","text":"Example

The example shows the result of empty for different JSON Pointers.

#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

Output:

\"\": true\n\"\": true\n\"/foo\": false\n\"/foo/0\": false\n
"},{"location":"api/json_pointer/empty/#version-history","title":"Version history","text":"

Added in version 3.6.0.

"},{"location":"api/json_pointer/json_pointer/","title":"nlohmann::json_pointer::json_pointer","text":"
explicit json_pointer(const string_t& s = \"\");\n

Create a JSON pointer according to the syntax described in Section 3 of RFC6901.

"},{"location":"api/json_pointer/json_pointer/#parameters","title":"Parameters","text":"s (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":""},{"location":"api/json_pointer/json_pointer/#examples","title":"Examples","text":"Example

The example shows the construction several valid JSON pointers as well as the exceptional behavior.

#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

Output:

[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
"},{"location":"api/json_pointer/json_pointer/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/operator_eq/","title":"nlohmann::json_pointer::operator==","text":"
// 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
  1. Compares two JSON pointers for equality by comparing their reference tokens.

  2. 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.

"},{"location":"api/json_pointer/operator_eq/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are equal

"},{"location":"api/json_pointer/operator_eq/#exception-safety","title":"Exception safety","text":"
  1. No-throw guarantee: this function never throws exceptions.
  2. Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/json_pointer/operator_eq/#exceptions","title":"Exceptions","text":"
  1. (none)
  2. The function can throw the following exceptions:
  3. Throws parse_error.107 if the given JSON pointer s is nonempty and does not begin with a slash (/); see example below.
  4. Throws parse_error.108 if a tilde (~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.
"},{"location":"api/json_pointer/operator_eq/#complexity","title":"Complexity","text":"

Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.

"},{"location":"api/json_pointer/operator_eq/#notes","title":"Notes","text":"

Deprecation

Overload 2 is deprecated and will be removed in a future major version release.

"},{"location":"api/json_pointer/operator_eq/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointers

The example demonstrates comparing JSON pointers.

#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

Output:

\"\" == \"\": true\n\"\" == \"\": true\n\"\" == \"/foo\": false\n\"/foo\" == \"/foo\": true\n
Example: (2) Comparing JSON pointers and strings

The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.

#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

Output:

\"\" == \"\": 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
"},{"location":"api/json_pointer/operator_eq/#version-history","title":"Version history","text":"
  1. Added in version 2.1.0. Added C++20 member functions in version 3.11.2.
  2. Added for backward compatibility and deprecated in version 3.11.2.
"},{"location":"api/json_pointer/operator_ne/","title":"nlohmann::json_pointer::operator!=","text":"
// 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
  1. Compares two JSON pointers for inequality by comparing their reference tokens.

  2. 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.

"},{"location":"api/json_pointer/operator_ne/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are not equal

"},{"location":"api/json_pointer/operator_ne/#exception-safety","title":"Exception safety","text":"
  1. No-throw guarantee: this function never throws exceptions.
  2. Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/json_pointer/operator_ne/#exceptions","title":"Exceptions","text":"
  1. (none)
  2. The function can throw the following exceptions:
  3. Throws parse_error.107 if the given JSON pointer s is nonempty and does not begin with a slash (/); see example below.
  4. Throws parse_error.108 if a tilde (~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.
"},{"location":"api/json_pointer/operator_ne/#complexity","title":"Complexity","text":"

Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.

"},{"location":"api/json_pointer/operator_ne/#notes","title":"Notes","text":"

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator==.

Deprecation

Overload 2 is deprecated and will be removed in a future major version release.

"},{"location":"api/json_pointer/operator_ne/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointers

The example demonstrates comparing JSON pointers.

#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

Output:

\"\" != \"\": false\n\"\" != \"\": false\n\"\" != \"/foo\": true\n\"/foo\" != \"/foo\": false\n
Example: (2) Comparing JSON pointers and strings

The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.

#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

Output:

\"\" != \"\": 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
"},{"location":"api/json_pointer/operator_ne/#version-history","title":"Version history","text":"
  1. Added in version 2.1.0.
  2. Added for backward compatibility and deprecated in version 3.11.2.
"},{"location":"api/json_pointer/operator_slash/","title":"nlohmann::json_pointer::operator/","text":"
// (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
  1. create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  2. create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  3. create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
"},{"location":"api/json_pointer/operator_slash/#parameters","title":"Parameters","text":"lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slash/#return-value","title":"Return value","text":"
  1. a new JSON pointer with rhs appended to lhs
  2. a new JSON pointer with unescaped token appended to lhs
  3. a new JSON pointer with array_idx appended to lhs
"},{"location":"api/json_pointer/operator_slash/#complexity","title":"Complexity","text":"
  1. Linear in the length of lhs and rhs.
  2. Linear in the length of lhs.
  3. Linear in the length of lhs.
"},{"location":"api/json_pointer/operator_slash/#examples","title":"Examples","text":"Example

The example shows the usage of operator/.

#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

Output:

\"/foo/bar/baz\"\n\"/foo/fob\"\n\"/foo/42\"\n
"},{"location":"api/json_pointer/operator_slash/#version-history","title":"Version history","text":"
  1. Added in version 3.6.0.
  2. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.
  3. Added in version 3.6.0.
"},{"location":"api/json_pointer/operator_slasheq/","title":"nlohmann::json_pointer::operator/=","text":"
// (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
  1. append another JSON pointer at the end of this JSON pointer
  2. append an unescaped reference token at the end of this JSON pointer
  3. append an array index at the end of this JSON pointer
"},{"location":"api/json_pointer/operator_slasheq/#parameters","title":"Parameters","text":"ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"
  1. JSON pointer with ptr appended
  2. JSON pointer with token appended without escaping token
  3. JSON pointer with array_idx appended
"},{"location":"api/json_pointer/operator_slasheq/#complexity","title":"Complexity","text":"
  1. Linear in the length of ptr.
  2. Amortized constant.
  3. Amortized constant.
"},{"location":"api/json_pointer/operator_slasheq/#examples","title":"Examples","text":"Example

The example shows the usage of operator/=.

#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

Output:

\"/foo\"\n\"/foo/bar/baz\"\n\"/foo/bar/baz/fob\"\n\"/foo/bar/baz/fob/42\"\n
"},{"location":"api/json_pointer/operator_slasheq/#version-history","title":"Version history","text":"
  1. Added in version 3.6.0.
  2. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.
  3. Added in version 3.6.0.
"},{"location":"api/json_pointer/operator_string_t/","title":"nlohmann::json_pointer::operator string_t","text":"
operator string_t() const\n

Return a string representation of the JSON pointer.

"},{"location":"api/json_pointer/operator_string_t/#return-value","title":"Return value","text":"

A string representation of the JSON pointer

"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","title":"Possible implementation","text":"
operator string_t() const\n{\n    return to_string();\n}\n
"},{"location":"api/json_pointer/operator_string_t/#notes","title":"Notes","text":"

Deprecation

This function is deprecated in favor of to_string and will be removed in a future major version release.

"},{"location":"api/json_pointer/operator_string_t/#examples","title":"Examples","text":"Example

The example shows how JSON Pointers can be implicitly converted to strings.

#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

Output:

/foo/0\n/a~1b\n
"},{"location":"api/json_pointer/operator_string_t/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/parent_pointer/","title":"nlohmann::json_pointer::parent_pointer","text":"
json_pointer parent_pointer() const;\n

Returns the parent of this JSON pointer.

"},{"location":"api/json_pointer/parent_pointer/#return-value","title":"Return value","text":"

Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.

"},{"location":"api/json_pointer/parent_pointer/#complexity","title":"Complexity","text":"

Linear in the length of the JSON pointer.

"},{"location":"api/json_pointer/parent_pointer/#examples","title":"Examples","text":"Example

The example shows the result of parent_pointer for different JSON Pointers.

#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

Output:

parent of \"\" is \"\"\nparent of \"/foo\" is \"\"\nparent of \"/foo/0\" is \"/foo\"\n
"},{"location":"api/json_pointer/parent_pointer/#version-history","title":"Version history","text":"

Added in version 3.6.0.

"},{"location":"api/json_pointer/pop_back/","title":"nlohmann::json_pointer::pop_back","text":"
void pop_back();\n

Remove last reference token.

"},{"location":"api/json_pointer/pop_back/#exceptions","title":"Exceptions","text":"

Throws out_of_range.405 if JSON pointer has no parent.

"},{"location":"api/json_pointer/pop_back/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/json_pointer/pop_back/#examples","title":"Examples","text":"Example

The example shows the usage of pop_back.

#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

Output:

\"/foo/bar/baz\"\n\"/foo/bar\"\n\"/foo\"\n\"\"\n
"},{"location":"api/json_pointer/pop_back/#version-history","title":"Version history","text":"

Added in version 3.6.0.

"},{"location":"api/json_pointer/push_back/","title":"nlohmann::json_pointer::push_back","text":"
void push_back(const string_t& token);\n\nvoid push_back(string_t&& token);\n

Append an unescaped token at the end of the reference pointer.

"},{"location":"api/json_pointer/push_back/#parameters","title":"Parameters","text":"token (in) token to add"},{"location":"api/json_pointer/push_back/#complexity","title":"Complexity","text":"

Amortized constant.

"},{"location":"api/json_pointer/push_back/#examples","title":"Examples","text":"Example

The example shows the result of push_back for different JSON Pointers.

#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

Output:

\"\"\n\"/foo\"\n\"/foo/0\"\n\"/foo/0/bar\"\n
"},{"location":"api/json_pointer/push_back/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/string_t/","title":"nlohmann::json_pointer::string_t","text":"
using string_t = RefStringType;\n

The string type used for the reference tokens making up the JSON pointer.

See basic_json::string_t for more information.

"},{"location":"api/json_pointer/string_t/#examples","title":"Examples","text":"Example

The example shows the type string_t and its relation to basic_json::string_t.

#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

Output:

This is a string.\ntrue\n
"},{"location":"api/json_pointer/string_t/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/to_string/","title":"nlohmann::json_pointer::to_string","text":"
string_t to_string() const;\n

Return a string representation of the JSON pointer.

"},{"location":"api/json_pointer/to_string/#return-value","title":"Return value","text":"

A string representation of the JSON pointer

"},{"location":"api/json_pointer/to_string/#notes","title":"Notes","text":"

For each JSON pointer ptr, it holds:

ptr == json_pointer(ptr.to_string());\n
"},{"location":"api/json_pointer/to_string/#examples","title":"Examples","text":"Example

The example shows the result of to_string.

#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

Output:

\"\"\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
"},{"location":"api/json_pointer/to_string/#version-history","title":"Version history","text":""},{"location":"api/json_sax/","title":"nlohmann::json_sax","text":"
template<typename BasicJsonType>\nstruct json_sax;\n

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.

"},{"location":"api/json_sax/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/json_sax/#member-types","title":"Member types","text":""},{"location":"api/json_sax/#member-functions","title":"Member functions","text":""},{"location":"api/json_sax/#version-history","title":"Version history","text":""},{"location":"api/json_sax/binary/","title":"nlohmann::json_sax::binary","text":"
virtual bool binary(binary_t& val) = 0;\n

A binary value was read.

"},{"location":"api/json_sax/binary/#parameters","title":"Parameters","text":"val (in) binary value"},{"location":"api/json_sax/binary/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/binary/#notes","title":"Notes","text":"

It is safe to move the passed binary value.

"},{"location":"api/json_sax/binary/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

binary(val=[...])\n\nresult: true\n
"},{"location":"api/json_sax/binary/#version-history","title":"Version history","text":""},{"location":"api/json_sax/boolean/","title":"nlohmann::json_sax::boolean","text":"
virtual bool boolean(bool val) = 0;\n

A boolean value was read.

"},{"location":"api/json_sax/boolean/#parameters","title":"Parameters","text":"val (in) boolean value"},{"location":"api/json_sax/boolean/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/boolean/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/boolean/#version-history","title":"Version history","text":""},{"location":"api/json_sax/end_array/","title":"nlohmann::json_sax::end_array","text":"
virtual bool end_array() = 0;\n

The end of an array was read.

"},{"location":"api/json_sax/end_array/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/end_array/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/end_array/#version-history","title":"Version history","text":""},{"location":"api/json_sax/end_object/","title":"nlohmann::json_sax::end_object","text":"
virtual bool end_object() = 0;\n

The end of an object was read.

"},{"location":"api/json_sax/end_object/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/end_object/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/end_object/#version-history","title":"Version history","text":""},{"location":"api/json_sax/key/","title":"nlohmann::json_sax::key","text":"
virtual bool key(string_t& val) = 0;\n

An object key was read.

"},{"location":"api/json_sax/key/#parameters","title":"Parameters","text":"val (in) object key"},{"location":"api/json_sax/key/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/key/#notes","title":"Notes","text":"

It is safe to move the passed object key value.

"},{"location":"api/json_sax/key/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/key/#version-history","title":"Version history","text":""},{"location":"api/json_sax/null/","title":"nlohmann::json_sax::null","text":"
virtual bool null() = 0;\n

A null value was read.

"},{"location":"api/json_sax/null/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/null/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/null/#version-history","title":"Version history","text":""},{"location":"api/json_sax/number_float/","title":"nlohmann::json_sax::number_float","text":"
virtual bool number_float(number_float_t val, const string_t& s) = 0;\n

A floating-point number was read.

"},{"location":"api/json_sax/number_float/#parameters","title":"Parameters","text":"val (in) floating-point value s (in) string representation of the original input"},{"location":"api/json_sax/number_float/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/number_float/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/number_float/#version-history","title":"Version history","text":""},{"location":"api/json_sax/number_integer/","title":"nlohmann::json_sax::number_integer","text":"
virtual bool number_integer(number_integer_t val) = 0;\n

An integer number was read.

"},{"location":"api/json_sax/number_integer/#parameters","title":"Parameters","text":"val (in) integer value"},{"location":"api/json_sax/number_integer/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/number_integer/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/number_integer/#version-history","title":"Version history","text":""},{"location":"api/json_sax/number_unsigned/","title":"nlohmann::json_sax::number_unsigned","text":"
virtual bool number_unsigned(number_unsigned_t val) = 0;\n

An unsigned integer number was read.

"},{"location":"api/json_sax/number_unsigned/#parameters","title":"Parameters","text":"val (in) unsigned integer value"},{"location":"api/json_sax/number_unsigned/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/number_unsigned/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/number_unsigned/#version-history","title":"Version history","text":""},{"location":"api/json_sax/parse_error/","title":"nlohmann::json_sax::parse_error","text":"
virtual bool parse_error(std::size_t position,\n                         const std::string& last_token,\n                         const detail::exception& ex) = 0;\n

A parse error occurred.

"},{"location":"api/json_sax/parse_error/#parameters","title":"Parameters","text":"position (in) the position in the input where the error occurs last_token (in) the last read token ex (in) an exception object describing the error"},{"location":"api/json_sax/parse_error/#return-value","title":"Return value","text":"

Whether parsing should proceed (must return false).

"},{"location":"api/json_sax/parse_error/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/parse_error/#version-history","title":"Version history","text":""},{"location":"api/json_sax/start_array/","title":"nlohmann::json_sax::start_array","text":"
virtual bool start_array(std::size_t elements) = 0;\n

The beginning of an array was read.

"},{"location":"api/json_sax/start_array/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_array/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/start_array/#notes","title":"Notes","text":"

Binary formats may report the number of elements.

"},{"location":"api/json_sax/start_array/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/start_array/#version-history","title":"Version history","text":""},{"location":"api/json_sax/start_object/","title":"nlohmann::json_sax::start_object","text":"
virtual bool start_object(std::size_t elements) = 0;\n

The beginning of an object was read.

"},{"location":"api/json_sax/start_object/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_object/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/start_object/#notes","title":"Notes","text":"

Binary formats may report the number of elements.

"},{"location":"api/json_sax/start_object/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/start_object/#version-history","title":"Version history","text":""},{"location":"api/json_sax/string/","title":"nlohmann::json_sax::string","text":"
virtual bool string(string_t& val) = 0;\n

A string value was read.

"},{"location":"api/json_sax/string/#parameters","title":"Parameters","text":"val (in) string value"},{"location":"api/json_sax/string/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/string/#notes","title":"Notes","text":"

It is safe to move the passed string value.

"},{"location":"api/json_sax/string/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/string/#version-history","title":"Version history","text":""},{"location":"api/macros/","title":"Macros","text":"

Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page.

"},{"location":"api/macros/#runtime-assertions","title":"Runtime assertions","text":""},{"location":"api/macros/#exceptions","title":"Exceptions","text":""},{"location":"api/macros/#language-support","title":"Language support","text":""},{"location":"api/macros/#library-version","title":"Library version","text":""},{"location":"api/macros/#library-namespace","title":"Library namespace","text":""},{"location":"api/macros/#type-conversions","title":"Type conversions","text":""},{"location":"api/macros/#comparison-behavior","title":"Comparison behavior","text":""},{"location":"api/macros/#serializationdeserialization-macros","title":"Serialization/deserialization macros","text":""},{"location":"api/macros/json_assert/","title":"JSON_ASSERT","text":"
#define JSON_ASSERT(x) /* value */\n

This macro controls which code is executed for runtime assertions of the library.

"},{"location":"api/macros/json_assert/#parameters","title":"Parameters","text":"x (in) expression of scalar type"},{"location":"api/macros/json_assert/#default-definition","title":"Default definition","text":"

The default value is assert(x).

#define JSON_ASSERT(x) assert(x)\n

Therefore, assertions can be switched off by defining NDEBUG.

"},{"location":"api/macros/json_assert/#notes","title":"Notes","text":""},{"location":"api/macros/json_assert/#examples","title":"Examples","text":"Example 1: default behavior

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n
Example 2: user-defined behavior

The assertion reporting can be changed by defining JSON_ASSERT(x) differently.

#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

Output:

assertion error in operator[]\n
"},{"location":"api/macros/json_assert/#version-history","title":"Version history","text":""},{"location":"api/macros/json_diagnostics/","title":"JSON_DIAGNOSTICS","text":"
#define JSON_DIAGNOSTICS /* value */\n

This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).

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.

"},{"location":"api/macros/json_diagnostics/#default-definition","title":"Default definition","text":"

The default value is 0 (extended diagnostics are switched off).

#define JSON_DIAGNOSTICS 0\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_diagnostics/#notes","title":"Notes","text":"

ABI compatibility

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.

This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior.

Where possible, it is still recommended that all code define this the same way for maximum interoperability.

CMake option

Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which defines JSON_DIAGNOSTICS accordingly.

"},{"location":"api/macros/json_diagnostics/#examples","title":"Examples","text":"Example 1: default behavior
#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

Output:

[json.exception.type_error.302] type must be number, but is string\n

This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.

Example 2: extended diagnostic messages
#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

Output:

[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n

Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.

"},{"location":"api/macros/json_diagnostics/#version-history","title":"Version history","text":""},{"location":"api/macros/json_disable_enum_serialization/","title":"JSON_DISABLE_ENUM_SERIALIZATION","text":"
#define JSON_DISABLE_ENUM_SERIALIZATION /* value */\n

When defined to 1, default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details).

Parsing or serializing an enum will result in a compiler error.

This works for both unscoped and scoped enums.

"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","title":"Default definition","text":"

The default value is 0.

#define JSON_DISABLE_ENUM_SERIALIZATION 0\n
"},{"location":"api/macros/json_disable_enum_serialization/#notes","title":"Notes","text":"

CMake option

Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization (OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.

"},{"location":"api/macros/json_disable_enum_serialization/#examples","title":"Examples","text":"Example 1: Disabled behavior

The code below forces the library not to create default serialization/deserialization functions from_json and to_json, meaning the code below does not compile.

#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
Example 2: Serialize enum macro

The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses NLOHMANN_JSON_SERIALIZE_ENUM to parse and serialize the enum.

#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
Example 3: User-defined serialization/deserialization functions

The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses user-defined functions to parse and serialize the enum.

#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
"},{"location":"api/macros/json_disable_enum_serialization/#see-also","title":"See also","text":""},{"location":"api/macros/json_disable_enum_serialization/#version-history","title":"Version history","text":""},{"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":"
#define JSON_HAS_CPP_11\n#define JSON_HAS_CPP_14\n#define JSON_HAS_CPP_17\n#define JSON_HAS_CPP_20\n

The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view 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.

"},{"location":"api/macros/json_has_cpp_11/#default-definition","title":"Default definition","text":"

The default value is detected based on preprocessor macros such as __cplusplus, _HAS_CXX17, or _MSVC_LANG.

"},{"location":"api/macros/json_has_cpp_11/#notes","title":"Notes","text":""},{"location":"api/macros/json_has_cpp_11/#examples","title":"Examples","text":"Example

The code below forces the library to use the C++14 standard:

#define JSON_HAS_CPP_14 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_cpp_11/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_filesystem/","title":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"
#define JSON_HAS_FILESYSTEM /* value */\n#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */\n

When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.

"},{"location":"api/macros/json_has_filesystem/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macros __cpp_lib_filesystem, __cpp_lib_experimental_filesystem, __has_include(<filesystem>), or __has_include(<experimental/filesystem>).

"},{"location":"api/macros/json_has_filesystem/#notes","title":"Notes","text":""},{"location":"api/macros/json_has_filesystem/#examples","title":"Examples","text":"Example

The code below forces the library to use the header <experimental/filesystem>.

#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_filesystem/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_ranges/","title":"JSON_HAS_RANGES","text":"
#define JSON_HAS_RANGES /* value */\n

This macro indicates whether the standard library has any support for ranges. Implies support for concepts. Possible values are 1 when supported or 0 when unsupported.

"},{"location":"api/macros/json_has_ranges/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macro __cpp_lib_ranges.

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_has_ranges/#examples","title":"Examples","text":"Example

The code below forces the library to enable support for ranges:

#define JSON_HAS_RANGES 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_ranges/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_static_rtti/","title":"JSON_HAS_STATIC_RTTI","text":"
#define JSON_HAS_STATIC_RTTI /* value */\n

This macro indicates whether the standard library has any support for RTTI (run time type information). Possible values are 1 when supported or 0 when unsupported.

"},{"location":"api/macros/json_has_static_rtti/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI.

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_has_static_rtti/#examples","title":"Examples","text":"Example

The code below forces the library to enable support for libraries with RTTI dependence:

#define JSON_HAS_STATIC_RTTI 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_static_rtti/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_three_way_comparison/","title":"JSON_HAS_THREE_WAY_COMPARISON","text":"
#define JSON_HAS_THREE_WAY_COMPARISON /* value */\n

This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.

"},{"location":"api/macros/json_has_three_way_comparison/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison.

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_has_three_way_comparison/#examples","title":"Examples","text":"Example

The code below forces the library to use 3-way comparison:

#define JSON_HAS_THREE_WAY_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_three_way_comparison/#version-history","title":"Version history","text":""},{"location":"api/macros/json_no_io/","title":"JSON_NO_IO","text":"
#define JSON_NO_IO\n

When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> 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)).

"},{"location":"api/macros/json_no_io/#default-definition","title":"Default definition","text":"

By default, JSON_NO_IO is not defined.

#undef JSON_NO_IO\n
"},{"location":"api/macros/json_no_io/#examples","title":"Examples","text":"Example

The code below forces the library not to use the headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream>.

#define JSON_NO_IO 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_no_io/#version-history","title":"Version history","text":""},{"location":"api/macros/json_noexception/","title":"JSON_NOEXCEPTION","text":"
#define JSON_NOEXCEPTION\n

Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION. When defining JSON_NOEXCEPTION, try is replaced by if (true), catch is replaced by if (false), and throw is replaced by std::abort().

The same effect is achieved by setting the compiler flag -fno-exceptions.

"},{"location":"api/macros/json_noexception/#default-definition","title":"Default definition","text":"

By default, the macro is not defined.

#undef JSON_NOEXCEPTION\n
"},{"location":"api/macros/json_noexception/#notes","title":"Notes","text":"

The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.

"},{"location":"api/macros/json_noexception/#examples","title":"Examples","text":"Example

The code below switches off exceptions in the library.

#define JSON_NOEXCEPTION 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_noexception/#see-also","title":"See also","text":""},{"location":"api/macros/json_noexception/#version-history","title":"Version history","text":"

Added in version 2.1.0.

"},{"location":"api/macros/json_skip_library_version_check/","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"
#define JSON_SKIP_LIBRARY_VERSION_CHECK\n

When defined, the library will not create a compiler warning when a different version of the library was already included.

"},{"location":"api/macros/json_skip_library_version_check/#default-definition","title":"Default definition","text":"

By default, the macro is not defined.

#undef JSON_SKIP_LIBRARY_VERSION_CHECK\n
"},{"location":"api/macros/json_skip_library_version_check/#notes","title":"Notes","text":"

ABI compatibility

Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.

"},{"location":"api/macros/json_skip_library_version_check/#examples","title":"Examples","text":"

Example

The following warning will be shown in case a different version of the library was already included:

Already included a different version of the library!\n
"},{"location":"api/macros/json_skip_library_version_check/#version-history","title":"Version history","text":"

Added in version 3.11.0.

"},{"location":"api/macros/json_skip_unsupported_compiler_check/","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n

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.

"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","title":"Default definition","text":"

By default, the macro is not defined.

#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n
"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","title":"Examples","text":"Example

The code below switches off the check whether the compiler is supported.

#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","title":"Version history","text":"

Added in version 3.2.0.

"},{"location":"api/macros/json_throw_user/","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER","text":"
// (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

Controls how exceptions are handled by the library.

  1. This macro overrides catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.
  2. This macro overrides throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
  3. This macro overrides try calls inside the library. It has no arguments and is always followed by a scope.
"},{"location":"api/macros/json_throw_user/#parameters","title":"Parameters","text":"exception (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"

By default, the macros map to their respective C++ keywords:

#define JSON_CATCH_USER(exception) catch(exception)\n#define JSON_THROW_USER(exception) throw exception\n#define JSON_TRY_USER              try\n

When exceptions are switched off, the try block is executed unconditionally, and throwing exceptions is replaced by calling std::abort to make reaching the throw branch abort the process.

#define JSON_THROW_USER(exception) std::abort()\n#define JSON_TRY_USER              if (true)\n#define JSON_CATCH_USER(exception) if (false)\n
"},{"location":"api/macros/json_throw_user/#examples","title":"Examples","text":"Example

The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.

#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
"},{"location":"api/macros/json_throw_user/#see-also","title":"See also","text":""},{"location":"api/macros/json_throw_user/#version-history","title":"Version history","text":""},{"location":"api/macros/json_use_global_udls/","title":"JSON_USE_GLOBAL_UDLS","text":"
#define JSON_USE_GLOBAL_UDLS /* value */\n

When defined to 1, the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals.

"},{"location":"api/macros/json_use_global_udls/#default-definition","title":"Default definition","text":"

The default value is 1.

#define JSON_USE_GLOBAL_UDLS 1\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_use_global_udls/#notes","title":"Notes","text":"

Future behavior change

The user-defined string literals will be removed from the global namespace in the next major release of the library.

To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details.

CMake option

The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs (ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.

"},{"location":"api/macros/json_use_global_udls/#examples","title":"Examples","text":"Example 1: Default behavior

The code below shows the default behavior using the _json UDL.

#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

Output:

42\n
Example 2: Namespaced UDLs

The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0.

#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

Output:

42\n
"},{"location":"api/macros/json_use_global_udls/#see-also","title":"See also","text":""},{"location":"api/macros/json_use_global_udls/#version-history","title":"Version history","text":""},{"location":"api/macros/json_use_implicit_conversions/","title":"JSON_USE_IMPLICIT_CONVERSIONS","text":"
#define JSON_USE_IMPLICIT_CONVERSIONS /* value */\n

When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType.

"},{"location":"api/macros/json_use_implicit_conversions/#default-definition","title":"Default definition","text":"

By default, implicit conversions are enabled.

#define JSON_USE_IMPLICIT_CONVERSIONS 1\n
"},{"location":"api/macros/json_use_implicit_conversions/#notes","title":"Notes","text":"

Future behavior change

Implicit conversions will be switched off by default in the next major release of the library.

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.

CMake option

Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions (ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.

"},{"location":"api/macros/json_use_implicit_conversions/#examples","title":"Examples","text":"Example

This is an example for an implicit conversion:

json j = \"Hello, world!\";\nstd::string s = j;\n

When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0, the code above does no longer compile. Instead, it must be written like this:

json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n
"},{"location":"api/macros/json_use_implicit_conversions/#see-also","title":"See also","text":""},{"location":"api/macros/json_use_implicit_conversions/#version-history","title":"Version history","text":""},{"location":"api/macros/json_use_legacy_discarded_value_comparison/","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON","text":"
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */\n

This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default).

When enabled, comparisons involving at least one discarded JSON value yield results as follows:

Operator Result == false != true < false <= true >= true > false

Otherwise, comparisons involving at least one discarded JSON value always yield false.

"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#default-definition","title":"Default definition","text":"

The default value is 0.

#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","title":"Notes","text":"

Inconsistent behavior in C++20 and beyond

When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.

Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in inconsistent and unpredictable behavior.

See operator<=> for more information on 3-way comparison.

Deprecation

The legacy comparison behavior is deprecated and may be removed in a future major version release.

New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.

CMake option

Legacy comparison can also be controlled with the CMake option JSON_LegacyDiscardedValueComparison (OFF by default) which defines JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON accordingly.

"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#examples","title":"Examples","text":"Example

The code below switches on the legacy discarded value comparison behavior in the library.

#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","title":"Version history","text":""},{"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":"
#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

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 NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.

  1. Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
  2. Will use value 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 from_json() function default constructs an object and uses its values as the defaults when calling the value function.
  3. Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
"},{"location":"api/macros/nlohmann_define_type_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (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":"

The macros add two friend functions to the class which take care of the serialization and deserialization:

friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&); // except (3)\n

See examples below for the concrete generated code.

"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","title":"Notes","text":"

Prerequisites

  1. The type type must be default constructible (except (3)). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
  2. The macro must be used inside the type (class/struct).

Implementation limits

"},{"location":"api/macros/nlohmann_define_type_intrusive/#examples","title":"Examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n

Notes:

The macro is equivalent to:

#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
Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n

Notes:

The macro is equivalent to:

#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

Note how a default-initialized person object is used in the from_json to fill missing values.

Example (3): NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n

Notes:

The macro is equivalent to:

#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
"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_define_type_intrusive/#version-history","title":"Version history","text":"
  1. Added in version 3.9.0.
  2. Added in version 3.11.0.
  3. Added in version TODO.
"},{"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":"
#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

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 NLOHMANN_DEFINE_TYPE_INTRUSIVE, it cannot access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.

  1. Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
  2. Will use value 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 from_json() function default constructs an object and uses its values as the defaults when calling the value function.
  3. Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (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":"

The macros add two functions to the namespace which take care of the serialization and deserialization:

void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&); // except (3)\n

See examples below for the concrete generated code.

"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","title":"Notes","text":"

Prerequisites

  1. The type type must be default constructible (except (3). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
  2. The macro must be used outside the type (class/struct).
  3. The passed members must be public.

Implementation limits

"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#examples","title":"Examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n

Notes:

The macro is equivalent to:

#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
Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n

Notes:

The macro is equivalent to:

#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

Note how a default-initialized person object is used in the from_json to fill missing values.

Example (3): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n

Notes:

The macro is equivalent to:

#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
"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_define_type_non_intrusive/#version-history","title":"Version history","text":"
  1. Added in version 3.9.0.
  2. Added in version 3.11.0.
  3. Added in version TODO.
"},{"location":"api/macros/nlohmann_json_namespace/","title":"NLOHMANN_JSON_NAMESPACE","text":"
#define NLOHMANN_JSON_NAMESPACE /* value */\n

This macro evaluates to the full name of the nlohmann namespace.

"},{"location":"api/macros/nlohmann_json_namespace/#default-definition","title":"Default definition","text":"

The default value consists of the root namespace (nlohmann) and an inline ABI namespace. See nlohmann Namespace for details.

When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.

"},{"location":"api/macros/nlohmann_json_namespace/#examples","title":"Examples","text":"Example

The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.

#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

Output:

nlohmann::json_abi_v3_11_3\n
"},{"location":"api/macros/nlohmann_json_namespace/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_namespace/#version-history","title":"Version history","text":""},{"location":"api/macros/nlohmann_json_namespace_begin/","title":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END","text":"
#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */  // (1)\n#define NLOHMANN_JSON_NAMESPACE_END   /* value */  // (2)\n

These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details.

  1. Opens the namespace.
  2. Closes the namespace.
"},{"location":"api/macros/nlohmann_json_namespace_begin/#default-definition","title":"Default definition","text":"

The default definitions open and close the nlohmann namespace. The precise definition of [NLOHMANN_JSON_NAMESPACE_BEGIN] varies as described here.

  1. Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN:

    namespace nlohmann\n{\ninline namespace json_abi_v3_11_2\n{\n
  2. Default definition of NLOHMANN_JSON_NAMESPACE_END:

    }  // namespace json_abi_v3_11_2\n}  // namespace nlohmann\n

When these macros are not defined, the library will define them to their default definitions.

"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","title":"Examples","text":"Example

The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN/NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page.

#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

Output:

[1,null]\n
"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_namespace_begin/#version-history","title":"Version history","text":""},{"location":"api/macros/nlohmann_json_namespace_no_version/","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION","text":"
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */\n

If defined to 1, the version component is omitted from the inline namespace. See nlohmann Namespace for details.

"},{"location":"api/macros/nlohmann_json_namespace_no_version/#default-definition","title":"Default definition","text":"

The default value is 0.

#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","title":"Examples","text":"Example

The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace.

#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

Output:

nlohmann::json_abi\n
"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_namespace_no_version/#version-history","title":"Version history","text":""},{"location":"api/macros/nlohmann_json_serialize_enum/","title":"NLOHMANN_JSON_SERIALIZE_ENUM","text":"
#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)\n

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.

The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.

"},{"location":"api/macros/nlohmann_json_serialize_enum/#parameters","title":"Parameters","text":"type (in) name of the enum to serialize/deserialize conversion (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":"

The macros add two friend functions to the class which take care of the serialization and deserialization:

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
"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","title":"Notes","text":"

Prerequisites

The macro must be used inside the namespace of the enum.

Important notes

"},{"location":"api/macros/nlohmann_json_serialize_enum/#examples","title":"Examples","text":"Example 1: Basic usage

The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes:

#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

Output:

ns::TS_STOPPED -> \"stopped\", ns::Color::red -> \"red\"\n\"running\" -> 1, \"blue\" -> 2\n3.14 -> -1, 3.14 -> 3\n
Example 2: Multiple conversions for one enumerator

The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\", because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red.

#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

Output:

0 -> \"red\"\n\"rot\" -> 0\n\"red\" -> 0\n
"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_serialize_enum/#version-history","title":"Version history","text":"

Added in version 3.4.0.

"},{"location":"api/macros/nlohmann_json_version_major/","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"
#define NLOHMANN_JSON_VERSION_MAJOR /* value */\n#define NLOHMANN_JSON_VERSION_MINOR /* value */\n#define NLOHMANN_JSON_VERSION_PATCH /* value */\n

These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.

"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","title":"Default definition","text":"

The macros are defined according to the current library version.

"},{"location":"api/macros/nlohmann_json_version_major/#examples","title":"Examples","text":"Example

The example below shows how NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH are defined by the library.

#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

Output:

JSON for Modern C++ version 3.11.3\n
"},{"location":"api/macros/nlohmann_json_version_major/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_version_major/#version-history","title":"Version history","text":""},{"location":"features/arbitrary_types/","title":"Arbitrary Type Conversions","text":"

Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:

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

It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:

// 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
"},{"location":"features/arbitrary_types/#basic-usage","title":"Basic usage","text":"

To make this work with one of your types, you only need to provide two functions:

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

That's all! When calling the json constructor with your type, your custom to_json method will be automatically called. Likewise, when calling template get<your_type>() or get_to(your_type&), the from_json method will be called.

Some important things:

"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","title":"Simplify your life with macros","text":"

If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate.

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:

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.

Implementation limits

Example

The to_json/from_json functions for the person struct above can be created with:

namespace ns {\n    NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n}\n

Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed:

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
"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"

This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:

The library uses JSON Serializers to convert types to json. The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).

It is implemented like this (simplified):

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

This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...

To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:

// 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

ABI compatibility

Use NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END instead of namespace nlohmann { } in code which may be linked with different versions of this library.

"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types","title":"How can I use get() for non-default constructible/non-copyable types?","text":"

There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:

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
"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"

Yes. You might want to take a look at unit-udt.cpp in the test suite, to see a few examples.

If you write your own serializer, you'll need to do a few things:

Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.

// 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

Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:

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 to_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
"},{"location":"features/assertions/","title":"Runtime Assertions","text":"

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.

"},{"location":"features/assertions/#switch-off-runtime-assertions","title":"Switch off runtime assertions","text":"

Runtime assertions can be switched off by defining the preprocessor macro NDEBUG (see the documentation of assert) which is the default for release builds.

"},{"location":"features/assertions/#change-assertion-behavior","title":"Change assertion behavior","text":"

The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header.

"},{"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":"

Function operator[] 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.

If you are not sure whether an element in an object exists, use checked access with the at function or call the contains function before.

See also the documentation on element access.

Example 1: Missing object key

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n
"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"

Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.

Example 2: Uninitialized iterator range

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n
"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"

Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.

Example 3: Uninitialized iterator

The following code will trigger an assertion at runtime:

#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n  json::iterator it;\n  ++it;\n}\n

Output:

Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n
"},{"location":"features/assertions/#reading-from-a-null-file-pointer","title":"Reading from a null FILE pointer","text":"

Reading from a null FILE pointer is undefined behavior and yields a runtime assertion. This can happen when calling std::fopen on a nonexistent file.

Example 4: Uninitialized iterator

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.\n
"},{"location":"features/binary_values/","title":"Binary Values","text":"

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.

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.

"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"

By default, binary values are stored as std::vector<std::uint8_t>. This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t:

auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE});\nauto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n

There are several convenience functions to check and set the subtype:

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

As json::binary_t is subclassing std::vector<std::uint8_t>, all member functions are available:

binary.size();  // returns 4\nbinary[1];      // returns 0xFE\n

JSON values can be constructed from json::binary_t:

json j = binary;\n

Binary values are primitive values just like numbers or strings:

j.is_binary();    // returns true\nj.is_primitive(); // returns true\n

Given a binary JSON value, the binary_t can be accessed by reference as via get_binary():

j.get_binary().has_subtype();  // returns true\nj.get_binary().size();         // returns 4\n

For convenience, binary JSON values can be constructed via json::binary:

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
"},{"location":"features/binary_values/#serialization","title":"Serialization","text":"

Binary values are serialized differently according to the formats.

"},{"location":"features/binary_values/#json","title":"JSON","text":"

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: bytes holds an array of integers, and subtype is an integer or null.

Example

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

Output:

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": 42\n  }\n}\n

No roundtrip for binary values

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.

"},{"location":"features/binary_values/#bjdata","title":"BJData","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 20 elements:

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

The following code uses the type and size optimization for UBJSON:

// convert to UBJSON using the size and type optimization\nauto v = json::to_bjdata(j, true, true);\n

The resulting vector has 22 elements; the optimization is not effective for examples with few values:

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

Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:

{\n  \"binary\": [202, 254, 186, 190]\n}\n
"},{"location":"features/binary_values/#bson","title":"BSON","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 22 elements:

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

Note that the serialization preserves the subtype, and deserializing v would yield the following value:

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": 42\n  }\n}\n
"},{"location":"features/binary_values/#cbor","title":"CBOR","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 15 elements:

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

Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless json::cbor_tag_handler_t::ignore or json::cbor_tag_handler_t::store is passed to json::from_cbor.

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": null\n  }\n}\n
"},{"location":"features/binary_values/#messagepack","title":"MessagePack","text":"

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.

If no subtype is given, the bin family (bin8, bin16, bin32) is used.

Example

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

v is a std::vector<std::uint8t> with the following 14 elements:

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

Note that the serialization preserves the subtype, and deserializing v would yield the following value:

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": 42\n  }\n}\n
"},{"location":"features/binary_values/#ubjson","title":"UBJSON","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 20 elements:

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

The following code uses the type and size optimization for UBJSON:

// convert to UBJSON using the size and type optimization\nauto v = json::to_ubjson(j, true, true);\n

The resulting vector has 23 elements; the optimization is not effective for examples with few values:

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

Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:

{\n  \"binary\": [202, 254, 186, 190]\n}\n
"},{"location":"features/comments/","title":"Comments","text":"

This library does not support comments by default. It does so for three reasons:

  1. Comments are not part of the JSON specification. You may argue that // or /* */ are allowed in JavaScript, but JSON is not JavaScript.
  2. This was not an oversight: Douglas Crockford wrote on this in May 2012:

    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
  3. 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.

However, you can pass set parameter ignore_comments to true in the parse function to ignore // or /* */ comments. Comments will then be treated as whitespace.

Example

Consider the following JSON with comments.

{\n    // update in 2006: removed Pluto\n    \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n                \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n}\n

When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true, the comments are ignored during parsing:

#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

Output:

[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
{\n  \"planets\": [\n    \"Mercury\",\n    \"Venus\",\n    \"Earth\",\n    \"Mars\",\n    \"Jupiter\",\n    \"Uranus\",\n    \"Neptune\"\n  ]\n}\n
"},{"location":"features/enum_conversion/","title":"Specializing enum conversion","text":"

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.

It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:

// 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

The NLOHMANN_JSON_SERIALIZE_ENUM() macro declares a set of to_json() / from_json() functions for type TaskState while avoiding repetition and boilerplate serialization code.

"},{"location":"features/enum_conversion/#usage","title":"Usage","text":"
// 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
"},{"location":"features/enum_conversion/#notes","title":"Notes","text":"

Just as in Arbitrary Type Conversions above,

Other Important points:

"},{"location":"features/iterators/","title":"Iterators","text":""},{"location":"features/iterators/#overview","title":"Overview","text":"

A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values.

As for other containers, begin() returns an iterator to the first value and end() 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, begin() will return end().

"},{"location":"features/iterators/#iteration-order-for-objects","title":"Iteration order for objects","text":"

When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.

Example
// 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

Output:

1\n3\n2\n

The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".

"},{"location":"features/iterators/#access-object-key-during-iteration","title":"Access object key during iteration","text":"

The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown.

Example
// 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

Output:

one : 1\nthree : 3\ntwo : 2\n
"},{"location":"features/iterators/#range-based-for-loops","title":"Range-based for loops","text":"

C++11 allows using range-based for loops to iterate over a container.

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

For this reason, the items() function allows accessing iterator::key() and iterator::value() 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.

for (auto& el : j_object.items())\n{\n    std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n

The items() function also allows using structured bindings (C++17):

for (auto& [key, val] : j_object.items())\n{\n    std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n

Note

When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string.

Warning

Using items() 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.

"},{"location":"features/iterators/#reverse-iteration-order","title":"Reverse iteration order","text":"

rbegin() and rend() return iterators in the reverse sequence.

Example
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

Output:

4\n3\n2\n1\n
"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"

Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe the underlying string or binary array is empty.

Example
json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n    std::cout << *it << std::endl;\n}\n

Output:

\"Hello, world\"\n
"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators clear all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"

JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.

Example

The following code shows how a JSON patch is applied to a value.

#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

Output:

{\n    \"baz\": \"qux\",\n    \"foo\": \"bar\"\n}\n\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"features/json_patch/#diff","title":"Diff","text":"

The library can also calculate a JSON patch (i.e., a diff) given two JSON values.

Invariant

For two JSON values source and target, the following code yields always true:

source.patch(diff(source, target)) == target;\n
Example

The following code shows how a JSON patch is created as a diff for two JSON values.

#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

Output:

[\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
"},{"location":"features/json_pointer/","title":"JSON Pointer","text":""},{"location":"features/json_pointer/#introduction","title":"Introduction","text":"

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.

Consider the following JSON document

{\n    \"array\": [\"A\", \"B\", \"C\"],\n    \"nested\": {\n        \"one\": 1,\n        \"two\": 2,\n        \"three\": [true, false]\n    }\n}\n

Then every value inside the JSON document can be identified as follows:

JSON Pointer JSON value `` {\"array\":[\"A\",\"B\",\"C\"],\"nested\":{\"one\":1,\"two\":2,\"three\":[true,false]}} /array [\"A\",\"B\",\"C\"] /array/0 A /array/1 B /array/2 C /nested {\"one\":1,\"two\":2,\"three\":[true,false]} /nested/one 1 /nested/two 2 /nested/three [true,false] /nested/three/0 true /nested/three/1 false

Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\". See RFC 6901 for more information.

"},{"location":"features/json_pointer/#json-pointer-creation","title":"JSON Pointer creation","text":"

JSON Pointers can be created from a string:

json::json_pointer p = \"/nested/one\";\n

Furthermore, a user-defined string literal can be used to achieve the same result:

auto p = \"/nested/one\"_json_pointer;\n

The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.

"},{"location":"features/json_pointer/#value-access","title":"Value access","text":"

JSON Pointers can be used in the at, operator[], and value functions just like object keys or array indices.

// 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
"},{"location":"features/json_pointer/#flatten-unflatten","title":"Flatten / unflatten","text":"

The library implements a function flatten 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).

// 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

The resulting value j_flat is:

{\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

The reverse function, unflatten recreates the original value.

auto j_original = j_flat.unflatten();\n
"},{"location":"features/json_pointer/#see-also","title":"See also","text":""},{"location":"features/macros/","title":"Supported Macros","text":"

Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.

"},{"location":"features/macros/#json_assertx","title":"JSON_ASSERT(x)","text":"

This macro controls which code is executed for runtime assertions of the library.

See full documentation of JSON_ASSERT(x).

"},{"location":"features/macros/#json_catch_userexception","title":"JSON_CATCH_USER(exception)","text":"

This macro overrides catch calls inside the library.

See full documentation of JSON_CATCH_USER(exception).

"},{"location":"features/macros/#json_diagnostics","title":"JSON_DIAGNOSTICS","text":"

This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).

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.

The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which sets JSON_DIAGNOSTICS accordingly.

See full documentation of JSON_DIAGNOSTICS.

"},{"location":"features/macros/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20","text":"

The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view 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.

See full documentation of JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, and JSON_HAS_CPP_20.

"},{"location":"features/macros/#json_has_filesystem-json_has_experimental_filesystem","title":"JSON_HAS_FILESYSTEM, JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"

When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.

See full documentation of JSON_HAS_FILESYSTEM and JSON_HAS_EXPERIMENTAL_FILESYSTEM.

"},{"location":"features/macros/#json_noexception","title":"JSON_NOEXCEPTION","text":"

Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION.

See full documentation of JSON_NOEXCEPTION.

"},{"location":"features/macros/#json_disable_enum_serialization","title":"JSON_DISABLE_ENUM_SERIALIZATION","text":"

When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM.

See full documentation of JSON_DISABLE_ENUM_SERIALIZATION.

"},{"location":"features/macros/#json_no_io","title":"JSON_NO_IO","text":"

When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> 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)).

See full documentation of JSON_NO_IO.

"},{"location":"features/macros/#json_skip_library_version_check","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"

When defined, the library will not create a compiler warning when a different version of the library was already included.

See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK.

"},{"location":"features/macros/#json_skip_unsupported_compiler_check","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"

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.

See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK.

"},{"location":"features/macros/#json_throw_userexception","title":"JSON_THROW_USER(exception)","text":"

This macro overrides throw calls inside the library. The argument is the exception to be thrown.

See full documentation of JSON_THROW_USER(exception).

"},{"location":"features/macros/#json_try_user","title":"JSON_TRY_USER","text":"

This macro overrides try calls inside the library.

See full documentation of JSON_TRY_USER.

"},{"location":"features/macros/#json_use_implicit_conversions","title":"JSON_USE_IMPLICIT_CONVERSIONS","text":"

When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on.

See full documentation of JSON_USE_IMPLICIT_CONVERSIONS.

"},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)","text":"

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.

The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.

See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE.

"},{"location":"features/macros/#nlohmann_define_type_intrusive_with_defaulttype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.

See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT.

"},{"location":"features/macros/#nlohmann_define_type_intrusive_only_serializetype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE 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.

See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE.

"},{"location":"features/macros/#nlohmann_define_type_non_intrusivetype-member","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)","text":"

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.

The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members.

See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.

"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_with_defaulttype-member","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.

See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.

"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_only_serializetype-member","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE 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.

See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE.

"},{"location":"features/macros/#nlohmann_json_serialize_enumtype","title":"NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)","text":"

This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information.

See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM.

"},{"location":"features/macros/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"

These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.

See full documentation of NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH.

"},{"location":"features/merge_patch/","title":"JSON Merge Patch","text":"

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.

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.

Example

The following code shows how a JSON Merge Patch is applied to a JSON document.

#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

Output:

{\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
"},{"location":"features/namespace/","title":"nlohmann Namespace","text":"

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.

"},{"location":"features/namespace/#structure","title":"Structure","text":"

The complete default namespace name is derived as follows:

For example, the namespace name for version 3.11.2 with JSON_DIAGNOSTICS defined to 1 is:

nlohmann::json_abi_diag_v3_11_2\n
"},{"location":"features/namespace/#purpose","title":"Purpose","text":"

Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS. This is illustrated in the diagram below.

In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library 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.

"},{"location":"features/namespace/#limitations","title":"Limitations","text":"

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.

There is an exception when forward declarations are used (i.e., when including json_fwd.hpp) in which case the linker may complain about undefined references.

"},{"location":"features/namespace/#disabling-the-version-component","title":"Disabling the version component","text":"

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.

To do so, define NLOHMANN_JSON_NAMESPACE_NO_VERSION to 1.

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 NLOHMANN_JSON_NAMESPACE_NO_VERSION macro.

Use at your own risk

Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!

"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"

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 NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows:

#define NLOHMANN_JSON_NAMESPACE_BEGIN  namespace nlohmann {\n#define NLOHMANN_JSON_NAMESPACE_END    }\n

Use at your own risk

Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!

"},{"location":"features/namespace/#version-history","title":"Version history","text":""},{"location":"features/object_order/","title":"Object Order","text":"

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.

"},{"location":"features/object_order/#default-behavior-sort-keys","title":"Default behavior: sort keys","text":"

The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.

Example
#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

Output:

{\n  \"one\": 1,\n  \"three\": 3,\n  \"two\": 2\n}\n
"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","title":"Alternative behavior: preserve insertion order","text":"

If you do want to preserve the insertion order, you can try the type nlohmann::ordered_json.

Example
#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

Output:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n

Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map (integration) or nlohmann::fifo_map (integration).

"},{"location":"features/object_order/#notes-on-parsing","title":"Notes on parsing","text":"

Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n

Right way

The following code correctly calls the parse function from nlohmann::ordered_json:

std::ifstream i(\"input.json\");\nauto j = nlohmann::ordered_json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n

The output will be:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n
Wrong way

The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file.

std::ifstream i(\"input.json\");\nnlohmann::ordered_json j = nlohmann::json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n

The output will be:

{\n  \"one\": 1,\n  \"three\": 3\n  \"two\": 2,\n}\n
"},{"location":"features/binary_formats/","title":"Binary Formats","text":"

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

to efficiently encode JSON values to byte vectors and to decode such vectors.

"},{"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

See binary values for more information.

"},{"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 %

Sizes compared to minified JSON value.

"},{"location":"features/binary_formats/bjdata/","title":"BJData","text":"

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 - [u] - uint16, [m] - uint32, [M] - uint64 and [h] - float16 - 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.

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.

References

"},{"location":"features/binary_formats/bjdata/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to BJData types according to the BJData specification:

JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map {

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a BJData value.

Any BJData output created by to_bjdata can be successfully parsed by from_bjdata.

Size constraints

The following values can not be converted to a BJData value:

Unused BJData markers

The following markers are not used in the conversion:

NaN/infinity handling

If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.

Endianness

A breaking difference between BJData and UBJSON is the endianness of numerical values. In BJData, all numerical data types (integers UiuImlML and floating-point values hdD) 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.

Optimized formats

Optimized formats for containers are supported via two parameters of to_bjdata:

Note that use_size = true 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.

ND-array optimized format

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 uint8 integer array [[1,2],[3,4],[5,6]], stored as nested optimized array in UBJSON [ [$U#i2 1 2 [$U#i2 3 4 [$U#i2 5 6 ], can be further compressed in BJData to [$U#[$i#i2 2 3 1 2 3 4 5 6 or [$U#[i2 i3] 1 2 3 4 5 6.

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 from_bjdata. For example, the above 2-D uint8 array can be parsed and accessed as

{\n    \"_ArrayType_\": \"uint8\",\n    \"_ArraySize_\": [2,3],\n    \"_ArrayData_\": [1,2,3,4,5,6]\n}\n

Likewise, when a JSON object in the above form is serialzed using to_bjdata, it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated.

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.

Restrictions in optimized data types for arrays and objects

Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ 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 UiuImlMLhdDC. This also means other variable ([{SH) or zero-length types (TFN) can not be used in an optimized array or object in BJData.

Binary values

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.

Example
#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"features/binary_formats/bjdata/#deserialization","title":"Deserialization","text":"

The library maps BJData types to JSON value types as follows:

BJData type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) {

Complete mapping

The mapping is complete in the sense that any BJData value can be converted to a JSON value.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/bson/","title":"BSON","text":"

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.

References

"},{"location":"features/binary_formats/bson/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to BSON types:

JSON value type value/range BSON type marker null null null 0x0A boolean true, false 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

Incomplete mapping

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.

Example
#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

Output:

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
"},{"location":"features/binary_formats/bson/#deserialization","title":"Deserialization","text":"

The library maps BSON record types to JSON value types as follows:

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

Incomplete mapping

The mapping is incomplete. The unsupported mappings are indicated in the table above.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/cbor/","title":"CBOR","text":"

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.

References

"},{"location":"features/binary_formats/cbor/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049):

JSON value type value/range CBOR type first byte null null Null 0xF6 boolean true True 0xF5 boolean false 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

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.

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a CBOR value.

NaN/infinity handling

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 null.

Unused CBOR types

The following CBOR types are not used in the conversion:

Tagged items

Binary subtypes will be serialized as tagged items. See binary values for an example.

Example
#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

Output:

0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"features/binary_formats/cbor/#deserialization","title":"Deserialization","text":"

The library maps CBOR types to JSON value types as follows:

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 false 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB

Incomplete mapping

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:

Object keys

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.

Tagged items

Tagged items will throw a parse error by default. They can be ignored by passing cbor_tag_handler_t::ignore to function from_cbor. They can be stored by passing cbor_tag_handler_t::store to function from_cbor.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/messagepack/","title":"MessagePack","text":"

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.

References

"},{"location":"features/binary_formats/messagepack/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification:

JSON value type value/range MessagePack type first byte null null nil 0xC0 boolean true true 0xC3 boolean false 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

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value.

Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.

Size constraints

The following values can not be converted to a MessagePack value:

NaN/infinity handling

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 null.

Example
#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

Output:

0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"features/binary_formats/messagepack/#deserialization","title":"Deserialization","text":"

The library maps MessagePack types to JSON value types as follows:

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 null 0xC0 false false 0xC2 true true 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

Info

Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/ubjson/","title":"UBJSON","text":"

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.

References

"},{"location":"features/binary_formats/ubjson/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:

JSON value type value/range UBJSON type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map {

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.

Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson.

Size constraints

The following values can not be converted to a UBJSON value:

Unused UBJSON markers

The following markers are not used in the conversion:

NaN/infinity handling

If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.

Optimized formats

The optimized formats for containers are supported: Parameter use_size adds size information to the beginning of a container and removes the closing marker. Parameter use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The use_type parameter must only be used together with use_size = true.

Note that use_size = true 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.

Binary values

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.

Example
#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"features/binary_formats/ubjson/#deserialization","title":"Deserialization","text":"

The library maps UBJSON types to JSON value types as follows:

UBJSON type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) {

Complete mapping

The mapping is complete in the sense that any UBJSON value can be converted to a JSON value.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/element_access/","title":"Element Access","text":"

There are many ways elements in a JSON value can be accessed:

"},{"location":"features/element_access/checked_access/","title":"Checked access: at","text":""},{"location":"features/element_access/checked_access/#overview","title":"Overview","text":"

The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise.

Read access

Consider the following JSON value:

{\n    \"name\": \"Mary Smith\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

Assume the value is parsed to a json variable j.

expression value j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j.at(\"name\") \"Mary Smith\" j.at(\"age\") 42 j.at(\"hobbies\") [\"hiking\", \"reading\"] j.at(\"hobbies\").at(0) \"hiking\" j.at(\"hobbies\").at(1) \"reading\"

The return value is a reference, so it can be modified by the original value.

Write access
j.at(\"name\") = \"John Smith\";\n

This code produces the following JSON value:

{\n    \"name\": \"John Smith\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

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.

Accessing via invalid index or missing key
j.at(\"hobbies\").at(3) = \"cooking\";\n

This code produces the following exception:

[json.exception.out_of_range.401] array index 3 is out of range\n

When you extended diagnostic messages are enabled by defining JSON_DIAGNOSTICS, the exception further gives information where the key or index is missing or out of range.

[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n
"},{"location":"features/element_access/checked_access/#notes","title":"Notes","text":"

Exceptions

"},{"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 basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown access to invalid array index basic_json::out_of_range exception is thrown basic_json::out_of_range 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":"

In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present.

Example

Consider the following JSON value:

{\n    \"logOutput\": \"result.log\",\n    \"append\": true\n}\n

Assume the value is parsed to a json variable j.

expression value j {\"logOutput\": \"result.log\", \"append\": true} j.value(\"logOutput\", \"logfile.log\") \"result.log\" j.value(\"append\", true) true j.value(\"append\", false) true j.value(\"logLevel\", \"verbose\") \"verbose\""},{"location":"features/element_access/default_value/#note","title":"Note","text":"

Exceptions

"},{"location":"features/element_access/unchecked_access/","title":"Unchecked access: operator[]","text":""},{"location":"features/element_access/unchecked_access/#overview","title":"Overview","text":"

Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std::map and a std::vector, respectively.

Read access

Consider the following JSON value:

{\n    \"name\": \"Mary Smith\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

Assume the value is parsed to a json variable j.

expression value j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j[\"name\"] \"Mary Smith\" j[\"age\"] 42 j[\"hobbies\"] [\"hiking\", \"reading\"] j[\"hobbies\"][0] \"hiking\" j[\"hobbies\"][1] \"reading\"

The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten.

Write access
j[\"name\"] = \"John Smith\";\nj[\"maidenName\"] = \"Jones\";\n

This code produces the following JSON value:

{\n    \"name\": \"John Smith\",\n    \"maidenName\": \"Jones\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

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 null.

Filling up arrays with null values
j[\"hobbies\"][0] = \"running\";\nj[\"hobbies\"][3] = \"cooking\";\n

This code produces the following JSON value:

{\n    \"name\": \"John Smith\",\n    \"maidenName\": \"Jones\",\n    \"age\": 42,\n    \"hobbies\": [\"running\", \"reading\", null, \"cooking\"]\n}\n
"},{"location":"features/element_access/unchecked_access/#notes","title":"Notes","text":"

Design rationale

The library behaves differently to std::vector and std::map:

The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.

Info

The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.

Danger

Exceptions

operator[] can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown.

"},{"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 null value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted null value is returned; any index between previous maximal index and passed index are filled with null undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"

Note

This page is under construction.

"},{"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":"

See parsing and exceptions.

"},{"location":"features/parsing/json_lines/","title":"JSON Lines","text":"

The JSON Lines format is a text format of newline-delimited JSON. In particular:

  1. The input must be UTF-8 encoded.
  2. Every line must be a valid JSON value.
  3. The line separator must be \\n. As \\r is silently ignored, \\r\\n is also supported.
  4. The final character may be \\n, but is not required to be one.

JSON Text example

{\"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

JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used:

Example: Parse JSON Text input line by line

The example below demonstrates how JSON Lines can be processed.

#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

Output:

{\"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

Note

Using operator>> like

json j;\nwhile (input >> j)\n{\n    std::cout << j << std::endl;\n}\n

with a JSON Lines input does not work, because the parser will try to parse one value after the last one.

"},{"location":"features/parsing/parse_exceptions/","title":"Parsing and Exceptions","text":"

When the input is not valid JSON, an exception of type parse_error 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 try/catch block, like

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

In case exceptions are undesired or not supported by the environment, there are different ways to proceed:

"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"

The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs (true, default) or whether a discarded value should be returned (false).

json j = json::parse(my_input, nullptr, false);\nif (j.is_discarded())\n{\n    std::cerr << \"parse error\" << std::endl;\n}\n

Note there is no diagnostic information available in this scenario.

"},{"location":"features/parsing/parse_exceptions/#use-accept-function","title":"Use accept() function","text":"

Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON.

if (!json::accept(my_input))\n{\n    std::cerr << \"parse error\" << std::endl;\n}\n

Again, there is no diagnostic information available.

"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","title":"User-defined SAX interface","text":"

Finally, you can implement the SAX interface and decide what should happen in case of a parse error.

This function has the following interface:

bool parse_error(std::size_t position,\n                 const std::string& last_token,\n                 const json::exception& ex);\n

The return value indicates whether the parsing should continue, so the function should usually return false.

Example
#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

Output:

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
"},{"location":"features/parsing/parser_callbacks/","title":"Parser Callbacks","text":""},{"location":"features/parsing/parser_callbacks/#overview","title":"Overview","text":"

With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.

The type of the callback function is:

template<typename BasicJsonType>\nusing parser_callback_t =\n    std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n
"},{"location":"features/parsing/parser_callbacks/#callback-event-types","title":"Callback event types","text":"

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 depth, event, and parsed.

parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example

When parsing the following JSON text,

{\n    \"name\": \"Berlin\",\n    \"location\": [\n        52.519444,\n        13.406667\n    ]\n}\n

these calls are made to the callback function:

event depth parsed object_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [52.519444,13.406667] object_end 0 {\"location\":[52.519444,13.406667],\"name\":\"Berlin\"}"},{"location":"features/parsing/parser_callbacks/#return-value","title":"Return value","text":"

Discarding a value (i.e., returning false) has different effects depending on the context in which the function was called:

Example

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
"},{"location":"features/parsing/sax_interface/","title":"SAX Interface","text":"

The library uses a SAX-like interface with the following functions:

// 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

The return value of each function determines whether parsing should proceed.

To implement your own SAX handler, proceed as follows:

  1. Implement the SAX interface in a class. You can use class nlohmann::json_sax<json> as base class, but you can also use any class where the functions described above are implemented and public.
  2. Create an object of your SAX interface class, e.g. my_sax.
  3. Call bool json::sax_parse(input, &my_sax); 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.

Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return json 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 parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file json_sax.hpp.

"},{"location":"features/parsing/sax_interface/#see-also","title":"See also","text":""},{"location":"features/types/","title":"Types","text":"

This page gives an overview how JSON values are stored and how this can be configured.

"},{"location":"features/types/#overview","title":"Overview","text":"

By default, JSON values are stored as follows:

JSON type C++ type object std::map<std::string, basic_json> array std::vector<basic_json> null std::nullptr_t string std::string boolean bool number std::int64_t, std::uint64_t, and double

Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.

"},{"location":"features/types/#storage","title":"Storage","text":""},{"location":"features/types/#template-arguments","title":"Template arguments","text":"

The data types to store a JSON value are derived from the template arguments passed to class basic_json:

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

Type json is an alias for basic_json<> and uses the default types.

From the template arguments, the following types are derived:

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
"},{"location":"features/types/#objects","title":"Objects","text":"

RFC 8259 describes JSON objects as follows:

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.

"},{"location":"features/types/#default-type","title":"Default type","text":"

With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:

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
"},{"location":"features/types/#behavior","title":"Behavior","text":"

The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:

"},{"location":"features/types/#key-order","title":"Key order","text":"

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 std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.

"},{"location":"features/types/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON object.

"},{"location":"features/types/#storage_1","title":"Storage","text":"

Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.

"},{"location":"features/types/#arrays","title":"Arrays","text":"

RFC 8259 describes JSON arrays as follows:

An array is an ordered sequence of zero or more values.

"},{"location":"features/types/#default-type_1","title":"Default type","text":"

With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:

std::vector<\n  basic_json, // value_type\n  std::allocator<basic_json> // allocator_type\n>\n
"},{"location":"features/types/#limits_1","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON array.

"},{"location":"features/types/#storage_2","title":"Storage","text":"

Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.

"},{"location":"features/types/#strings","title":"Strings","text":"

RFC 8259 describes JSON strings as follows:

A string is a sequence of zero or more Unicode characters.

Unicode values are split by the JSON class into byte-sized characters during deserialization.

"},{"location":"features/types/#default-type_2","title":"Default type","text":"

With the default values for StringType (std::string), the default value for string_t is std::string.

"},{"location":"features/types/#encoding","title":"Encoding","text":"

Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.

"},{"location":"features/types/#string-comparison","title":"String comparison","text":"

RFC 8259 states:

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 \"a\\\\b\" and \"a\\u005Cb\" are not equal.

This implementation is interoperable as it does compare strings code unit by code unit.

"},{"location":"features/types/#storage_3","title":"Storage","text":"

String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.

"},{"location":"features/types/#booleans","title":"Booleans","text":"

RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.

"},{"location":"features/types/#default-type_3","title":"Default type","text":"

With the default values for BooleanType (bool), the default value for boolean_t is bool.

"},{"location":"features/types/#storage_4","title":"Storage","text":"

Boolean values are stored directly inside a basic_json type.

"},{"location":"features/types/#numbers","title":"Numbers","text":"

See the number handling article for a detailed discussion on how numbers are handled by this library.

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t, and number_float_t are used.

"},{"location":"features/types/#default-types","title":"Default types","text":"

With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t. With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t. With the default values for NumberFloatType (double), the default value for number_float_t is double.

"},{"location":"features/types/#default-behavior","title":"Default behavior","text":""},{"location":"features/types/#limits_2","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (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 number_unsigned_t or number_float_t.

When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. 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 number_integer_t or number_float_t.

RFC 8259 further states:

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.

As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.

RFC 8259 states:

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.

This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.

"},{"location":"features/types/#storage_5","title":"Storage","text":"

Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.

"},{"location":"features/types/number_handling/","title":"Number Handling","text":"

This document describes how the library is handling numbers.

"},{"location":"features/types/number_handling/#background","title":"Background","text":"

This section briefly summarizes how the JSON specification describes how numbers should be handled.

"},{"location":"features/types/number_handling/#json-number-syntax","title":"JSON number syntax","text":"

JSON defines the syntax of numbers as follows:

RFC 8259, Section 6

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.

A fraction part is a decimal point followed by one or more digits.

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.

The following railroad diagram from json.org visualizes the number syntax:

"},{"location":"features/types/number_handling/#number-interoperability","title":"Number interoperability","text":"

On number interoperability, the following remarks are made:

RFC 8259, Section 6

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.

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.

"},{"location":"features/types/number_handling/#library-implementation","title":"Library implementation","text":"

This section describes how the above number specification is implemented by this library.

"},{"location":"features/types/number_handling/#number-storage","title":"Number storage","text":"

In the default json type, numbers are stored as std::uint64_t, std::int64_t, and double, respectively. Thereby, std::uint64_t and std::int64_t 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 double.

Notes

Examples

"},{"location":"features/types/number_handling/#number-limits","title":"Number limits","text":"

Interoperability

"},{"location":"features/types/number_handling/#zeros","title":"Zeros","text":"

The JSON number grammar allows for different ways to express zero, and this library will store zeros differently:

Literal Stored value and type Serialization 0 std::uint64_t(0) 0 -0 std::int64_t(0) 0 0.0 double(0.0) 0.0 -0.0 double(-0.0) -0.0 0E0 double(0.0) 0.0 -0E0 double(-0.0) -0.0

That is, -0 is stored as a signed integer, but the serialization does not reproduce the -.

"},{"location":"features/types/number_handling/#number-serialization","title":"Number serialization","text":"

Notes regarding precision of floating-point numbers

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:

All examples here can be reproduced by passing the original double value to

std::printf(\"%.*g\\n\", std::numeric_limits<double>::max_digits10, double_value);\n
"},{"location":"features/types/number_handling/#nan-handling","title":"NaN handling","text":"

NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded:

RFC 8259, Section 6

Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.

That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment.

This library serializes NaN values as null. This corresponds to the behavior of JavaScript's JSON.stringify function.

Example

The following example shows how a NaN value is stored in a json value.

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

output:

val=nan\nj=null\nval=nan\n
"},{"location":"features/types/number_handling/#number-comparison","title":"Number comparison","text":"

Floating-point inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default.

Alternative comparison functions

To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance

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
Or you can self-define an operator equal function like this:

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

(see #703 for more information.)

Note

NaN values never compare equal to themselves or to other NaN values. See #514.

"},{"location":"features/types/number_handling/#number-conversion","title":"Number conversion","text":"

Just like the C++ language itself, the get family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising.

Unconditional number conversions

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

Note the last line with throw a json.exception.type_error.302 exception if jd is not a numerical type, for instance a string.

The rationale is twofold:

  1. JSON does not define a number type or precision (see above).
  2. C++ also allows to silently convert between number types.

Conditional number conversion

The code above can be solved by explicitly checking the nature of the value with members such as is_number_integer() or is_number_unsigned():

// 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

Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.

(Example taken from #777.)

"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"

As the example in Number conversion shows, there are different functions to determine the type of the stored number:

function unsigned integer signed integer floating-point string is_number() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"

The number types can be changed with template parameters.

position number type default type possible values 5 signed integers std::int64_t std::int32_t, std::int16_t, etc. 6 unsigned integers std::uint64_t std::uint32_t, std::uint16_t, etc. 7 floating-point double float, long double

Constraints on number types

Example

A basic_json type that uses long double as floating-point type.

using json_ld = nlohmann::basic_json<std::map, std::vector, std::string, bool,\n                                     std::int64_t, std::uint64_t, long double>;\n

Note values should then be parsed with json_ld::parse rather than json::parse as the latter would parse floating-point values to double before then converting them to long double.

"},{"location":"home/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"home/code_of_conduct/#our-pledge","title":"Our Pledge","text":"

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.

"},{"location":"home/code_of_conduct/#our-standards","title":"Our Standards","text":"

Examples of behavior that contributes to creating a positive environment include:

Examples of unacceptable behavior by participants include:

"},{"location":"home/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"

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.

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.

"},{"location":"home/code_of_conduct/#scope","title":"Scope","text":"

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.

"},{"location":"home/code_of_conduct/#enforcement","title":"Enforcement","text":"

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.

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.

"},{"location":"home/code_of_conduct/#attribution","title":"Attribution","text":"

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4

"},{"location":"home/design_goals/","title":"Design goals","text":"

There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:

Other aspects were not so important to us:

See the contribution guidelines for more information.

"},{"location":"home/exceptions/","title":"Exceptions","text":""},{"location":"home/exceptions/#overview","title":"Overview","text":""},{"location":"home/exceptions/#base-type","title":"Base type","text":"

All exceptions inherit from class json::exception (which in turn inherits from std::exception). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions.

"},{"location":"home/exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"

Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION. In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw), JSON_TRY_USER (overriding try), and JSON_CATCH_USER (overriding catch).

Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.

Example

The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.

#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

Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.

See documentation of JSON_TRY_USER, JSON_CATCH_USER and JSON_THROW_USER for more information.

"},{"location":"home/exceptions/#extended-diagnostic-messages","title":"Extended diagnostic messages","text":"

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.

Example
#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

Output:

[json.exception.type_error.302] type must be number, but is string\n

This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.

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.

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 JSON_DIAGNOSTICS to 1 before including json.hpp.

Example
#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

Output:

[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n

Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.

See documentation of JSON_DIAGNOSTICS for more information.

"},{"location":"home/exceptions/#parse-errors","title":"Parse errors","text":"

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.

Exceptions have ids 1xx.

Byte index

Member byte holds the byte index of the last read character in the input file.

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).

Example

The following code shows how a parse_error exception can be caught.

#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

Output:

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
"},{"location":"home/exceptions/#jsonexceptionparse_error101","title":"json.exception.parse_error.101","text":"

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 byte indicates the error position.

Example message

Input ended prematurely:

[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal\n

No input:

[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

Control character was not escaped:

[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

String was not closed:

[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

Invalid number format:

[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

\\u was not be followed by four hex digits:

[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

Invalid UTF-8 surrogate pair:

[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

Invalid UTF-8 byte:

[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

Tip

"},{"location":"home/exceptions/#jsonexceptionparse_error102","title":"json.exception.parse_error.102","text":"

JSON uses the \\uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \\uxxxx entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.

Example message

parse error at 14: missing or wrong low surrogate\n

Note

This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.

"},{"location":"home/exceptions/#jsonexceptionparse_error103","title":"json.exception.parse_error.103","text":"

Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.

Example message

parse error: code points above 0x10FFFF are invalid\n

Note

This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.

"},{"location":"home/exceptions/#jsonexceptionparse_error104","title":"json.exception.parse_error.104","text":"

RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.

Example message

[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\n
"},{"location":"home/exceptions/#jsonexceptionparse_error105","title":"json.exception.parse_error.105","text":"

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.

Example message

[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'\n
[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'\n
[json.exception.parse_error.105] parse error: operation value 'foo' is invalid\n

"},{"location":"home/exceptions/#jsonexceptionparse_error106","title":"json.exception.parse_error.106","text":"

An array index in a JSON Pointer (RFC 6901) may be 0 or any number without a leading 0.

Example message

[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n
"},{"location":"home/exceptions/#jsonexceptionparse_error107","title":"json.exception.parse_error.107","text":"

A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character.

Example message

[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n
"},{"location":"home/exceptions/#jsonexceptionparse_error108","title":"json.exception.parse_error.108","text":"

In a JSON Pointer, only ~0 and ~1 are valid escape sequences.

Example message

[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n
"},{"location":"home/exceptions/#jsonexceptionparse_error109","title":"json.exception.parse_error.109","text":"

A JSON Pointer array index must be a number.

Example messages

[json.exception.parse_error.109] parse error: array index 'one' is not a number\n
[json.exception.parse_error.109] parse error: array index '+1' is not a number\n

"},{"location":"home/exceptions/#jsonexceptionparse_error110","title":"json.exception.parse_error.110","text":"

When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.

Example message

[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input\n
[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A\n

"},{"location":"home/exceptions/#jsonexceptionparse_error112","title":"json.exception.parse_error.112","text":"

An unexpected byte was read in a binary format or length information is invalid (BSON).

Example messages

[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C\n
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1\n
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02\n
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02\n
[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
[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

"},{"location":"home/exceptions/#jsonexceptionparse_error113","title":"json.exception.parse_error.113","text":"

While parsing a map key, a value that is not a string has been read.

Example messages

[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
[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
[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

"},{"location":"home/exceptions/#jsonexceptionparse_error114","title":"json.exception.parse_error.114","text":"

The parsing of the corresponding BSON record type is not implemented (yet).

Example message

[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF\n
"},{"location":"home/exceptions/#jsonexceptionparse_error115","title":"json.exception.parse_error.115","text":"

A UBJSON high-precision number could not be parsed.

Example message

[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A\n
"},{"location":"home/exceptions/#iterator-errors","title":"Iterator errors","text":"

This exception is thrown if iterators passed to a library function do not match the expected semantics.

Exceptions have ids 2xx.

Example

The following code shows how an invalid_iterator exception can be caught.

#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

Output:

message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","title":"json.exception.invalid_iterator.201","text":"

The iterators passed to constructor basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.

Example message

[json.exception.invalid_iterator.201] iterators are not compatible\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","title":"json.exception.invalid_iterator.202","text":"

In the erase or insert function, the passed iterator pos 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.

Example messages

[json.exception.invalid_iterator.202] iterator does not fit current value\n
[json.exception.invalid_iterator.202] iterators first and last must point to objects\n

"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","title":"json.exception.invalid_iterator.203","text":"

Either iterator passed to function erase(IteratorType first, IteratorType last) 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.

Example message

[json.exception.invalid_iterator.203] iterators do not fit current value\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","title":"json.exception.invalid_iterator.204","text":"

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 (begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid.

Example message

[json.exception.invalid_iterator.204] iterators out of range\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","title":"json.exception.invalid_iterator.205","text":"

When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.

Example message

[json.exception.invalid_iterator.205] iterator out of range\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","title":"json.exception.invalid_iterator.206","text":"

The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.

Example message

[json.exception.invalid_iterator.206] cannot construct with iterators from null\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","title":"json.exception.invalid_iterator.207","text":"

The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.

Example message

[json.exception.invalid_iterator.207] cannot use key() for non-object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","title":"json.exception.invalid_iterator.208","text":"

The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.

Example message

[json.exception.invalid_iterator.208] cannot use operator[] for object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","title":"json.exception.invalid_iterator.209","text":"

The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.

Example message

[json.exception.invalid_iterator.209] cannot use offsets with object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","title":"json.exception.invalid_iterator.210","text":"

The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.

Example message

[json.exception.invalid_iterator.210] iterators do not fit\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","title":"json.exception.invalid_iterator.211","text":"

The iterator range passed to the insert function must not be a subrange of the container to insert to.

Example message

[json.exception.invalid_iterator.211] passed iterators may not belong to container\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","title":"json.exception.invalid_iterator.212","text":"

When two iterators are compared, they must belong to the same container.

Example message

[json.exception.invalid_iterator.212] cannot compare iterators of different containers\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","title":"json.exception.invalid_iterator.213","text":"

The order of object iterators cannot be compared, because JSON objects are unordered.

Example message

[json.exception.invalid_iterator.213] cannot compare order of object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","title":"json.exception.invalid_iterator.214","text":"

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 begin().

Example message

[json.exception.invalid_iterator.214] cannot get value\n
"},{"location":"home/exceptions/#type-errors","title":"Type errors","text":"

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.

Exceptions have ids 3xx.

Example

The following code shows how a type_error exception can be caught.

#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

Output:

message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n
"},{"location":"home/exceptions/#jsonexceptiontype_error301","title":"json.exception.type_error.301","text":"

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.

Example message

[json.exception.type_error.301] cannot create object from initializer list\n
"},{"location":"home/exceptions/#jsonexceptiontype_error302","title":"json.exception.type_error.302","text":"

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.

Example messages

[json.exception.type_error.302] type must be object, but is null\n
[json.exception.type_error.302] type must be string, but is object\n

"},{"location":"home/exceptions/#jsonexceptiontype_error303","title":"json.exception.type_error.303","text":"

To retrieve a reference to a value stored in a basic_json object with get_ref, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t &.

Example messages

[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object\n
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"\n

"},{"location":"home/exceptions/#jsonexceptiontype_error304","title":"json.exception.type_error.304","text":"

The at() member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.304] cannot use at() with string\n
[json.exception.type_error.304] cannot use at() with number\n

"},{"location":"home/exceptions/#jsonexceptiontype_error305","title":"json.exception.type_error.305","text":"

The operator[] member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.305] cannot use operator[] with a string argument with array\n
[json.exception.type_error.305] cannot use operator[] with a numeric argument with object\n

"},{"location":"home/exceptions/#jsonexceptiontype_error306","title":"json.exception.type_error.306","text":"

The value() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.306] cannot use value() with number\n
"},{"location":"home/exceptions/#jsonexceptiontype_error307","title":"json.exception.type_error.307","text":"

The erase() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.307] cannot use erase() with string\n
"},{"location":"home/exceptions/#jsonexceptiontype_error308","title":"json.exception.type_error.308","text":"

The push_back() and operator+= member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.308] cannot use push_back() with string\n
"},{"location":"home/exceptions/#jsonexceptiontype_error309","title":"json.exception.type_error.309","text":"

The insert() member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.309] cannot use insert() with array\n
[json.exception.type_error.309] cannot use insert() with number\n

"},{"location":"home/exceptions/#jsonexceptiontype_error310","title":"json.exception.type_error.310","text":"

The swap() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.310] cannot use swap() with number\n
"},{"location":"home/exceptions/#jsonexceptiontype_error311","title":"json.exception.type_error.311","text":"

The emplace() and emplace_back() member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.311] cannot use emplace() with number\n
[json.exception.type_error.311] cannot use emplace_back() with number\n

"},{"location":"home/exceptions/#jsonexceptiontype_error312","title":"json.exception.type_error.312","text":"

The update() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.312] cannot use update() with array\n
"},{"location":"home/exceptions/#jsonexceptiontype_error313","title":"json.exception.type_error.313","text":"

The unflatten 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.

Example message

[json.exception.type_error.313] invalid value to unflatten\n
"},{"location":"home/exceptions/#jsonexceptiontype_error314","title":"json.exception.type_error.314","text":"

The unflatten function only works for an object whose keys are JSON Pointers.

Example message

Calling unflatten() on an array [1,2,3]:

[json.exception.type_error.314] only objects can be unflattened\n
"},{"location":"home/exceptions/#jsonexceptiontype_error315","title":"json.exception.type_error.315","text":"

The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive.

Example message

Calling unflatten() on an object {\"/1\", [1,2,3]}:

[json.exception.type_error.315] values in object must be primitive\n
"},{"location":"home/exceptions/#jsonexceptiontype_error316","title":"json.exception.type_error.316","text":"

The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded.

Example message

Calling dump() on a JSON value containing an ISO 8859-1 encoded string:

[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F\n

Tip

"},{"location":"home/exceptions/#jsonexceptiontype_error317","title":"json.exception.type_error.317","text":"

The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON)

Example messages

Serializing null to BSON:

[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n
Serializing [1,2,3] to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n

Tip

Encapsulate the JSON value in an object. That is, instead of serializing true, serialize {\"value\": true}

"},{"location":"home/exceptions/#out-of-range","title":"Out of range","text":"

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.

Exceptions have ids 4xx.

Example

The following code shows how an out_of_range exception can be caught.

#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

Output:

message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range401","title":"json.exception.out_of_range.401","text":"

The provided array index i is larger than size-1.

Example message

array index 3 is out of range\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range402","title":"json.exception.out_of_range.402","text":"

The special array index - 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.

Example message

array index '-' (3) is out of range\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range403","title":"json.exception.out_of_range.403","text":"

The provided key was not found in the JSON object.

Example message

key 'foo' not found\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range404","title":"json.exception.out_of_range.404","text":"

A reference token in a JSON Pointer could not be resolved.

Example message

unresolved reference token 'foo'\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range405","title":"json.exception.out_of_range.405","text":"

The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.

Example message

JSON pointer has no parent\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range406","title":"json.exception.out_of_range.406","text":"

A parsed number could not be stored as without changing it to NaN or INF.

Example message

number overflow parsing '10E1000'\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range407","title":"json.exception.out_of_range.407","text":"

UBJSON and BSON only support integer numbers up to 9223372036854775807.

Example message

number overflow serializing '9223372036854775808'\n

Note

Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.

"},{"location":"home/exceptions/#jsonexceptionout_of_range408","title":"json.exception.out_of_range.408","text":"

The size (following #) of an UBJSON array or object exceeds the maximal capacity.

Example message

excessive array size: 8658170730974374167\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range409","title":"json.exception.out_of_range.409","text":"

Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.

Example message

BSON key cannot contain code point U+0000 (at byte 2)\n
"},{"location":"home/exceptions/#further-exceptions","title":"Further exceptions","text":"

This exception is thrown in case of errors that cannot be classified with the other exception types.

Exceptions have ids 5xx.

Example

The following code shows how an other_error exception can be caught.

#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

Output:

message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n
"},{"location":"home/exceptions/#jsonexceptionother_error501","title":"json.exception.other_error.501","text":"

A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.

Example message

Executing {\"op\":\"test\", \"path\":\"/baz\", \"value\":\"bar\"} on {\"baz\": \"qux\"}:

[json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}\n
"},{"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":"

Question

Why does

json j{true};\n

and

json j(true);\n

yield different results ([true] vs. true)?

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

json array = {1, 2, 3, 4};\n

for arrays and

json object = {{\"one\", 1}, {\"two\", 2}}; \n

for objects.

Tip

To avoid any confusion and ensure portable code, do not use brace initialization with the types basic_json, json, or ordered_json unless you want to create an object or array as shown in the examples above.

"},{"location":"home/faq/#limitations","title":"Limitations","text":""},{"location":"home/faq/#relaxed-parsing","title":"Relaxed parsing","text":"

Question

Can you add an option to ignore trailing commas?

This library does not support any feature which would jeopardize interoperability.

"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","title":"Parse errors reading non-ASCII characters","text":"

Questions

The library supports Unicode input as follows:

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.

"},{"location":"home/faq/#wide-string-handling","title":"Wide string handling","text":"

Question

Why are wide strings (e.g., std::wstring) dumped as arrays of numbers?

As described above, the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding.

Example

#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

The result is:

{\n  \"encoded\": \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\",\n  \"original\": [36554, 66, 49, 50, 51, 52, 32, 12371, 12435, 12395, 12385, 12399]\n}\n
"},{"location":"home/faq/#exceptions","title":"Exceptions","text":""},{"location":"home/faq/#parsing-without-exceptions","title":"Parsing without exceptions","text":"

Question

Is it possible to indicate a parse error without throwing an exception?

Yes, see Parsing and exceptions.

"},{"location":"home/faq/#key-name-in-exceptions","title":"Key name in exceptions","text":"

Question

Can I get the key of the object item that caused an exception?

Yes, you can. Please define the symbol JSON_DIAGNOSTICS to get extended diagnostics messages.

"},{"location":"home/faq/#serialization-issues","title":"Serialization issues","text":""},{"location":"home/faq/#number-precision","title":"Number precision","text":"

Question

The library uses std::numeric_limits<number_float_t>::digits10 (15 for IEEE doubles) 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.

cppreference.com

The value of std::numeric_limits<T>::digits10 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.

Tip

The website https://float.exposed gives a good insight into the internal storage of floating-point numbers.

See this section on the library's number handling for more information.

"},{"location":"home/faq/#compilation-issues","title":"Compilation issues","text":""},{"location":"home/faq/#android-sdk","title":"Android SDK","text":"

Question

Why does the code not compile with Android SDK?

Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.

APP_STL := c++_shared\nNDK_TOOLCHAIN_VERSION := clang3.6\nAPP_CPPFLAGS += -frtti -fexceptions\n

The code compiles successfully with Android NDK, Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.

"},{"location":"home/faq/#missing-stl-function","title":"Missing STL function","text":"

Questions

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 APP_STL := gnustl_static, please refer to this discussion.

"},{"location":"home/license/","title":"License","text":"

The class is licensed under the MIT License:

Copyright \u00a9 2013-2022 Niels Lohmann

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.

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

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

The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0.

"},{"location":"home/releases/","title":"Releases","text":""},{"location":"home/releases/#v373","title":"v3.7.3","text":"

Files

Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)

"},{"location":"home/releases/#summary","title":"Summary","text":"

This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes","title":"Bug Fixes","text":""},{"location":"home/releases/#deprecated-functions","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v372","title":"v3.7.2","text":"

Files

Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)

"},{"location":"home/releases/#summary_1","title":"Summary","text":"

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.

"},{"location":"home/releases/#bug-fixes_1","title":"Bug Fixes","text":""},{"location":"home/releases/#further-changes","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_1","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v371","title":"v3.7.1","text":"

Files

Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)

"},{"location":"home/releases/#summary_2","title":"Summary","text":"

This release fixes several small bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_2","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements","title":"Improvements","text":""},{"location":"home/releases/#further-changes_1","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_2","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v370","title":"v3.7.0","text":"

Files

Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)

"},{"location":"home/releases/#summary_3","title":"Summary","text":"

This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.

"},{"location":"home/releases/#new-features","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_3","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_1","title":"Improvements","text":""},{"location":"home/releases/#further-changes_2","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_3","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v361","title":"v3.6.1","text":"

Files

Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)

"},{"location":"home/releases/#summary_4","title":"Summary","text":"

This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_4","title":"Bug Fixes","text":""},{"location":"home/releases/#further-changes_3","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_4","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v360","title":"v3.6.0","text":"

Files

Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip)

\u2139\ufe0f This release introduced a regression. Please update to version 3.6.1!

"},{"location":"home/releases/#summary_5","title":"Summary","text":"

This release adds some convenience functions for JSON Pointers, introduces a contains 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.

"},{"location":"home/releases/#new-features_1","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_5","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_2","title":"Improvements","text":""},{"location":"home/releases/#further-changes_4","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_5","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v350","title":"v3.5.0","text":"

Files

Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)

"},{"location":"home/releases/#summary_6","title":"Summary","text":"

This release introduces the support for structured bindings and reading from FILE*. Besides, a few bugs have been fixed. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_2","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_6","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_3","title":"Improvements","text":""},{"location":"home/releases/#further-changes_5","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_6","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v340","title":"v3.4.0","text":"

Files

Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)

"},{"location":"home/releases/#summary_7","title":"Summary","text":"

This release introduces three new features:

Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_3","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_7","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_4","title":"Improvements","text":""},{"location":"home/releases/#further-changes_6","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_7","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v330","title":"v3.3.0","text":"

Files

Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)

"},{"location":"home/releases/#summary_8","title":"Summary","text":"

This release adds support for GCC 4.8. Furthermore, it adds a function get_to to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented.

Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_4","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_8","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_5","title":"Improvements","text":""},{"location":"home/releases/#further-changes_7","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_8","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v320","title":"v3.2.0","text":"

Files

Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)

"},{"location":"home/releases/#summary_9","title":"Summary","text":"

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 parse, accept, from_cbor, from_msgpack, and from_ubjson 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 std::vector<bool> to track the hierarchy of structured values) which allows to process nested input more efficiently.

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.

This release further fixes several bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_5","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_9","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_6","title":"Improvements","text":""},{"location":"home/releases/#further-changes_8","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_9","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v312","title":"v3.1.2","text":"

Files

Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)

"},{"location":"home/releases/#summary_10","title":"Summary","text":"

This release fixes several bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_10","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_7","title":"Improvements","text":""},{"location":"home/releases/#further-changes_9","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_10","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v311","title":"v3.1.1","text":"

Files

Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)

"},{"location":"home/releases/#summary_11","title":"Summary","text":"

This release fixes several bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_11","title":"Bug Fixes","text":""},{"location":"home/releases/#further-changes_10","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_11","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v310","title":"v3.1.0","text":"

Files

Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)

"},{"location":"home/releases/#summary_12","title":"Summary","text":"

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.

"},{"location":"home/releases/#new-features_6","title":"New features","text":""},{"location":"home/releases/#improvements_8","title":"Improvements","text":""},{"location":"home/releases/#reorganization","title":"Reorganization","text":""},{"location":"home/releases/#further-changes_11","title":"Further changes","text":""},{"location":"home/releases/#deprecated-functions_12","title":"Deprecated functions","text":"

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):

Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.

"},{"location":"home/releases/#v301","title":"v3.0.1","text":"

Files

Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c

"},{"location":"home/releases/#summary_13","title":"Summary","text":"

This release fixes small issues in the implementation of JSON Pointer and JSON Patch. All changes are backward-compatible.

"},{"location":"home/releases/#changes","title":"Changes","text":""},{"location":"home/releases/#deprecated-functions_13","title":"Deprecated functions","text":"

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):

Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.

"},{"location":"home/releases/#v300","title":"v3.0.0","text":"

Files

Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462

"},{"location":"home/releases/#summary_14","title":"Summary","text":"

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.

"},{"location":"home/releases/#breaking-changes","title":"Breaking changes","text":"

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.

"},{"location":"home/releases/#deprecated-functions_14","title":"Deprecated functions","text":"

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):

Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.

"},{"location":"home/releases/#new-features_7","title":"New features","text":"

With all this breaking and deprecation out of the way, let's talk about features!

"},{"location":"home/releases/#further-changes_12","title":"Further changes","text":"

Furthermore, there have been a lot of changes under the hood:

"},{"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":"

There are five different exceptions inheriting from json::exception:

To support these exception, the try/catch blocks of your code need to be adjusted:

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":""},{"location":"home/releases/#removal-of-deprecated-functions","title":"Removal of deprecated functions","text":"

Function explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) should be replaced by the parse function: Let ss be a stream and cb be a parse callback function.

Old code:

json j(ss, cb);\n

New code:

json j = json::parse(ss, cb);\n

If no callback function is used, also the following code works:

json j;\nj << ss;\n

or

json j;\nss >> j;\n
"},{"location":"home/releases/#v211","title":"v2.1.1","text":"

Files

Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57

"},{"location":"home/releases/#summary_15","title":"Summary","text":"

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.

"},{"location":"home/releases/#changes_1","title":"Changes","text":""},{"location":"home/releases/#v210","title":"v2.1.0","text":"

Files

"},{"location":"home/releases/#summary_16","title":"Summary","text":"

This release introduces a means to convert from/to user-defined types. The release is backwards compatible.

"},{"location":"home/releases/#changes_2","title":"Changes","text":""},{"location":"home/releases/#v2010","title":"v2.0.10","text":"

Files

"},{"location":"home/releases/#summary_17","title":"Summary","text":"

This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.

"},{"location":"home/releases/#changes_3","title":"Changes","text":""},{"location":"home/releases/#v209","title":"v2.0.9","text":"

Files

"},{"location":"home/releases/#summary_18","title":"Summary","text":"

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.

"},{"location":"home/releases/#changes_4","title":"Changes","text":""},{"location":"home/releases/#v208","title":"v2.0.8","text":"

Files

"},{"location":"home/releases/#summary_19","title":"Summary","text":"

This release combines a lot of small fixes and improvements. The fixes are backwards compatible.

"},{"location":"home/releases/#changes_5","title":"Changes","text":""},{"location":"home/releases/#v207","title":"v2.0.7","text":"

Files

"},{"location":"home/releases/#summary_20","title":"Summary","text":"

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.

"},{"location":"home/releases/#changes_6","title":"Changes","text":""},{"location":"home/releases/#v206","title":"v2.0.6","text":"

Files

"},{"location":"home/releases/#summary_21","title":"Summary","text":"

This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible.

"},{"location":"home/releases/#changes_7","title":"Changes","text":""},{"location":"home/releases/#v205","title":"v2.0.5","text":"

Files

"},{"location":"home/releases/#summary_22","title":"Summary","text":"

This release fixes a regression bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.

"},{"location":"home/releases/#changes_8","title":"Changes","text":""},{"location":"home/releases/#v204","title":"v2.0.4","text":"

Files

"},{"location":"home/releases/#summary_23","title":"Summary","text":"

This release fixes a bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.

"},{"location":"home/releases/#changes_9","title":"Changes","text":""},{"location":"home/releases/#v203","title":"v2.0.3","text":"

Files

"},{"location":"home/releases/#summary_24","title":"Summary","text":"

This release combines a lot of small fixes and improvements. The release is backwards compatible.

"},{"location":"home/releases/#changes_10","title":"Changes","text":""},{"location":"home/releases/#v202","title":"v2.0.2","text":"

Files

"},{"location":"home/releases/#summary_25","title":"Summary","text":"

This release combines a lot of small fixes and improvements. The release is backwards compatible.

"},{"location":"home/releases/#changes_11","title":"Changes","text":""},{"location":"home/releases/#v201","title":"v2.0.1","text":"

Files

"},{"location":"home/releases/#summary_26","title":"Summary","text":"

This release fixes a performance regression in the JSON serialization (function dump()). This fix is backwards compatible.

"},{"location":"home/releases/#changes_12","title":"Changes","text":""},{"location":"home/releases/#v200","title":"v2.0.0","text":"

Files

"},{"location":"home/releases/#summary_27","title":"Summary","text":"

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.

As noexcept and constexpr 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.

"},{"location":"home/releases/#changes_13","title":"Changes","text":""},{"location":"home/releases/#notes","title":"Notes","text":""},{"location":"home/releases/#v110","title":"v1.1.0","text":"

Files

"},{"location":"home/releases/#summary_28","title":"Summary","text":"

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:

"},{"location":"home/releases/#changes_14","title":"Changes","text":""},{"location":"home/releases/#notes_1","title":"Notes","text":"

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.

"},{"location":"home/releases/#v100","title":"v1.0.0","text":"

Files

"},{"location":"home/releases/#summary_29","title":"Summary","text":"

This is the first official release. Compared to the prerelease version 1.0.0-rc1, only a few minor improvements have been made:

"},{"location":"home/releases/#changes_15","title":"Changes","text":""},{"location":"home/sponsors/","title":"Sponsors","text":"

You can sponsor this library at GitHub Sponsors.

"},{"location":"home/sponsors/#named-sponsors","title":"Named Sponsors","text":"

Thanks everyone!

"},{"location":"integration/","title":"Header only","text":"

json.hpp is the single required file in single_include/nlohmann or released here. You need to add

#include <nlohmann/json.hpp>\n\n// for convenience\nusing json = nlohmann::json;\n

to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang).

You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.

"},{"location":"integration/cmake/","title":"CMake","text":""},{"location":"integration/cmake/#integration","title":"Integration","text":"

You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags.

"},{"location":"integration/cmake/#external","title":"External","text":"

To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration:

Example

CMakeLists.txt
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

The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.

"},{"location":"integration/cmake/#embedded","title":"Embedded","text":"

To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.

Example

CMakeLists.txt
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

Note

Do not use include(nlohmann_json/CMakeLists.txt), 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 include(...) for pulling in other CMake projects anyways.

"},{"location":"integration/cmake/#supporting-both","title":"Supporting Both","text":"

To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.

Example

CMakeLists.txt
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
thirdparty/CMakeLists.txt
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

thirdparty/nlohmann_json is then a complete copy of this source tree.

"},{"location":"integration/cmake/#fetchcontent","title":"FetchContent","text":"

Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type.

Example

CMakeLists.txt
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

Note

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

FetchContent_Declare(json\n    GIT_REPOSITORY https://github.com/nlohmann/json\n    GIT_TAG v3.11.3\n)\n

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.

"},{"location":"integration/cmake/#cmake-options","title":"CMake Options","text":""},{"location":"integration/cmake/#json_buildtests","title":"JSON_BuildTests","text":"

Build the unit tests when BUILD_TESTING is enabled. This option is ON 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.

"},{"location":"integration/cmake/#json_ci","title":"JSON_CI","text":"

Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.

"},{"location":"integration/cmake/#json_diagnostics","title":"JSON_Diagnostics","text":"

Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS. This option is OFF by default.

"},{"location":"integration/cmake/#json_disableenumserialization","title":"JSON_DisableEnumSerialization","text":"

Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION. This option is OFF by default.

"},{"location":"integration/cmake/#json_fasttests","title":"JSON_FastTests","text":"

Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests.

"},{"location":"integration/cmake/#json_globaludls","title":"JSON_GlobalUDLs","text":"

Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS. This option is OFF by default.

"},{"location":"integration/cmake/#json_implicitconversions","title":"JSON_ImplicitConversions","text":"

Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS. This option is ON by default.

"},{"location":"integration/cmake/#json_install","title":"JSON_Install","text":"

Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project.

"},{"location":"integration/cmake/#json_multipleheaders","title":"JSON_MultipleHeaders","text":"

Use non-amalgamated version of the library. This option is OFF by default.

"},{"location":"integration/cmake/#json_systeminclude","title":"JSON_SystemInclude","text":"

Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default.

"},{"location":"integration/cmake/#json_valgrind","title":"JSON_Valgrind","text":"

Execute test suite with Valgrind. This option is OFF by default. Depends on JSON_BuildTests.

"},{"location":"integration/migration_guide/","title":"Migration Guide","text":"

This page collects some guidelines on how to future-proof your code for future versions of this library.

"},{"location":"integration/migration_guide/#replace-deprecated-functions","title":"Replace deprecated functions","text":"

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 HEDLEY_DEPRECATED_FOR to report which function to use instead.

"},{"location":"integration/migration_guide/#parsing","title":"Parsing","text":""},{"location":"integration/migration_guide/#json-pointers","title":"JSON Pointers","text":""},{"location":"integration/migration_guide/#miscellaneous-functions","title":"Miscellaneous functions","text":""},{"location":"integration/migration_guide/#replace-implicit-conversions","title":"Replace implicit conversions","text":"

Implicit conversions via operator ValueType will be switched off by default in the next major release of the library.

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get, get_to, get_ref, or get_ptr.

DeprecatedFuture-proofFuture-proof (alternative)
nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n
nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n
nlohmann::json j = \"Hello, world!\";\nstd::string s;\nj.get_to(s);\n

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.

"},{"location":"integration/migration_guide/#import-namespace-literals-for-udls","title":"Import namespace literals for UDLs","text":"

The user-defined string literals operator\"\"_json and operator\"\"_json_pointer will be removed from the global namespace in the next major release of the library.

DeprecatedFuture-proof
nlohmann::json j = \"[1,2,3]\"_json;\n
using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n

To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.

"},{"location":"integration/migration_guide/#do-not-hard-code-the-complete-library-namespace","title":"Do not hard-code the complete library namespace","text":"

The nlohmann namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use nlohmann as namespace or, when the exact version and configuration is relevant, use macro NLOHMANN_JSON_NAMESPACE to denote the namespace.

DangerousFuture-proofFuture-proof (alternative)
void to_json(nlohmann::json_abi_v3_11_2::json& j, const person& p)\n{\n    j[\"age\"] = p.age;\n}\n
void to_json(nlohmann::json& j, const person& p)\n{\n    j[\"age\"] = p.age;\n}\n
void to_json(NLOHMANN_JSON_NAMESPACE::json& j, const person& p)\n{\n    j[\"age\"] = p.age;\n}\n
"},{"location":"integration/migration_guide/#do-not-use-the-details-namespace","title":"Do not use the details namespace","text":"

The details 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 details namespace.

"},{"location":"integration/package_managers/","title":"Package Managers","text":"

Throughout this page, we will describe how to compile the example file example.cpp below.

#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

When executed, this program should create output similar to

{\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
"},{"location":"integration/package_managers/#homebrew","title":"Homebrew","text":"

If you are using OS X and Homebrew, just type

brew install nlohmann-json\n

and you're set. If you want the bleeding edge rather than the latest release, use

brew install nlohmann-json --HEAD\n

instead. See nlohmann-json for more information.

Example
  1. Create the following file:

    example.cpp
    #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
  2. Install the package

    brew install nlohmann-json\n
  3. Determine the include path, which defaults to /usr/local/Cellar/nlohmann-json/$version/include, where $version is the version of the library, e.g. 3.7.3. The path of the library can be determined with

    brew list nlohmann-json\n
  4. Compile the code. For instance, the code can be compiled using Clang with

    clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std=c++11 -o example\n

The formula is updated automatically.

"},{"location":"integration/package_managers/#meson","title":"Meson","text":"

If you are using the Meson Build System, add this source tree as a meson subproject. You may also use the include.zip 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 meson wrap install nlohmann_json. Please see the meson project for any issues regarding the packaging.

The provided meson.build can also be used as an alternative to cmake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly.

"},{"location":"integration/package_managers/#bazel","title":"Bazel","text":"

This repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive, git_repository, or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g. via deps attribute).

"},{"location":"integration/package_managers/#conan","title":"Conan","text":"

If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages.

Example
  1. Create the following files:

    Conanfile.txt
    [requires]\nnlohmann_json/3.7.3\n\n[generators]\ncmake\n
    CMakeLists.txt
    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
    example.cpp
    #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
  2. Build:

    mkdir build\ncd build\nconan install ..\ncmake ..\ncmake --build .\n

The package is updated automatically.

"},{"location":"integration/package_managers/#spack","title":"Spack","text":"

If you are using Spack to manage your dependencies, you can use the nlohmann-json package. Please see the spack project for any issues regarding the packaging.

"},{"location":"integration/package_managers/#hunter","title":"Hunter","text":"

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.

"},{"location":"integration/package_managers/#buckaroo","title":"Buckaroo","text":"

If you are using Buckaroo, you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json. Please file issues here. There is a demo repo here.

"},{"location":"integration/package_managers/#vcpkg","title":"vcpkg","text":"

If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with vcpkg install nlohmann-json and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging.

Example
  1. Create the following files:

    CMakeLists.txt
    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
    example.cpp
    #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
  2. Install package:

    vcpkg install nlohmann-json\n
  3. Build:

    mkdir build\ncd build\ncmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake\ncmake --build .\n

Note you need to adjust /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake to your system.

"},{"location":"integration/package_managers/#cget","title":"cget","text":"

If you are using cget, you can install the latest development version with cget install nlohmann/json. A specific version can be installed with cget install nlohmann/json@v3.1.0. Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON).

cget reads directly from the GitHub repository and is always up-to-date.

"},{"location":"integration/package_managers/#cocoapods","title":"CocoaPods","text":"

If you are using CocoaPods, you can use the library by adding pod \"nlohmann_json\", '~>3.1.2' to your podfile (see an example). Please file issues here.

"},{"location":"integration/package_managers/#nuget","title":"NuGet","text":"

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.

"},{"location":"integration/package_managers/#conda","title":"Conda","text":"

If you are using conda, you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json. Please file issues here.

"},{"location":"integration/package_managers/#msys2","title":"MSYS2","text":"

If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages.

The package is updated automatically.

"},{"location":"integration/package_managers/#macports","title":"MacPorts","text":"

If you are using MacPorts, execute sudo port install nlohmann-json to install the nlohmann-json package.

The package is updated automatically.

"},{"location":"integration/package_managers/#build2","title":"build2","text":"

If you are using build2, you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository. In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints). If you are not familiar with using dependencies in build2, please read this introduction. Please file issues here if you experience problems with the packages.

The package is updated automatically.

"},{"location":"integration/package_managers/#wsjcpp","title":"wsjcpp","text":"

If you are using wsjcpp, you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch.

wsjcpp reads directly from the GitHub repository and is always up-to-date.

"},{"location":"integration/package_managers/#cpmcmake","title":"CPM.cmake","text":"

If you are using CPM.cmake, you can check this example. After adding CPM script to your project, implement the following snippet to your CMake:

CPMAddPackage(\n    NAME nlohmann_json\n    GITHUB_REPOSITORY nlohmann/json\n    VERSION 3.9.1)\n
"},{"location":"integration/pkg-config/","title":"Pkg-config","text":"

If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed:

pkg-config nlohmann_json --cflags\n

Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config:

json = dependency('nlohmann_json', required: true)\n
"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"JSON for Modern C++","text":""},{"location":"api/json/","title":"nlohmann::json","text":"
using json = basic_json<>;\n

This type is the default specialization of the basic_json class which uses the standard template types.

"},{"location":"api/json/#examples","title":"Examples","text":"Example

The example below demonstrates how to use the type nlohmann::json.

#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

Output:

{\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
"},{"location":"api/json/#version-history","title":"Version history","text":"

Since version 1.0.0.

"},{"location":"api/operator_gtgt/","title":"nlohmann::operator>>(basic_json)","text":"
std::istream& operator>>(std::istream& i, basic_json& j);\n

Deserializes an input stream to a JSON value.

"},{"location":"api/operator_gtgt/#parameters","title":"Parameters","text":"i (in, out) input stream to read a serialized JSON value from j (in, out) JSON value to write the deserialized input to"},{"location":"api/operator_gtgt/#return-value","title":"Return value","text":"

the stream i

"},{"location":"api/operator_gtgt/#exceptions","title":"Exceptions","text":""},{"location":"api/operator_gtgt/#complexity","title":"Complexity","text":"

Linear in the length of the input. The parser is a predictive LL(1) parser.

"},{"location":"api/operator_gtgt/#notes","title":"Notes","text":"

A UTF-8 byte order mark is silently ignored.

Deprecation

This function replaces function std::istream& operator<<(basic_json& j, std::istream& i) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i; with i >> j;.

"},{"location":"api/operator_gtgt/#examples","title":"Examples","text":"Example

The example below shows how a JSON value is constructed by reading a serialization from a stream.

#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

Output:

{\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
"},{"location":"api/operator_gtgt/#see-also","title":"See also","text":""},{"location":"api/operator_gtgt/#version-history","title":"Version history","text":""},{"location":"api/operator_literal_json/","title":"nlohmann::operator\"\"_json","text":"
json operator \"\"_json(const char* s, std::size_t n);\n

This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred.

It is recommended to bring the operator into scope using any of the following lines:

using nlohmann::literals::operator \"\"_json;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n

This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.

"},{"location":"api/operator_literal_json/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON object n (in) length of string s"},{"location":"api/operator_literal_json/#return-value","title":"Return value","text":"

json value parsed from s

"},{"location":"api/operator_literal_json/#exceptions","title":"Exceptions","text":"

The function can throw anything that parse(s, s+n) would throw.

"},{"location":"api/operator_literal_json/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/operator_literal_json/#examples","title":"Examples","text":"Example

The following code shows how to create JSON values from string literals.

#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

Output:

{\n  \"answer\": 42,\n  \"hello\": \"world\"\n}\n
"},{"location":"api/operator_literal_json/#version-history","title":"Version history","text":""},{"location":"api/operator_literal_json_pointer/","title":"nlohmann::operator\"\"_json_pointer","text":"
json_pointer operator \"\"_json_pointer(const char* s, std::size_t n);\n

This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred.

It is recommended to bring the operator into scope using any of the following lines:

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
This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.

"},{"location":"api/operator_literal_json_pointer/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON Pointer n (in) length of string s"},{"location":"api/operator_literal_json_pointer/#return-value","title":"Return value","text":"

json_pointer value parsed from s

"},{"location":"api/operator_literal_json_pointer/#exceptions","title":"Exceptions","text":"

The function can throw anything that json_pointer::json_pointer would throw.

"},{"location":"api/operator_literal_json_pointer/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/operator_literal_json_pointer/#examples","title":"Examples","text":"Example

The following code shows how to create JSON Pointers from string literals.

#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

Output:

\"world\"\n
"},{"location":"api/operator_literal_json_pointer/#see-also","title":"See also","text":""},{"location":"api/operator_literal_json_pointer/#version-history","title":"Version history","text":""},{"location":"api/operator_ltlt/","title":"nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)","text":"
std::ostream& operator<<(std::ostream& o, const basic_json& j);      // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr);  // (2)\n
  1. Serialize the given JSON value j to the output stream o. The JSON value will be serialized using the dump member function.
    • The indentation of the output can be controlled with the member variable width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).
    • The indentation character can be controlled with the member variable fill of the output stream o. For instance, the manipulator std::setfill('\\\\t') sets indentation to use a tab character rather than the default space character.
  2. Write a string representation of the given JSON pointer ptr to the output stream o. The string representation is obtained using the to_string member function.
"},{"location":"api/operator_ltlt/#parameters","title":"Parameters","text":"o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write"},{"location":"api/operator_ltlt/#return-value","title":"Return value","text":"

the stream o

"},{"location":"api/operator_ltlt/#exceptions","title":"Exceptions","text":"
  1. Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike the dump member functions, no error_handler can be set.
  2. None.
"},{"location":"api/operator_ltlt/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/operator_ltlt/#notes","title":"Notes","text":"

Deprecation

Function std::ostream& operator<<(std::ostream& o, const basic_json& j) replaces function std::ostream& operator>>(const basic_json& j, std::ostream& o) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o; with o << j;.

"},{"location":"api/operator_ltlt/#examples","title":"Examples","text":"Example: (1) serialize JSON value to stream

The example below shows the serialization with different parameters to width to adjust the indentation level.

#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

Output:

{\"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
Example: (2) write JSON pointer to stream

The example below shows how to write a JSON pointer to a stream.

#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

Output:

/foo/bar/baz\n
"},{"location":"api/operator_ltlt/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added support for indentation character and deprecated std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.
  2. Added in version 3.11.0.
"},{"location":"api/ordered_json/","title":"nlohmann::ordered_json","text":"
using ordered_json = basic_json<ordered_map>;\n

This type preserves the insertion order of object keys.

"},{"location":"api/ordered_json/#examples","title":"Examples","text":"Example

The example below demonstrates how ordered_json preserves the insertion order of object keys.

#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

Output:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n
"},{"location":"api/ordered_json/#see-also","title":"See also","text":""},{"location":"api/ordered_json/#version-history","title":"Version history","text":"

Since version 3.9.0.

"},{"location":"api/ordered_map/","title":"nlohmann::ordered_map","text":"
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

A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json (nlohmann::basic_json<ordered_map>).

"},{"location":"api/ordered_map/#template-parameters","title":"Template parameters","text":"Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std::map) Allocator allocator type"},{"location":"api/ordered_map/#member-types","title":"Member types","text":""},{"location":"api/ordered_map/#member-functions","title":"Member functions","text":""},{"location":"api/ordered_map/#examples","title":"Examples","text":"Example

The example shows the different behavior of std::map and nlohmann::ordered_map.

#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

Output:

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
"},{"location":"api/ordered_map/#see-also","title":"See also","text":""},{"location":"api/ordered_map/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/","title":"nlohmann::adl_serializer","text":"
template<typename, typename>\nstruct adl_serializer;\n

Serializer that uses ADL (Argument-Dependent Lookup) to choose to_json/from_json functions from the types' namespaces.

It is implemented similar to

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
"},{"location":"api/adl_serializer/#member-functions","title":"Member functions","text":""},{"location":"api/adl_serializer/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/from_json/","title":"nlohmann::adl_serializer::from_json","text":"
// (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

This function is usually called by the get() function of the basic_json class (either explicitly or via the conversion operators).

  1. This function is chosen for default-constructible value types.
  2. This function is chosen for value types which are not default-constructible.
"},{"location":"api/adl_serializer/from_json/#parameters","title":"Parameters","text":"j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"

Copy of the JSON value, converted to ValueType

"},{"location":"api/adl_serializer/from_json/#examples","title":"Examples","text":"Example: (1) Default-constructible type

The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when template get<ns::person>() is called.

#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

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
Example: (2) Non-default-constructible type

The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.

#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

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
"},{"location":"api/adl_serializer/from_json/#see-also","title":"See also","text":""},{"location":"api/adl_serializer/from_json/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/to_json/","title":"nlohmann::adl_serializer::to_json","text":"
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

This function is usually called by the constructors of the basic_json class.

"},{"location":"api/adl_serializer/to_json/#parameters","title":"Parameters","text":"j (out) JSON value to write to val (in) value to read from"},{"location":"api/adl_serializer/to_json/#examples","title":"Examples","text":"Example

The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called.

#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

Output:

{\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n
"},{"location":"api/adl_serializer/to_json/#see-also","title":"See also","text":""},{"location":"api/adl_serializer/to_json/#version-history","title":"Version history","text":""},{"location":"api/basic_json/","title":"nlohmann::basic_json","text":"

Defined in header <nlohmann/json.hpp>

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
"},{"location":"api/basic_json/#template-parameters","title":"Template parameters","text":"Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t"},{"location":"api/basic_json/#specializations","title":"Specializations","text":""},{"location":"api/basic_json/#iterator-invalidation","title":"Iterator invalidation","text":"

Todo

"},{"location":"api/basic_json/#requirements","title":"Requirements","text":"

The class satisfies the following concept requirements:

"},{"location":"api/basic_json/#basic","title":"Basic","text":""},{"location":"api/basic_json/#layout","title":"Layout","text":""},{"location":"api/basic_json/#library-wide","title":"Library-wide","text":""},{"location":"api/basic_json/#container","title":"Container","text":""},{"location":"api/basic_json/#member-types","title":"Member types","text":""},{"location":"api/basic_json/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/#container-types","title":"Container types","text":"Type Definition value_type basic_json reference value_type& const_reference const value_type& difference_type std::ptrdiff_t size_type std::size_t allocator_type AllocatorType<basic_json> pointer std::allocator_traits<allocator_type>::pointer const_pointer std::allocator_traits<allocator_type>::const_pointer iterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iterator const_reverse_iterator reverse iterator, derived from const_iterator iteration_proxy helper type for items function"},{"location":"api/basic_json/#json-value-data-types","title":"JSON value data types","text":""},{"location":"api/basic_json/#parser-callback","title":"Parser callback","text":""},{"location":"api/basic_json/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/#object-inspection","title":"Object inspection","text":"

Functions to inspect the type of a JSON value.

"},{"location":"api/basic_json/#value-access","title":"Value access","text":"

Direct access to the stored value of a JSON value.

"},{"location":"api/basic_json/#element-access","title":"Element access","text":"

Access to the JSON value

"},{"location":"api/basic_json/#lookup","title":"Lookup","text":""},{"location":"api/basic_json/#iterators","title":"Iterators","text":""},{"location":"api/basic_json/#capacity","title":"Capacity","text":""},{"location":"api/basic_json/#modifiers","title":"Modifiers","text":""},{"location":"api/basic_json/#lexicographical-comparison-operators","title":"Lexicographical comparison operators","text":""},{"location":"api/basic_json/#serialization-dumping","title":"Serialization / Dumping","text":""},{"location":"api/basic_json/#deserialization-parsing","title":"Deserialization / Parsing","text":""},{"location":"api/basic_json/#json-pointer-functions","title":"JSON Pointer functions","text":""},{"location":"api/basic_json/#json-patch-functions","title":"JSON Patch functions","text":""},{"location":"api/basic_json/#json-merge-patch-functions","title":"JSON Merge Patch functions","text":""},{"location":"api/basic_json/#static-functions","title":"Static functions","text":""},{"location":"api/basic_json/#binary-formats","title":"Binary formats","text":""},{"location":"api/basic_json/#non-member-functions","title":"Non-member functions","text":""},{"location":"api/basic_json/#literals","title":"Literals","text":""},{"location":"api/basic_json/#helper-classes","title":"Helper classes","text":""},{"location":"api/basic_json/#examples","title":"Examples","text":"Example

The example shows how the library is used.

#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

Output:

{\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
"},{"location":"api/basic_json/#see-also","title":"See also","text":""},{"location":"api/basic_json/#version-history","title":"Version history","text":""},{"location":"api/basic_json/accept/","title":"nlohmann::basic_json::accept","text":"
// (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

Checks whether the input is valid JSON.

  1. Reads from a compatible input.
  2. Reads from a pair of character iterators

    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.

Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.

"},{"location":"api/basic_json/accept/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType

a compatible iterator type, for instance.

"},{"location":"api/basic_json/accept/#parameters","title":"Parameters","text":"i (in) Input to parse from. ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"

Whether the input is valid JSON.

"},{"location":"api/basic_json/accept/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/accept/#complexity","title":"Complexity","text":"

Linear in the length of the input. The parser is a predictive LL(1) parser.

"},{"location":"api/basic_json/accept/#notes","title":"Notes","text":"

(1) A UTF-8 byte order mark is silently ignored.

Runtime assertion

The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion.

"},{"location":"api/basic_json/accept/#examples","title":"Examples","text":"Example

The example below demonstrates the accept() function reading from a string.

#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

Output:

true false\n
"},{"location":"api/basic_json/accept/#see-also","title":"See also","text":""},{"location":"api/basic_json/accept/#version-history","title":"Version history","text":"

Deprecation

Overload (2) replaces calls to accept 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 accept({ptr, ptr+len}, ...); with accept(ptr, ptr+len, ...);.

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/array/","title":"nlohmann::basic_json::array","text":"
static basic_json array(initializer_list_t init = {});\n

Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.

"},{"location":"api/basic_json/array/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an array from (optional)"},{"location":"api/basic_json/array/#return-value","title":"Return value","text":"

JSON array value

"},{"location":"api/basic_json/array/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/array/#complexity","title":"Complexity","text":"

Linear in the size of init.

"},{"location":"api/basic_json/array/#notes","title":"Notes","text":"

This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (basic_json(initializer_list_t, bool, value_t)). These cases are:

  1. 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
  2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
"},{"location":"api/basic_json/array/#examples","title":"Examples","text":"Example

The following code shows an example for the array function.

#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

Output:

[]\n[]\n[1,2,3,4]\n[[\"one\",1],[\"two\",2]]\n
"},{"location":"api/basic_json/array/#see-also","title":"See also","text":""},{"location":"api/basic_json/array/#version-history","title":"Version history","text":""},{"location":"api/basic_json/array_t/","title":"nlohmann::basic_json::array_t","text":"
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n

The type used to store JSON arrays.

RFC 8259 describes JSON arrays as follows:

An array is an ordered sequence of zero or more values.

To store objects in C++, a type is defined by the template parameters explained below.

"},{"location":"api/basic_json/array_t/#template-parameters","title":"Template parameters","text":"ArrayType container type to store arrays (e.g., std::vector or std::list) AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/array_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/array_t/#default-type","title":"Default type","text":"

With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:

std::vector<\n  basic_json, // value_type\n  std::allocator<basic_json> // allocator_type\n>\n
"},{"location":"api/basic_json/array_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON array.

"},{"location":"api/basic_json/array_t/#storage","title":"Storage","text":"

Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.

"},{"location":"api/basic_json/array_t/#examples","title":"Examples","text":"Example

The following code shows that array_t is by default, a typedef to std::vector<nlohmann::json>.

#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

Output:

true\n
"},{"location":"api/basic_json/array_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/at/","title":"nlohmann::basic_json::at","text":"
// (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
  1. Returns a reference to the array element at specified location idx, with bounds checking.
  2. Returns a reference to the object element with specified key key, with bounds checking.
  3. See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
  4. Returns a reference to the element at specified JSON pointer ptr, with bounds checking.
"},{"location":"api/basic_json/at/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/at/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the elements to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/at/#return-value","title":"Return value","text":"
  1. reference to the element at index idx
  2. reference to the element at key key
  3. reference to the element at key key
  4. reference to the element pointed to by ptr
"},{"location":"api/basic_json/at/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/at/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.
    • Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.
  2. The function can throw the following exceptions:
    • Throws type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.
    • Throws out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.
  3. See 2.
  4. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.
    • Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.
    • Throws out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.
    • Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.
    • Throws out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.
    • Throws out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.
"},{"location":"api/basic_json/at/#complexity","title":"Complexity","text":"
  1. Constant.
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
  4. Logarithmic in the size of the container.
"},{"location":"api/basic_json/at/#examples","title":"Examples","text":"Example: (1) access specified array element with bounds checking

The example below shows how array elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (1) access specified array element with bounds checking

The example below shows how array elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (2) access specified object element with bounds checking

The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (2) access specified object element with bounds checking

The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"il brutto\"\n[json.exception.type_error.304] cannot use at() with string\nout of range\n
Example: (3) access specified object element using string_view with bounds checking

The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"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
Example: (3) access specified object element using string_view with bounds checking

The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

\"il brutto\"\n[json.exception.type_error.304] cannot use at() with string\nout of range\n
Example: (4) access specified element via JSON Pointer

The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

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
Example: (4) access specified element via JSON Pointer

The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown.

#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

Output:

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
"},{"location":"api/basic_json/at/#see-also","title":"See also","text":""},{"location":"api/basic_json/at/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0.
  3. Added in version 3.11.0.
  4. Added in version 2.0.0.
"},{"location":"api/basic_json/back/","title":"nlohmann::basic_json::back","text":"
reference back();\n\nconst_reference back() const;\n

Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to

auto tmp = c.end();\n--tmp;\nreturn *tmp;\n
"},{"location":"api/basic_json/back/#return-value","title":"Return value","text":"

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.

"},{"location":"api/basic_json/back/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/back/#exceptions","title":"Exceptions","text":"

If the JSON value is null, exception invalid_iterator.214 is thrown.

"},{"location":"api/basic_json/back/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/back/#notes","title":"Notes","text":"

Precondition

The array or object must not be empty. Calling back on an empty array or object yields undefined behavior.

"},{"location":"api/basic_json/back/#examples","title":"Examples","text":"Example

The following code shows an example for back().

#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

Output:

true\n17\n23.42\n2\n16\n\"Hello, world\"\n[json.exception.invalid_iterator.214] cannot get value\n
"},{"location":"api/basic_json/back/#see-also","title":"See also","text":""},{"location":"api/basic_json/back/#version-history","title":"Version history","text":""},{"location":"api/basic_json/basic_json/","title":"nlohmann::basic_json::basic_json","text":"
// (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
  1. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:

    Value type initial value null null boolean false string \"\" number 0 object {} array [] binary empty array

    The postcondition of this constructor can be restored by calling clear().

  2. Create a null JSON value. It either takes a null pointer as parameter (explicitly creating null) or no parameter (implicitly creating null). The passed null pointer itself is not read -- it is only used to choose the right constructor.

  3. This is a \"catch all\" constructor for all compatible JSON types; that is, types for which a to_json() method exists. The constructor forwards the parameter val to that method (to json_serializer<U>::to_json method with U = uncvref_t<CompatibleType>, to be exact).

    Template type CompatibleType includes, but is not limited to, the following types:

    • arrays: array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.
    • objects: object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.
    • strings: string_t, string literals, and all compatible string containers can be used.
    • numbers: number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.
    • boolean: boolean_t / bool can be used.
    • binary: binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* 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.

    See the examples below.

  4. This is a constructor for existing basic_json types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones.

    The constructor tries to convert the internal m_value of the parameter.

  5. Creates a JSON value of type array or object from the passed initializer list init. In case type_deduction is true (default), the type of the JSON value to be created is deducted from the initializer list init according to the following rules:

    1. If the list is empty, an empty JSON object value {} is created.
    2. 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.
    3. In all other cases, an array is created.

    The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:

    1. The empty initializer list is written as {} which is exactly an empty JSON object.
    2. 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.
    3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe.

    With the rules described above, the following JSON values cannot be expressed by an initializer list:

    • the empty array ([]): use array(initializer_list_t) with an empty initializer list in this case
    • arrays whose elements satisfy rule 2: use array(initializer_list_t) with the same initializer list in this case

    Function array() and object() force array and object creation from initializer lists, respectively.

  6. Constructs a JSON array value by creating cnt copies of a passed value. In case cnt is 0, an empty array is created.

  7. Constructs the JSON value with the contents of the range [first, last). The semantics depends on the different types a JSON value can have:

    • In case of a null type, invalid_iterator.206 is thrown.
    • In case of other primitive types (number, boolean, or string), first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.
    • In case of structured types (array, object), the constructor behaves as similar versions for std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.
  8. Creates a copy of a given JSON value.

  9. Move constructor. Constructs a JSON value with the contents of the given value other using move semantics. It \"steals\" the resources from other and leaves it as JSON null value.

"},{"location":"api/basic_json/basic_json/#template-parameters","title":"Template parameters","text":"CompatibleType

a type such that:

BasicJsonType:

a type such that:

U: uncvref_t<CompatibleType>"},{"location":"api/basic_json/basic_json/#parameters","title":"Parameters","text":"v (in) the type of the value to create val (in) the value to be forwarded to the respective constructor init (in) initializer list with JSON values type_deduction (in) internal parameter; when set to true, the type of the JSON value is deducted from the initializer list init; when set to false, the type provided via manual_type is forced. This mode is used by the functions array(initializer_list_t) and object(initializer_list_t). manual_type (in) internal parameter; when type_deduction is set to false, the created JSON value will use the provided type (only value_t::array and value_t::object are valid); when type_deduction is set to true, this parameter has no effect cnt (in) the number of JSON copies of val to create first (in) begin of the range to copy from (included) last (in) end of the range to copy from (excluded) other (in) the JSON value to copy/move"},{"location":"api/basic_json/basic_json/#exception-safety","title":"Exception safety","text":"
  1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  2. No-throw guarantee: this constructor never throws exceptions.
  3. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
  4. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
  5. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  6. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  7. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  8. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
  9. No-throw guarantee: this constructor never throws exceptions.
"},{"location":"api/basic_json/basic_json/#exceptions","title":"Exceptions","text":"
  1. (none)
  2. The function does not throw exceptions.
  3. (none)
  4. (none)
  5. The function can throw the following exceptions:
    • Throws type_error.301 if type_deduction is false, manual_type is value_t::object, but init 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 type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.
  6. (none)
  7. The function can throw the following exceptions:
    • Throws invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.
    • Throws invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.
    • Throws invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.
  8. (none)
  9. The function does not throw exceptions.
"},{"location":"api/basic_json/basic_json/#complexity","title":"Complexity","text":"
  1. Constant.
  2. Constant.
  3. Usually linear in the size of the passed val, also depending on the implementation of the called to_json() method.
  4. Usually linear in the size of the passed val, also depending on the implementation of the called to_json() method.
  5. Linear in the size of the initializer list init.
  6. Linear in cnt.
  7. Linear in distance between first and last.
  8. Linear in the size of other.
  9. Constant.
"},{"location":"api/basic_json/basic_json/#notes","title":"Notes","text":""},{"location":"api/basic_json/basic_json/#examples","title":"Examples","text":"Example: (1) create an empty value with a given type

The following code shows the constructor for different value_t values.

#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

Output:

null\nfalse\n0\n0.0\n{}\n[]\n\"\"\n
Example: (2) create a null object

The following code shows the constructor with and without a null pointer parameter.

#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

Output:

null\nnull\n
Example: (3) create a JSON value from compatible types

The following code shows the constructor with several compatible types.

#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

Output:

{\"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

Note the output is platform-dependent.

Example: (5) create a container (array or object) from an initializer list

The example below shows how JSON values are created from initializer lists.

#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

Output:

{}\n{\"one\":1,\"two\":2}\n[1,2,3,4]\n{\"one\":[1],\"two\":[1,2]}\n[[[1],\"one\"],[[1,2],\"two\"]]\n
Example: (6) construct an array with count copies of given value

The following code shows examples for creating arrays with several copies of a given value.

#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

Output:

[]\n[\"Hello\"]\n[\"Hello\",\"Hello\",\"Hello\",\"Hello\",\"Hello\"]\n
Example: (7) construct a JSON container given an iterator range

The example below shows several ways to create JSON values by specifying a subrange with iterators.

#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

Output:

[\"bravo\",\"charly\"]\n42\n{\"one\":\"eins\"}\n[json.exception.invalid_iterator.204] iterators out of range\n
Example: (8) copy constructor

The following code shows an example for the copy constructor.

#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

Output:

[\"one\",\"two\",3,4.5,false] = [\"one\",\"two\",3,4.5,false]\ntrue\n
Example: (9) move constructor

The code below shows the move constructor explicitly called via std::move.

#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

Output:

null\n23\n
"},{"location":"api/basic_json/basic_json/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.1.0.
  4. Since version 3.2.0.
  5. Since version 1.0.0.
  6. Since version 1.0.0.
  7. Since version 1.0.0.
  8. Since version 1.0.0.
  9. Since version 1.0.0.
"},{"location":"api/basic_json/begin/","title":"nlohmann::basic_json::begin","text":"
iterator begin() noexcept;\nconst_iterator begin() const noexcept;\n

Returns an iterator to the first element.

"},{"location":"api/basic_json/begin/#return-value","title":"Return value","text":"

iterator to the first element

"},{"location":"api/basic_json/begin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/begin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/begin/#examples","title":"Examples","text":"Example

The following code shows an example for begin().

#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

Output:

1\n
"},{"location":"api/basic_json/begin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/binary/","title":"nlohmann::basic_json::binary","text":"
// (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
  1. Creates a JSON binary array value from a given binary container.
  2. Creates a JSON binary array value from a given binary container with subtype.

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.

"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"

JSON binary array value

"},{"location":"api/basic_json/binary/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/binary/#complexity","title":"Complexity","text":"

Linear in the size of init; constant for typename binary_t::container_type&& init versions.

"},{"location":"api/basic_json/binary/#notes","title":"Notes","text":"

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 std::vector. 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.

"},{"location":"api/basic_json/binary/#examples","title":"Examples","text":"Example

The following code shows how to create a binary value.

#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

Output:

type: binary, subtype: 42\n
"},{"location":"api/basic_json/binary/#version-history","title":"Version history","text":""},{"location":"api/basic_json/binary_t/","title":"nlohmann::basic_json::binary_t","text":"
using binary_t = byte_container_with_subtype<BinaryType>;\n

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.

Additionally, as an implementation detail, the subtype of the binary data is carried around as a std::uint64_t, 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 BinaryType via the helper type byte_container_with_subtype.

CBOR's RFC 7049 describes this type as:

Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).

MessagePack's documentation on the bin type family describes this type as:

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.

BSON's specifications describe several binary types; however, this type is intended to represent the generic binary type which has the description:

Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.

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.

The default representation of this binary format is a std::vector<std::uint8_t>, which is a very common way to represent a byte array in modern C++.

"},{"location":"api/basic_json/binary_t/#template-parameters","title":"Template parameters","text":"BinaryType 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":"

The default values for BinaryType is std::vector<std::uint8_t>.

"},{"location":"api/basic_json/binary_t/#storage","title":"Storage","text":"

Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t* must be dereferenced.

"},{"location":"api/basic_json/binary_t/#notes-on-subtypes","title":"Notes on subtypes","text":""},{"location":"api/basic_json/binary_t/#examples","title":"Examples","text":"Example

The following code shows that binary_t is by default, a typedef to nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>.

#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

Output:

true\n
"},{"location":"api/basic_json/binary_t/#see-also","title":"See also","text":""},{"location":"api/basic_json/binary_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/boolean_t/","title":"nlohmann::basic_json::boolean_t","text":"
using boolean_t = BooleanType;\n

The type used to store JSON booleans.

RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.

To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.

"},{"location":"api/basic_json/boolean_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/boolean_t/#default-type","title":"Default type","text":"

With the default values for BooleanType (bool), the default value for boolean_t is bool.

"},{"location":"api/basic_json/boolean_t/#storage","title":"Storage","text":"

Boolean values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/boolean_t/#examples","title":"Examples","text":"Example

The following code shows that boolean_t is by default, a typedef to bool.

#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

Output:

true\n
"},{"location":"api/basic_json/boolean_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cbegin/","title":"nlohmann::basic_json::cbegin","text":"
const_iterator cbegin() const noexcept;\n

Returns an iterator to the first element.

"},{"location":"api/basic_json/cbegin/#return-value","title":"Return value","text":"

iterator to the first element

"},{"location":"api/basic_json/cbegin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/cbegin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/cbegin/#examples","title":"Examples","text":"Example

The following code shows an example for cbegin().

#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

Output:

1\n
"},{"location":"api/basic_json/cbegin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cbor_tag_handler_t/","title":"nlohmann::basic_json::cbor_tag_handler_t","text":"
enum class cbor_tag_handler_t\n{\n    error,\n    ignore,\n    store\n};\n

This enumeration is used in the from_cbor function to choose how to treat tags:

error throw a parse_error 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

The example below shows how the different values of the cbor_tag_handler_t influence the behavior of from_cbor when reading a tagged byte string.

#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

Output:

[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
"},{"location":"api/basic_json/cbor_tag_handler_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cend/","title":"nlohmann::basic_json::cend","text":"
const_iterator cend() const noexcept;\n

Returns an iterator to one past the last element.

"},{"location":"api/basic_json/cend/#return-value","title":"Return value","text":"

iterator one past the last element

"},{"location":"api/basic_json/cend/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/cend/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/cend/#examples","title":"Examples","text":"Example

The following code shows an example for cend().

#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

Output:

5\n
"},{"location":"api/basic_json/cend/#version-history","title":"Version history","text":""},{"location":"api/basic_json/clear/","title":"nlohmann::basic_json::clear","text":"
void clear() noexcept;\n

Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type():

Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array []

Has the same effect as calling

*this = basic_json(type());\n
"},{"location":"api/basic_json/clear/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/clear/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value.

"},{"location":"api/basic_json/clear/#notes","title":"Notes","text":"

All iterators, pointers and references related to this container are invalidated.

"},{"location":"api/basic_json/clear/#examples","title":"Examples","text":"Example

The example below shows the effect of clear() to different JSON types.

#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

Output:

null\nfalse\n0\n0.0\n{}\n[]\n\"\"\n
"},{"location":"api/basic_json/clear/#version-history","title":"Version history","text":""},{"location":"api/basic_json/contains/","title":"nlohmann::basic_json::contains","text":"
// (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
  1. Check whether an element exists in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, false is returned.
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
  3. Check whether the given JSON pointer ptr can be resolved in the current JSON value.
"},{"location":"api/basic_json/contains/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/contains/#parameters","title":"Parameters","text":"key (in) key value to check its existence. ptr (in) JSON pointer to check its existence."},{"location":"api/basic_json/contains/#return-value","title":"Return value","text":"
  1. true if an element with specified key exists. If no such element with such key is found or the JSON value is not an object, false is returned.
  2. See 1.
  3. true if the JSON pointer can be resolved to a stored value, false otherwise.
"},{"location":"api/basic_json/contains/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/contains/#exceptions","title":"Exceptions","text":"
  1. The function does not throw exceptions.
  2. The function does not throw exceptions.
  3. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index begins with 0.
    • Throws parse_error.109 if an array index was not a number.
"},{"location":"api/basic_json/contains/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

"},{"location":"api/basic_json/contains/#notes","title":"Notes","text":"

Postconditions

If j.contains(x) returns true for a key or JSON pointer x, then it is safe to call j[x].

"},{"location":"api/basic_json/contains/#examples","title":"Examples","text":"Example: (1) check with key

The example shows how contains() is used.

#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

Output:

j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n
Example: (2) check with key using string_view

The example shows how contains() is used.

#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

Output:

j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n
Example: (3) check with JSON pointer

The example shows how contains() is used.

#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

Output:

true\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/contains/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0.
  3. Added in version 3.7.0.
"},{"location":"api/basic_json/count/","title":"nlohmann::basic_json::count","text":"
// (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
  1. Returns the number of elements with key key. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/count/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/count/#parameters","title":"Parameters","text":"key (in) key value of the element to count."},{"location":"api/basic_json/count/#return-value","title":"Return value","text":"

Number of elements with key key. If the JSON value is not an object, the return value will be 0.

"},{"location":"api/basic_json/count/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/count/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

"},{"location":"api/basic_json/count/#notes","title":"Notes","text":"

This method always returns 0 when executed on a JSON type that is not an object.

"},{"location":"api/basic_json/count/#examples","title":"Examples","text":"Example: (1) count number of elements

The example shows how count() is used.

#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

Output:

number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n
Example: (2) count number of elements using string_view

The example shows how count() is used.

#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

Output:

number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n
"},{"location":"api/basic_json/count/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0.
"},{"location":"api/basic_json/crbegin/","title":"nlohmann::basic_json::crbegin","text":"
const_reverse_iterator crbegin() const noexcept;\n

Returns an iterator to the reverse-beginning; that is, the last element.

"},{"location":"api/basic_json/crbegin/#return-value","title":"Return value","text":"

reverse iterator to the first element

"},{"location":"api/basic_json/crbegin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/crbegin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/crbegin/#examples","title":"Examples","text":"Example

The following code shows an example for crbegin().

#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

Output:

5\n
"},{"location":"api/basic_json/crbegin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/crend/","title":"nlohmann::basic_json::crend","text":"
const_reverse_iterator crend() const noexcept;\n

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.

"},{"location":"api/basic_json/crend/#return-value","title":"Return value","text":"

reverse iterator to the element following the last element

"},{"location":"api/basic_json/crend/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/crend/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/crend/#examples","title":"Examples","text":"Example

The following code shows an example for eend().

#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

Output:

1\n
"},{"location":"api/basic_json/crend/#version-history","title":"Version history","text":""},{"location":"api/basic_json/default_object_comparator_t/","title":"nlohmann::basic_json::default_object_comparator_t","text":"
using default_object_comparator_t = std::less<StringType>;  // until C++14\n\nusing default_object_comparator_t = std::less<>;            // since C++14\n

The default comparator used by object_t.

Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object.

The actual comparator used depends on object_t and can be obtained via object_comparator_t.

"},{"location":"api/basic_json/default_object_comparator_t/#examples","title":"Examples","text":"Example

The example below demonstrates the default comparator.

#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

Output:

one < two : true\nthree < four : false\n
"},{"location":"api/basic_json/default_object_comparator_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/diff/","title":"nlohmann::basic_json::diff","text":"
static basic_json diff(const basic_json& source,\n                       const basic_json& target);\n

Creates a JSON Patch so that value source can be changed into the value target by calling patch function.

For two JSON values source and target, the following code yields always true:

source.patch(diff(source, target)) == target;\n

"},{"location":"api/basic_json/diff/#parameters","title":"Parameters","text":"source (in) JSON value to compare from target (in) JSON value to compare against"},{"location":"api/basic_json/diff/#return-value","title":"Return value","text":"

a JSON patch to convert the source to target

"},{"location":"api/basic_json/diff/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/diff/#complexity","title":"Complexity","text":"

Linear in the lengths of source and target.

"},{"location":"api/basic_json/diff/#notes","title":"Notes","text":"

Currently, only remove, add, and replace operations are generated.

"},{"location":"api/basic_json/diff/#examples","title":"Examples","text":"Example

The following code shows how a JSON patch is created as a diff for two JSON values.

#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

Output:

[\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
"},{"location":"api/basic_json/diff/#see-also","title":"See also","text":""},{"location":"api/basic_json/diff/#version-history","title":"Version history","text":""},{"location":"api/basic_json/dump/","title":"nlohmann::basic_json::dump","text":"
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

Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent and ensure_ascii parameters.

"},{"location":"api/basic_json/dump/#parameters","title":"Parameters","text":"indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are three possible values (see error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (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":"

string containing the serialization of the JSON value

"},{"location":"api/basic_json/dump/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/dump/#exceptions","title":"Exceptions","text":"

Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict

"},{"location":"api/basic_json/dump/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/dump/#notes","title":"Notes","text":"

Binary values are serialized as object containing two keys:

"},{"location":"api/basic_json/dump/#examples","title":"Examples","text":"Example

The following example shows the effect of different indent, indent_char, and ensure_ascii parameters to the result of the serialization.

#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

Output:

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
"},{"location":"api/basic_json/dump/#version-history","title":"Version history","text":""},{"location":"api/basic_json/emplace/","title":"nlohmann::basic_json::emplace","text":"
template<class... Args>\nstd::pair<iterator, bool> emplace(Args&& ... args);\n

Inserts a new element into a JSON object constructed in-place with the given args 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 args.

"},{"location":"api/basic_json/emplace/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace/#return-value","title":"Return value","text":"

a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.

"},{"location":"api/basic_json/emplace/#exceptions","title":"Exceptions","text":"

Throws type_error.311 when called on a type other than JSON object or null; example: \"cannot use emplace() with number\"

"},{"location":"api/basic_json/emplace/#complexity","title":"Complexity","text":"

Logarithmic in the size of the container, O(log(size())).

"},{"location":"api/basic_json/emplace/#examples","title":"Examples","text":"Example

The example shows how emplace() can be used to add elements to a JSON object. Note how the null 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.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"one\":1,\"three\":3,\"two\":2}\n3 true\n{\"A\":\"a\",\"B\":\"b\"}\n\"b\" false\n
"},{"location":"api/basic_json/emplace/#version-history","title":"Version history","text":""},{"location":"api/basic_json/emplace_back/","title":"nlohmann::basic_json::emplace_back","text":"
template<class... Args>\nreference emplace_back(Args&& ... args);\n

Creates a JSON value from the passed parameters args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from args.

"},{"location":"api/basic_json/emplace_back/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace_back/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace_back/#return-value","title":"Return value","text":"

reference to the inserted element

"},{"location":"api/basic_json/emplace_back/#exceptions","title":"Exceptions","text":"

Throws type_error.311 when called on a type other than JSON array or null; example: \"cannot use emplace_back() with number\"

"},{"location":"api/basic_json/emplace_back/#complexity","title":"Complexity","text":"

Amortized constant.

"},{"location":"api/basic_json/emplace_back/#examples","title":"Examples","text":"Example

The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.

#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

Output:

[1,2,3,4,5]\nnull\n[1,2,3,4,5,6]\n[\"first\",[\"second\",\"second\",\"second\"]]\n
"},{"location":"api/basic_json/emplace_back/#version-history","title":"Version history","text":""},{"location":"api/basic_json/empty/","title":"nlohmann::basic_json::empty","text":"
bool empty() const noexcept;\n

Checks if a JSON value has no elements (i.e. whether its size() is 0).

"},{"location":"api/basic_json/empty/#return-value","title":"Return value","text":"

The return value depends on the different types and is defined as follows:

Value type return value null true boolean false string false number false binary false object result of function object_t::empty() array result of function array_t::empty()"},{"location":"api/basic_json/empty/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/empty/#complexity","title":"Complexity","text":"

Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity.

"},{"location":"api/basic_json/empty/#possible-implementation","title":"Possible implementation","text":"
bool empty() const noexcept\n{\n    return size() == 0;\n}\n
"},{"location":"api/basic_json/empty/#notes","title":"Notes","text":"

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 false in the case of a string.

"},{"location":"api/basic_json/empty/#examples","title":"Examples","text":"Example

The following code uses empty() to check if a JSON object contains any elements.

#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

Output:

true\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\ntrue\nfalse\n
"},{"location":"api/basic_json/empty/#version-history","title":"Version history","text":""},{"location":"api/basic_json/end/","title":"nlohmann::basic_json::end","text":"
iterator end() noexcept;\nconst_iterator end() const noexcept;\n

Returns an iterator to one past the last element.

"},{"location":"api/basic_json/end/#return-value","title":"Return value","text":"

iterator one past the last element

"},{"location":"api/basic_json/end/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/end/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/end/#examples","title":"Examples","text":"Example

The following code shows an example for end().

#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

Output:

5\n
"},{"location":"api/basic_json/end/#version-history","title":"Version history","text":""},{"location":"api/basic_json/erase/","title":"nlohmann::basic_json::erase","text":"
// (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
  1. Removes an element from a JSON value specified by iterator pos. The iterator pos must be valid and dereferenceable. Thus, the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

    If called on a primitive type other than null, the resulting JSON value will be null.

  2. Remove an element range specified by [first; last) from a JSON value. The iterator first does not need to be dereferenceable if first == last: erasing an empty range is a no-op.

    If called on a primitive type other than null, the resulting JSON value will be null.

  3. Removes an element from a JSON object by key.

  4. See 3. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.

  5. Removes an element from a JSON array by index.

"},{"location":"api/basic_json/erase/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/erase/#parameters","title":"Parameters","text":"pos (in) iterator to the element to remove first (in) iterator to the beginning of the range to remove last (in) iterator past the end of the range to remove key (in) object key of the elements to remove idx (in) array index of the element to remove"},{"location":"api/basic_json/erase/#return-value","title":"Return value","text":"
  1. Iterator following the last removed element. If the iterator pos refers to the last element, the end() iterator is returned.
  2. Iterator following the last removed element. If the iterator last refers to the last element, the end() iterator is returned.
  3. Number of elements removed. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
  4. See 3.
  5. (none)
"},{"location":"api/basic_json/erase/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/erase/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: \"iterator out of range\"
  2. The function can throw the following exceptions:
    • Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
    • Throws invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: \"iterators do not fit current value\"
    • Throws invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: \"iterators out of range\"
  3. The function can throw the following exceptions:
    • Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
  4. See 3.
  5. The function can throw the following exceptions:
    • Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
    • Throws out_of_range.401 when idx >= size(); example: \"array index 17 is out of range\"
"},{"location":"api/basic_json/erase/#complexity","title":"Complexity","text":"
  1. The complexity depends on the type:
    • objects: amortized constant
    • arrays: linear in distance between pos and the end of the container
    • strings and binary: linear in the length of the member
    • other types: constant
  2. The complexity depends on the type:
    • objects: log(size()) + std::distance(first, last)
    • arrays: linear in the distance between first and last, plus linear in the distance between last and end of the container
    • strings and binary: linear in the length of the member
    • other types: constant
  3. log(size()) + count(key)
  4. log(size()) + count(key)
  5. Linear in distance between idx and the end of the container.
"},{"location":"api/basic_json/erase/#notes","title":"Notes","text":"
  1. Invalidates iterators and references at or after the point of the erase, including the end() iterator.
  2. (none)
  3. References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
  4. See 3.
  5. (none)
"},{"location":"api/basic_json/erase/#examples","title":"Examples","text":"Example: (1) remove element given an iterator

The example shows the effect of erase() for different JSON types using an iterator.

#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

Output:

null\nnull\nnull\n{\"one\":1}\n[1,2,8,16]\nnull\n
Example: (2) remove elements given an iterator range

The example shows the effect of erase() for different JSON types using an iterator range.

#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

Output:

null\nnull\nnull\n{\"one\":1}\n[1,8,16]\nnull\n
Example: (3) remove element from a JSON object given a key

The example shows the effect of erase() for different JSON types using an object key.

#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

Output:

{\"two\":2}\n1 0\n
Example: (4) remove element from a JSON object given a key using string_view

The example shows the effect of erase() for different JSON types using an object key.

#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

Output:

{\"two\":2}\n1 0\n
Example: (5) remove element from a JSON array given an index

The example shows the effect of erase() using an array index.

#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

Output:

[0,1,3,4,5]\n
"},{"location":"api/basic_json/erase/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added support for binary types in version 3.8.0.
  2. Added in version 1.0.0. Added support for binary types in version 3.8.0.
  3. Added in version 1.0.0.
  4. Added in version 3.11.0.
  5. Added in version 1.0.0.
"},{"location":"api/basic_json/error_handler_t/","title":"nlohmann::basic_json::error_handler_t","text":"
enum class error_handler_t {\n    strict,\n    replace,\n    ignore\n};\n

This enumeration is used in the dump function to choose how to treat decoding errors while serializing a basic_json value. Three values are differentiated:

strict throw a type_error 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

The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.

#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

Output:

[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
"},{"location":"api/basic_json/error_handler_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/exception/","title":"nlohmann::basic_json::exception","text":"
class exception : public std::exception;\n

This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions, see example below.

Subclasses:

"},{"location":"api/basic_json/exception/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/exception/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/exception/#notes","title":"Notes","text":"

To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.

"},{"location":"api/basic_json/exception/#examples","title":"Examples","text":"Example

The following code shows how arbitrary library exceptions can be caught.

#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

Output:

message: [json.exception.out_of_range.403] key 'non-existing' not found\nexception id: 403\n
"},{"location":"api/basic_json/exception/#see-also","title":"See also","text":"

List of exceptions

"},{"location":"api/basic_json/exception/#version-history","title":"Version history","text":""},{"location":"api/basic_json/find/","title":"nlohmann::basic_json::find","text":"
// (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
  1. Finds an element in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, end() is returned.
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/find/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/find/#parameters","title":"Parameters","text":"key (in) key value of the element to search for."},{"location":"api/basic_json/find/#return-value","title":"Return value","text":"

Iterator to an element with a key equivalent to key. If no such element is found or the JSON value is not an object, a past-the-end iterator (see end()) is returned.

"},{"location":"api/basic_json/find/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/find/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

"},{"location":"api/basic_json/find/#notes","title":"Notes","text":"

This method always returns end() when executed on a JSON type that is not an object.

"},{"location":"api/basic_json/find/#examples","title":"Examples","text":"Example: (1) find object element by key

The example shows how find() is used.

#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

Output:

\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n
Example: (2) find object element by key using string_view

The example shows how find() is used.

#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

Output:

\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n
"},{"location":"api/basic_json/find/#see-also","title":"See also","text":""},{"location":"api/basic_json/find/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.
"},{"location":"api/basic_json/flatten/","title":"nlohmann::basic_json::flatten","text":"
basic_json flatten() const;\n

The function creates a JSON object whose keys are JSON pointers (see RFC 6901) and whose values are all primitive (see is_primitive() for more information). The original JSON value can be restored using the unflatten() function.

"},{"location":"api/basic_json/flatten/#return-value","title":"Return value","text":"

an object that maps JSON pointers to primitive values

"},{"location":"api/basic_json/flatten/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/flatten/#complexity","title":"Complexity","text":"

Linear in the size the JSON value.

"},{"location":"api/basic_json/flatten/#notes","title":"Notes","text":"

Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.

"},{"location":"api/basic_json/flatten/#examples","title":"Examples","text":"Example

The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.

#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

Output:

{\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
"},{"location":"api/basic_json/flatten/#see-also","title":"See also","text":""},{"location":"api/basic_json/flatten/#version-history","title":"Version history","text":""},{"location":"api/basic_json/from_bjdata/","title":"nlohmann::basic_json::from_bjdata","text":"
// (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

Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_bjdata/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bjdata/#parameters","title":"Parameters","text":"i (in) an input in BJData format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bjdata/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_bjdata/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_bjdata/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_bjdata/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_bjdata/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in BJData format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_bjdata/#version-history","title":"Version history","text":""},{"location":"api/basic_json/from_bson/","title":"nlohmann::basic_json::from_bson","text":"
// (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

Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_bson/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bson/#parameters","title":"Parameters","text":"i (in) an input in BSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bson/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_bson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_bson/#exceptions","title":"Exceptions","text":"

Throws parse_error.114 if an unsupported BSON record type is encountered.

"},{"location":"api/basic_json/from_bson/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_bson/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in BSON format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_bson/#see-also","title":"See also","text":""},{"location":"api/basic_json/from_bson/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/from_cbor/","title":"nlohmann::basic_json::from_cbor","text":"
// (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

Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_cbor/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_cbor/#parameters","title":"Parameters","text":"i (in) an input in CBOR format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) tag_handler (in) how to treat CBOR tags (optional, error by default); see cbor_tag_handler_t for more information"},{"location":"api/basic_json/from_cbor/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_cbor/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_cbor/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_cbor/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_cbor/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in CBOR format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_cbor/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/from_msgpack/","title":"nlohmann::basic_json::from_msgpack","text":"
// (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

Deserializes a given input to a JSON value using the MessagePack serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_msgpack/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_msgpack/#parameters","title":"Parameters","text":"i (in) an input in MessagePack format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_msgpack/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_msgpack/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_msgpack/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_msgpack/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_msgpack/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in MessagePack format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_msgpack/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/from_ubjson/","title":"nlohmann::basic_json::from_ubjson","text":"
// (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

Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format.

  1. Reads from a compatible input.
  2. Reads from an iterator range.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/from_ubjson/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType a compatible iterator type"},{"location":"api/basic_json/from_ubjson/#parameters","title":"Parameters","text":"i (in) an input in UBJSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_ubjson/#return-value","title":"Return value","text":"

deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/from_ubjson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/from_ubjson/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/from_ubjson/#complexity","title":"Complexity","text":"

Linear in the size of the input.

"},{"location":"api/basic_json/from_ubjson/#examples","title":"Examples","text":"Example

The example shows the deserialization of a byte vector in UBJSON format to a JSON value.

#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"api/basic_json/from_ubjson/#version-history","title":"Version history","text":"

Deprecation

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/front/","title":"nlohmann::basic_json::front","text":"
reference front();\nconst_reference front() const;\n

Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().

"},{"location":"api/basic_json/front/#return-value","title":"Return value","text":"

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.

"},{"location":"api/basic_json/front/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/front/#exceptions","title":"Exceptions","text":"

If the JSON value is null, exception invalid_iterator.214 is thrown.

"},{"location":"api/basic_json/front/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/front/#notes","title":"Notes","text":"

Precondition

The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.

"},{"location":"api/basic_json/front/#examples","title":"Examples","text":"Example

The following code shows an example for front().

#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

Output:

true\n17\n23.42\n1\n1\n\"Hello, world\"\n
"},{"location":"api/basic_json/front/#see-also","title":"See also","text":""},{"location":"api/basic_json/front/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get/","title":"nlohmann::basic_json::get","text":"
// (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
  1. Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.

    The function is equivalent to executing

    ValueType ret;\nJSONSerializer<ValueType>::from_json(*this, ret);\nreturn ret;\n

    This overload is chosen if:

    • ValueType is not basic_json,
    • json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&), and
    • json_serializer<ValueType> does not have a from_json() method of the form ValueType from_json(const basic_json&)

    If the type is not CopyConstructible and not DefaultConstructible, the value is converted by calling the json_serializer<ValueType> from_json() method.

    The function is then equivalent to executing

    return JSONSerializer<ValueTypeCV>::from_json(*this);\n

    This overload is chosen if:

    • ValueType is not basic_json and
    • json_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)

    If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.

  2. Overload for basic_json specializations. The function is equivalent to executing

    return *this;\n

  3. Explicit pointer access to the internally stored JSON value. No copies are made.

"},{"location":"api/basic_json/get/#template-parameters","title":"Template parameters","text":"ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get/#return-value","title":"Return value","text":"
  1. copy of the JSON value, converted to ValueType
  2. a copy of *this, converted into BasicJsonType
  3. pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
"},{"location":"api/basic_json/get/#exceptions","title":"Exceptions","text":"

Depends on what json_serializer<ValueType> from_json() method throws

"},{"location":"api/basic_json/get/#notes","title":"Notes","text":"

Undefined behavior

Writing data to the pointee (overload 3) of the result yields an undefined state.

"},{"location":"api/basic_json/get/#examples","title":"Examples","text":"Example

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 std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.

#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

Output:

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
Example

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 #cpp nullptr is returned if the value and the requested pointer type does not match.

#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

Output:

17 17 17 17\ntrue\n
"},{"location":"api/basic_json/get/#version-history","title":"Version history","text":"
  1. Since version 2.1.0.
  2. Since version 2.1.0. Extended to work with other specializations of basic_json in version 3.2.0.
  3. Since version 1.0.0.
"},{"location":"api/basic_json/get_allocator/","title":"nlohmann::basic_json::get_allocator","text":"
static allocator_type get_allocator();\n

Returns the allocator associated with the container.

"},{"location":"api/basic_json/get_allocator/#return-value","title":"Return value","text":"

associated allocator

"},{"location":"api/basic_json/get_allocator/#examples","title":"Examples","text":"Example

The example shows how get_allocator() is used to created json values.

#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

Output:

\"Hello, world!\"\n
"},{"location":"api/basic_json/get_allocator/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_binary/","title":"nlohmann::basic_json::get_binary","text":"
binary_t& get_binary();\n\nconst binary_t& get_binary() const;\n

Returns a reference to the stored binary value.

"},{"location":"api/basic_json/get_binary/#return-value","title":"Return value","text":"

Reference to binary value.

"},{"location":"api/basic_json/get_binary/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/get_binary/#exceptions","title":"Exceptions","text":"

Throws type_error.302 if the value is not binary

"},{"location":"api/basic_json/get_binary/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/get_binary/#examples","title":"Examples","text":"Example

The following code shows how to query a binary value.

#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

Output:

type: binary, subtype: 42\n
"},{"location":"api/basic_json/get_binary/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_ptr/","title":"nlohmann::basic_json::get_ptr","text":"
template<typename PointerType>\nPointerType get_ptr() noexcept;\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n

Implicit pointer access to the internally stored JSON value. No copies are made.

"},{"location":"api/basic_json/get_ptr/#template-parameters","title":"Template parameters","text":"PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get_ptr/#return-value","title":"Return value","text":"

pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise

"},{"location":"api/basic_json/get_ptr/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/get_ptr/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/get_ptr/#notes","title":"Notes","text":"

Undefined behavior

Writing data to the pointee of the result yields an undefined state.

"},{"location":"api/basic_json/get_ptr/#examples","title":"Examples","text":"Example

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 nullptr is returned if the value and the requested pointer type does not match.

#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

Output:

17 17 17 17\ntrue\n
"},{"location":"api/basic_json/get_ptr/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_ref/","title":"nlohmann::basic_json::get_ref","text":"
template<typename ReferenceType>\nReferenceType get_ref();\n\ntemplate<typename ReferenceType>\nconst ReferenceType get_ref() const;\n

Implicit reference access to the internally stored JSON value. No copies are made.

"},{"location":"api/basic_json/get_ref/#template-parameters","title":"Template parameters","text":"ReferenceType reference type; must be a reference to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Enforced by a static assertion."},{"location":"api/basic_json/get_ref/#return-value","title":"Return value","text":"

reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise

"},{"location":"api/basic_json/get_ref/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/get_ref/#exceptions","title":"Exceptions","text":"

Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: \"incompatible ReferenceType for get_ref, actual type is binary\".

"},{"location":"api/basic_json/get_ref/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/get_ref/#notes","title":"Notes","text":"

Undefined behavior

Writing data to the referee of the result yields an undefined state.

"},{"location":"api/basic_json/get_ref/#examples","title":"Examples","text":"Example

The example shows several calls to get_ref().

#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

Output:

17 17\n[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\n
"},{"location":"api/basic_json/get_ref/#version-history","title":"Version history","text":""},{"location":"api/basic_json/get_to/","title":"nlohmann::basic_json::get_to","text":"
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

Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer<ValueType> from_json() method.

The function is equivalent to executing

ValueType v;\nJSONSerializer<ValueType>::from_json(*this, v);\n

This overload is chosen if:

"},{"location":"api/basic_json/get_to/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"

the input parameter, allowing chaining calls

"},{"location":"api/basic_json/get_to/#exceptions","title":"Exceptions","text":"

Depends on what json_serializer<ValueType> from_json() method throws

"},{"location":"api/basic_json/get_to/#examples","title":"Examples","text":"Example

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 std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map<std::string, json>.

#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

Output:

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
"},{"location":"api/basic_json/get_to/#version-history","title":"Version history","text":""},{"location":"api/basic_json/input_format_t/","title":"nlohmann::basic_json::input_format_t","text":"
enum class input_format_t {\n    json,\n    cbor,\n    msgpack,\n    ubjson,\n    bson,\n    bjdata\n};\n

This enumeration is used in the sax_parse function to choose the input format to parse:

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

The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR.

#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

Output:

binary(val=[...])\n\nresult: true\n
"},{"location":"api/basic_json/input_format_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/insert/","title":"nlohmann::basic_json::insert","text":"
// (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
  1. Inserts element val into array before iterator pos.
  2. Inserts cnt copies of val into array before iterator pos.
  3. Inserts elements from range [first, last) into array before iterator pos.
  4. Inserts elements from initializer list ilist into array before iterator pos.
  5. Inserts elements from range [first, last) into object.
"},{"location":"api/basic_json/insert/#parameters","title":"Parameters","text":"pos (in) iterator before which the content will be inserted; may be the end() iterator val (in) value to insert cnt (in) number of copies of val to insert first (in) begin of the range of elements to insert last (in) end of the range of elements to insert ilist (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"
  1. iterator pointing to the inserted val.
  2. iterator pointing to the first element inserted, or pos if cnt==0
  3. iterator pointing to the first element inserted, or pos if first==last
  4. iterator pointing to the first element inserted, or pos if ilist is empty
  5. (none)
"},{"location":"api/basic_json/insert/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/insert/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
  2. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
  3. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
    • Throws invalid_iterator.211 if first or last are iterators into container for which insert is called; example: \"passed iterators may not belong to container\"
  4. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
  5. The function can throw the following exceptions:
    • Throws type_error.309 if called on JSON values other than objects; example: \"cannot use insert() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
"},{"location":"api/basic_json/insert/#complexity","title":"Complexity","text":"
  1. Constant plus linear in the distance between pos and end of the container.
  2. Linear in cnt plus linear in the distance between pos and end of the container.
  3. Linear in std::distance(first, last) plus linear in the distance between pos and end of the container.
  4. Linear in ilist.size() plus linear in the distance between pos and end of the container.
  5. Logarithmic: O(N*log(size() + N)), where N is the number of elements to insert.
"},{"location":"api/basic_json/insert/#examples","title":"Examples","text":"Example (1): insert element into array

The example shows how insert() is used.

#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

Output:

10\n[1,2,10,3,4]\n
Example (2): insert copies of element into array

The example shows how insert() is used.

#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

Output:

7\n[1,2,7,7,7,7,7,7,7,3,4]\n
Example (3): insert range of elements into array

The example shows how insert() is used.

#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

Output:

\"one\"\n[1,2,3,4,\"one\",\"two\",\"three\",\"four\"]\n
Example (4): insert elements from initializer list into array

The example shows how insert() is used.

#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

Output:

7\n[1,2,3,4,7,8,9]\n
Example (5): insert range of elements into object

The example shows how insert() is used.

#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

Output:

{\"one\":\"eins\",\"two\":\"zwei\"}\n{\"eleven\":\"elf\",\"seventeen\":\"siebzehn\"}\n{\"eleven\":\"elf\",\"one\":\"eins\",\"seventeen\":\"siebzehn\",\"two\":\"zwei\"}\n
"},{"location":"api/basic_json/insert/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0.
  3. Added in version 1.0.0.
  4. Added in version 1.0.0.
  5. Added in version 3.0.0.
"},{"location":"api/basic_json/invalid_iterator/","title":"nlohmann::basic_json::invalid_iterator","text":"
class invalid_iterator : public exception;\n

This exception is thrown if iterators passed to a library function do not match the expected semantics.

Exceptions have ids 2xx (see list of iterator errors).

"},{"location":"api/basic_json/invalid_iterator/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/invalid_iterator/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/invalid_iterator/#examples","title":"Examples","text":"Example

The following code shows how a invalid_iterator exception can be caught.

#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

Output:

message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n
"},{"location":"api/basic_json/invalid_iterator/#see-also","title":"See also","text":""},{"location":"api/basic_json/invalid_iterator/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_array/","title":"nlohmann::basic_json::is_array","text":"
constexpr bool is_array() const noexcept;\n

This function returns true if and only if the JSON value is an array.

"},{"location":"api/basic_json/is_array/#return-value","title":"Return value","text":"

true if type is an array, false otherwise.

"},{"location":"api/basic_json/is_array/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_array/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_array/#examples","title":"Examples","text":"Example

The following code exemplifies is_array() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\n
"},{"location":"api/basic_json/is_array/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_binary/","title":"nlohmann::basic_json::is_binary","text":"
constexpr bool is_binary() const noexcept;\n

This function returns true if and only if the JSON value is binary array.

"},{"location":"api/basic_json/is_binary/#return-value","title":"Return value","text":"

true if type is binary, false otherwise.

"},{"location":"api/basic_json/is_binary/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_binary/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_binary/#examples","title":"Examples","text":"Example

The following code exemplifies is_binary() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\n
"},{"location":"api/basic_json/is_binary/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_boolean/","title":"nlohmann::basic_json::is_boolean","text":"
constexpr bool is_boolean() const noexcept;\n

This function returns true if and only if the JSON value is true or false.

"},{"location":"api/basic_json/is_boolean/#return-value","title":"Return value","text":"

true if type is boolean, false otherwise.

"},{"location":"api/basic_json/is_boolean/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_boolean/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_boolean/#examples","title":"Examples","text":"Example

The following code exemplifies is_boolean() for all JSON types.

#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

Output:

false\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_boolean/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_discarded/","title":"nlohmann::basic_json::is_discarded","text":"
constexpr bool is_discarded() const noexcept;\n

This function returns true for a JSON value if either:

"},{"location":"api/basic_json/is_discarded/#return-value","title":"Return value","text":"

true if type is discarded, false otherwise.

"},{"location":"api/basic_json/is_discarded/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_discarded/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_discarded/#notes","title":"Notes","text":"

Comparisons

Discarded values are never compared equal with operator==. That is, checking whether a JSON value j is discarded will only work via:

j.is_discarded()\n

because

j == json::value_t::discarded\n

will always be false.

Removal during parsing with callback functions

When a value is discarded by a callback function (see parser_callback_t) 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 [null, discarded, false], the array [null, false] is returned. Only if the top-level value is discarded, the return value of the parse call is discarded.

This function will always be false 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.

"},{"location":"api/basic_json/is_discarded/#examples","title":"Examples","text":"Example

The following code exemplifies is_discarded() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_discarded/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_null/","title":"nlohmann::basic_json::is_null","text":"
constexpr bool is_null() const noexcept;\n

This function returns true if and only if the JSON value is null.

"},{"location":"api/basic_json/is_null/#return-value","title":"Return value","text":"

true if type is null, false otherwise.

"},{"location":"api/basic_json/is_null/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_null/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_null/#examples","title":"Examples","text":"Example

The following code exemplifies is_null() for all JSON types.

#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

Output:

true\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_null/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number/","title":"nlohmann::basic_json::is_number","text":"
constexpr bool is_number() const noexcept;\n

This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.

"},{"location":"api/basic_json/is_number/#return-value","title":"Return value","text":"

true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.

"},{"location":"api/basic_json/is_number/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number/#possible-implementation","title":"Possible implementation","text":"
constexpr bool is_number() const noexcept\n{\n    return is_number_integer() || is_number_float();\n}\n
"},{"location":"api/basic_json/is_number/#examples","title":"Examples","text":"Example

The following code exemplifies is_number() for all JSON types.

#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

Output:

false\nfalse\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number_float/","title":"nlohmann::basic_json::is_number_float","text":"
constexpr bool is_number_float() const noexcept;\n

This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.

"},{"location":"api/basic_json/is_number_float/#return-value","title":"Return value","text":"

true if type is a floating-point number, false otherwise.

"},{"location":"api/basic_json/is_number_float/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number_float/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number_float/#examples","title":"Examples","text":"Example

The following code exemplifies is_number_float() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number_float/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number_float/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number_integer/","title":"nlohmann::basic_json::is_number_integer","text":"
constexpr bool is_number_integer() const noexcept;\n

This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.

"},{"location":"api/basic_json/is_number_integer/#return-value","title":"Return value","text":"

true if type is an integer or unsigned integer number, false otherwise.

"},{"location":"api/basic_json/is_number_integer/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number_integer/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number_integer/#examples","title":"Examples","text":"Example

The following code exemplifies is_number_integer() for all JSON types.

#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

Output:

false\nfalse\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number_integer/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number_integer/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_number_unsigned/","title":"nlohmann::basic_json::is_number_unsigned","text":"
constexpr bool is_number_unsigned() const noexcept;\n

This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.

"},{"location":"api/basic_json/is_number_unsigned/#return-value","title":"Return value","text":"

true if type is an unsigned integer number, false otherwise.

"},{"location":"api/basic_json/is_number_unsigned/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_number_unsigned/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_number_unsigned/#examples","title":"Examples","text":"Example

The following code exemplifies is_number_unsigned() for all JSON types.

#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

Output:

false\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_number_unsigned/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_number_unsigned/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_object/","title":"nlohmann::basic_json::is_object","text":"
constexpr bool is_object() const noexcept;\n

This function returns true if and only if the JSON value is an object.

"},{"location":"api/basic_json/is_object/#return-value","title":"Return value","text":"

true if type is an object, false otherwise.

"},{"location":"api/basic_json/is_object/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_object/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_object/#examples","title":"Examples","text":"Example

The following code exemplifies is_object() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/is_object/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_primitive/","title":"nlohmann::basic_json::is_primitive","text":"
constexpr bool is_primitive() const noexcept;\n

This function returns true if and only if the JSON type is primitive (string, number, boolean, null, binary).

"},{"location":"api/basic_json/is_primitive/#return-value","title":"Return value","text":"

true if type is primitive (string, number, boolean, null, or binary), false otherwise.

"},{"location":"api/basic_json/is_primitive/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_primitive/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_primitive/#possible-implementation","title":"Possible implementation","text":"
constexpr bool is_primitive() const noexcept\n{\n    return is_null() || is_string() || is_boolean() || is_number() || is_binary();\n}\n
"},{"location":"api/basic_json/is_primitive/#notes","title":"Notes","text":"

The term primitive stems from RFC 8259:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.

"},{"location":"api/basic_json/is_primitive/#examples","title":"Examples","text":"Example

The following code exemplifies is_primitive() for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\nfalse\nfalse\ntrue\ntrue\n
"},{"location":"api/basic_json/is_primitive/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_primitive/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_string/","title":"nlohmann::basic_json::is_string","text":"
constexpr bool is_string() const noexcept;\n

This function returns true if and only if the JSON value is a string.

"},{"location":"api/basic_json/is_string/#return-value","title":"Return value","text":"

true if type is a string, false otherwise.

"},{"location":"api/basic_json/is_string/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_string/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_string/#examples","title":"Examples","text":"Example

The following code exemplifies is_string() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\n
"},{"location":"api/basic_json/is_string/#version-history","title":"Version history","text":""},{"location":"api/basic_json/is_structured/","title":"nlohmann::basic_json::is_structured","text":"
constexpr bool is_structured() const noexcept;\n

This function returns true if and only if the JSON type is structured (array or object).

"},{"location":"api/basic_json/is_structured/#return-value","title":"Return value","text":"

true if type is structured (array or object), false otherwise.

"},{"location":"api/basic_json/is_structured/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/is_structured/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/is_structured/#possible-implementation","title":"Possible implementation","text":"
constexpr bool is_primitive() const noexcept\n{\n    return is_array() || is_object();\n}\n
"},{"location":"api/basic_json/is_structured/#notes","title":"Notes","text":"

The term structured stems from RFC 8259:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

Note that though strings are containers in C++, they are treated as primitive values in JSON.

"},{"location":"api/basic_json/is_structured/#examples","title":"Examples","text":"Example

The following code exemplifies is_structured() for all JSON types.

#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

Output:

false\nfalse\nfalse\nfalse\nfalse\ntrue\ntrue\nfalse\nfalse\n
"},{"location":"api/basic_json/is_structured/#see-also","title":"See also","text":""},{"location":"api/basic_json/is_structured/#version-history","title":"Version history","text":""},{"location":"api/basic_json/items/","title":"nlohmann::basic_json::items","text":"
iteration_proxy<iterator> items() noexcept;\niteration_proxy<const_iterator> items() const noexcept;\n

This function allows accessing iterator::key() and iterator::value() 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.

For loop without items() function:

for (auto it = j_object.begin(); it != j_object.end(); ++it)\n{\n    std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n}\n

Range-based for loop without items() function:

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

Range-based for loop with items() function:

for (auto& el : j_object.items())\n{\n    std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n

The items() function also allows using structured bindings (C++17):

for (auto& [key, val] : j_object.items())\n{\n    std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n
"},{"location":"api/basic_json/items/#return-value","title":"Return value","text":"

iteration proxy object wrapping the current value with an interface to use in range-based for loops

"},{"location":"api/basic_json/items/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/items/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/items/#notes","title":"Notes","text":"

When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string.

Lifetime issues

Using items() 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.

"},{"location":"api/basic_json/items/#examples","title":"Examples","text":"Example

The following code shows an example for items().

#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

Output:

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
"},{"location":"api/basic_json/items/#version-history","title":"Version history","text":"

Deprecation

This function replaces the static function iterator_wrapper which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function iterator_wrapper will be removed in version 4.0.0. Please replace all occurrences of iterator_wrapper(j) with j.items().

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/json_base_class_t/","title":"nlohmann::basic_json::json_base_class_t","text":"
using json_base_class_t = detail::json_base_class<CustomBaseClass>;\n

The base class used to inject custom functionality into each instance of basic_json. Examples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.

"},{"location":"api/basic_json/json_base_class_t/#template-parameters","title":"Template parameters","text":"CustomBaseClass the base class to be added to basic_json"},{"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":"

The default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.

"},{"location":"api/basic_json/json_base_class_t/#limitations","title":"Limitations","text":"

The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.

"},{"location":"api/basic_json/json_base_class_t/#examples","title":"Examples","text":"Example

The following code shows how to inject custom data and methods for each node.

#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

Output:

/ - 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
"},{"location":"api/basic_json/json_base_class_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/json_serializer/","title":"nlohmann::basic_json::json_serializer","text":"
template<typename T, typename SFINAE>\nusing json_serializer = JSONSerializer<T, SFINAE>;\n
"},{"location":"api/basic_json/json_serializer/#template-parameters","title":"Template parameters","text":"T type to convert; will be used in the to_json/from_json functions SFINAE type to add compile type checks via SFINAE; usually void"},{"location":"api/basic_json/json_serializer/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_serializer/#default-type","title":"Default type","text":"

The default values for json_serializer is adl_serializer.

"},{"location":"api/basic_json/json_serializer/#examples","title":"Examples","text":"Example

The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer.

#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

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
"},{"location":"api/basic_json/json_serializer/#version-history","title":"Version history","text":""},{"location":"api/basic_json/max_size/","title":"nlohmann::basic_json::max_size","text":"
size_type max_size() const noexcept;\n

Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the JSON value.

"},{"location":"api/basic_json/max_size/#return-value","title":"Return value","text":"

The return value depends on the different types and is defined as follows:

Value type return value null 0 (same as size()) boolean 1 (same as size()) string 1 (same as size()) number 1 (same as size()) binary 1 (same as size()) object result of function object_t::max_size() array result of function array_t::max_size()"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/max_size/#complexity","title":"Complexity","text":"

Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.

"},{"location":"api/basic_json/max_size/#notes","title":"Notes","text":"

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 1.

"},{"location":"api/basic_json/max_size/#examples","title":"Examples","text":"Example

The following code calls max_size() on the different value types.

#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

Output:

0\n1\n1\n1\n115292150460684697\n576460752303423487\n1\n

Note the output is platform-dependent.

"},{"location":"api/basic_json/max_size/#version-history","title":"Version history","text":""},{"location":"api/basic_json/merge_patch/","title":"nlohmann::basic_json::merge_patch","text":"
void merge_patch(const basic_json& apply_patch);\n

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.

The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):

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

Thereby, Target is the current object; that is, the patch is applied to the current value.

"},{"location":"api/basic_json/merge_patch/#parameters","title":"Parameters","text":"apply_patch (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"

Linear in the lengths of apply_patch.

"},{"location":"api/basic_json/merge_patch/#examples","title":"Examples","text":"Example

The following code shows how a JSON Merge Patch is applied to a JSON document.

#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

Output:

{\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
"},{"location":"api/basic_json/merge_patch/#see-also","title":"See also","text":""},{"location":"api/basic_json/merge_patch/#version-history","title":"Version history","text":""},{"location":"api/basic_json/meta/","title":"nlohmann::basic_json::meta","text":"
static basic_json meta();\n

This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.

"},{"location":"api/basic_json/meta/#return-value","title":"Return value","text":"

JSON object holding version information

key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown. url The URL of the project as string. version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/meta/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/meta/#examples","title":"Examples","text":"Example

The following code shows an example output of the meta() function.

#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

Output:

{\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

Note the output is platform-dependent.

"},{"location":"api/basic_json/meta/#see-also","title":"See also","text":""},{"location":"api/basic_json/meta/#version-history","title":"Version history","text":""},{"location":"api/basic_json/number_float_t/","title":"nlohmann::basic_json::number_float_t","text":"
using number_float_t = NumberFloatType;\n

The type used to store JSON numbers (floating-point).

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t and number_float_t are used.

To store floating-point numbers in C++, a type is defined by the template parameter NumberFloatType which chooses the type to use.

"},{"location":"api/basic_json/number_float_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_float_t/#default-type","title":"Default type","text":"

With the default values for NumberFloatType (double), the default value for number_float_t is double.

"},{"location":"api/basic_json/number_float_t/#default-behavior","title":"Default behavior","text":""},{"location":"api/basic_json/number_float_t/#limits","title":"Limits","text":"

RFC 8259 states:

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.

This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.

"},{"location":"api/basic_json/number_float_t/#storage","title":"Storage","text":"

Floating-point number values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/number_float_t/#examples","title":"Examples","text":"Example

The following code shows that number_float_t is by default, a typedef to double.

#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

Output:

true\n
"},{"location":"api/basic_json/number_float_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/number_integer_t/","title":"nlohmann::basic_json::number_integer_t","text":"
using number_integer_t = NumberIntegerType;\n

The type used to store JSON numbers (integers).

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t and number_float_t are used.

To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.

"},{"location":"api/basic_json/number_integer_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_integer_t/#default-type","title":"Default type","text":"

With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t.

"},{"location":"api/basic_json/number_integer_t/#default-behavior","title":"Default behavior","text":""},{"location":"api/basic_json/number_integer_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (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 number_unsigned_t or number_float_t.

RFC 8259 further states:

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.

As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.

"},{"location":"api/basic_json/number_integer_t/#storage","title":"Storage","text":"

Integer number values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/number_integer_t/#examples","title":"Examples","text":"Example

The following code shows that number_integer_t is by default, a typedef to std::int64_t.

#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

Output:

true\n
"},{"location":"api/basic_json/number_integer_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/number_unsigned_t/","title":"nlohmann::basic_json::number_unsigned_t","text":"
using number_unsigned_t = NumberUnsignedType;\n

The type used to store JSON numbers (unsigned).

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t and number_float_t are used.

To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.

"},{"location":"api/basic_json/number_unsigned_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/number_unsigned_t/#default-type","title":"Default type","text":"

With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t.

"},{"location":"api/basic_json/number_unsigned_t/#default-behavior","title":"Default behavior","text":""},{"location":"api/basic_json/number_unsigned_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. 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 number_integer_t or number_float_t.

RFC 8259 further states:

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.

As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.

"},{"location":"api/basic_json/number_unsigned_t/#storage","title":"Storage","text":"

Integer number values are stored directly inside a basic_json type.

"},{"location":"api/basic_json/number_unsigned_t/#examples","title":"Examples","text":"Example

The following code shows that number_unsigned_t is by default, a typedef to std::uint64_t.

#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

Output:

true\n
"},{"location":"api/basic_json/number_unsigned_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/object/","title":"nlohmann::basic_json::object","text":"
static basic_json object(initializer_list_t init = {});\n

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 {} is created.

"},{"location":"api/basic_json/object/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"

JSON object value

"},{"location":"api/basic_json/object/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/object/#exceptions","title":"Exceptions","text":"

Throws type_error.301 if init 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 basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list init. See example below.

"},{"location":"api/basic_json/object/#complexity","title":"Complexity","text":"

Linear in the size of init.

"},{"location":"api/basic_json/object/#notes","title":"Notes","text":"

This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t).

"},{"location":"api/basic_json/object/#examples","title":"Examples","text":"Example

The following code shows an example for the object function.

#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

Output:

{}\n{}\n{\"one\":1,\"two\":2}\n[json.exception.type_error.301] cannot create object from initializer list\n
"},{"location":"api/basic_json/object/#see-also","title":"See also","text":""},{"location":"api/basic_json/object/#version-history","title":"Version history","text":""},{"location":"api/basic_json/object_comparator_t/","title":"nlohmann::basic_json::object_comparator_t","text":"
using object_comparator_t = typename object_t::key_compare;\n// or\nusing object_comparator_t = default_object_comparator_t;\n

The comparator used by object_t. Defined as typename object_t::key_compare if available, and default_object_comparator_t otherwise.

"},{"location":"api/basic_json/object_comparator_t/#examples","title":"Examples","text":"Example

The example below demonstrates the used object comparator.

#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

Output:

json::object_comparator_t(\"one\", \"two\") = true\njson::object_comparator_t(\"three\", \"four\") = false\n
"},{"location":"api/basic_json/object_comparator_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/object_t/","title":"nlohmann::basic_json::object_t","text":"
using object_t = ObjectType<StringType,\n                            basic_json,\n                            default_object_comparator_t,\n                            AllocatorType<std::pair<const StringType, basic_json>>>;\n

The type used to store JSON objects.

RFC 8259 describes JSON objects as follows:

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.

To store objects in C++, a type is defined by the template parameters described below.

"},{"location":"api/basic_json/object_t/#template-parameters","title":"Template parameters","text":"ObjectType the container to store objects (e.g., std::map or std::unordered_map) StringType the type of the keys or names (e.g., std::string). The comparison function std::less<StringType> is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/object_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/object_t/#default-type","title":"Default type","text":"

With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:

// 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

See default_object_comparator_t for more information.

"},{"location":"api/basic_json/object_t/#behavior","title":"Behavior","text":"

The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:

"},{"location":"api/basic_json/object_t/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON object.

"},{"location":"api/basic_json/object_t/#storage","title":"Storage","text":"

Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.

"},{"location":"api/basic_json/object_t/#object-key-order","title":"Object key order","text":"

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 std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.

"},{"location":"api/basic_json/object_t/#examples","title":"Examples","text":"Example

The following code shows that object_t is by default, a typedef to std::map<json::string_t, json>.

#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

Output:

true\n
"},{"location":"api/basic_json/object_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/operator%2B%3D/","title":"nlohmann::basic_json::operator+=","text":"
// (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
  1. Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.

  2. Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.

  3. This function allows using operator+= with an initializer list. In case

    1. the current value is an object,
    2. the initializer list init contains only two elements, and
    3. the first element of init is a string,

    init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).

"},{"location":"api/basic_json/operator%2B%3D/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"

*this

"},{"location":"api/basic_json/operator%2B%3D/#exceptions","title":"Exceptions","text":"

All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use operator+=() with number\"

"},{"location":"api/basic_json/operator%2B%3D/#complexity","title":"Complexity","text":"
  1. Amortized constant.
  2. Logarithmic in the size of the container, O(log(size())).
  3. Linear in the size of the initializer list init.
"},{"location":"api/basic_json/operator%2B%3D/#notes","title":"Notes","text":"

(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.

"},{"location":"api/basic_json/operator%2B%3D/#examples","title":"Examples","text":"Example: (1) add element to array

The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.

#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

Output:

[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n
Example: (2) add element to object

The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n
Example: (3) add to object from initializer list

The example shows how initializer lists are treated as objects when possible.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n
"},{"location":"api/basic_json/operator%2B%3D/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.0.0.
"},{"location":"api/basic_json/operator%3D/","title":"nlohmann::basic_json::operator=","text":"
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

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 swap() member function.

"},{"location":"api/basic_json/operator%3D/#parameters","title":"Parameters","text":"other (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator%3D/#examples","title":"Examples","text":"Example

The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.

#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

Output:

23\n23\n
"},{"location":"api/basic_json/operator%3D/#version-history","title":"Version history","text":""},{"location":"api/basic_json/operator%5B%5D/","title":"nlohmann::basic_json::operator[]","text":"
// (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
  1. Returns a reference to the array element at specified location idx.
  2. Returns a reference to the object element with specified key key. The non-const qualified overload takes the key by value.
  3. See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
  4. Returns a reference to the element with specified JSON pointer ptr.
"},{"location":"api/basic_json/operator%5B%5D/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the element to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"
  1. (const) reference to the element at index idx
  2. (const) reference to the element at key key
  3. (const) reference to the element at key key
  4. (const) reference to the element pointed to by ptr
"},{"location":"api/basic_json/operator%5B%5D/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/operator%5B%5D/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense.
  2. The function can throw the following exceptions:
    • Throws type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense.
  3. See 2.
  4. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'.
    • Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number.
    • Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version.
    • Throws out_of_range.404 if the JSON pointer ptr can not be resolved.
"},{"location":"api/basic_json/operator%5B%5D/#complexity","title":"Complexity","text":"
  1. Constant if idx is in the range of the array. Otherwise, linear in idx - size().
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
  4. Logarithmic in the size of the container.
"},{"location":"api/basic_json/operator%5B%5D/#notes","title":"Notes","text":"

Undefined behavior and runtime assertions

  1. If the element with key idx does not exist, the behavior is undefined.
  2. If the element with key key does not exist, the behavior is undefined and is guarded by a runtime assertion!
  1. The non-const version may add values: If idx is beyond the range of the array (i.e., idx >= size()), then the array is silently filled up with null values to make idx a valid reference to the last stored element. In case the value was null before, it is converted to an array.

  2. If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.

  3. See 2.

  4. null values are created in arrays and objects if necessary.

    In particular:

    • If the JSON pointer points to an object key that does not exist, it is created and filled with a null value before a reference to it is returned.
    • If the JSON pointer points to an array index that does not exist, it is created and filled with a null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.
    • The special value - is treated as a synonym for the index past the end.
"},{"location":"api/basic_json/operator%5B%5D/#examples","title":"Examples","text":"Example: (1) access specified array element

The example below shows how array elements can be read and written using [] operator. Note the addition of null values.

#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

Output:

4\n[1,2,3,4,6]\n[1,2,3,4,6,null,null,null,null,null,11]\n
Example: (1) access specified array element (const)

The example below shows how array elements can be read using the [] operator.

#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

Output:

\"third\"\n
Example: (2) access specified object element

The example below shows how object elements can be read and written using the [] operator.

#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

Output:

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
Example: (2) access specified object element (const)

The example below shows how object elements can be read using the [] operator.

#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

Output:

2\n
Example: (3) access specified object element using string_view

The example below shows how object elements can be read using the [] operator.

#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

Output:

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
Example: (3) access specified object element using string_view (const)

The example below shows how object elements can be read using the [] operator.

#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

Output:

2\n
Example: (4) access specified element via JSON Pointer

The example below shows how values can be read and written using JSON Pointers.

#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

Output:

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
Example: (4) access specified element via JSON Pointer (const)

The example below shows how values can be read using JSON Pointers.

#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

Output:

1\n\"foo\"\n[1,2]\n2\n
"},{"location":"api/basic_json/operator%5B%5D/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator%5B%5D/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0. Added overloads for T* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0.
  3. Added in version 3.11.0.
  4. Added in version 2.0.0.
"},{"location":"api/basic_json/operator_ValueType/","title":"nlohmann::basic_json::operator ValueType","text":"
template<typename ValueType>\nJSON_EXPLICIT operator ValueType() const;\n

Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.

"},{"location":"api/basic_json/operator_ValueType/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"

copy of the JSON value, converted to ValueType

"},{"location":"api/basic_json/operator_ValueType/#exceptions","title":"Exceptions","text":"

Depends on what json_serializer<ValueType> from_json() method throws

"},{"location":"api/basic_json/operator_ValueType/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value.

"},{"location":"api/basic_json/operator_ValueType/#notes","title":"Notes","text":"

Definition of JSON_EXPLICIT

By default JSON_EXPLICIT is defined to the empty string, so the signature is:

template<typename ValueType>\noperator ValueType() const;\n

If JSON_USE_IMPLICIT_CONVERSIONS is set to 0, JSON_EXPLICIT is defined to explicit:

template<typename ValueType>\nexplicit operator ValueType() const;\n

That is, implicit conversions can be switched off by defining JSON_USE_IMPLICIT_CONVERSIONS to 0.

Future behavior change

Implicit conversions will be switched off by default in the next major release of the library. That is, JSON_EXPLICIT will be set to explicit by default.

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.

"},{"location":"api/basic_json/operator_ValueType/#examples","title":"Examples","text":"Example

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 std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.

#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

Output:

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
"},{"location":"api/basic_json/operator_ValueType/#version-history","title":"Version history","text":""},{"location":"api/basic_json/operator_eq/","title":"nlohmann::basic_json::operator==","text":"
// 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
  1. Compares two JSON values for equality according to the following rules:

    • 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 operator==.
    • Integer and floating-point numbers are automatically converted before comparison.
  2. 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.

"},{"location":"api/basic_json/operator_eq/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are equal

"},{"location":"api/basic_json/operator_eq/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_eq/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_eq/#notes","title":"Notes","text":"

Comparing special values

Comparing floating-point numbers

Floating-point numbers inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default. To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance

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

Or you can self-defined operator equal function like this:

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

Comparing different basic_json specializations

Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects

{\n   \"version\": 1,\n   \"type\": \"integer\"\n}\n

and

{\n   \"type\": \"integer\",\n   \"version\": 1\n}\n

depends on whether nlohmann::json or nlohmann::ordered_json is used:

#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

Output:

true\nfalse\n
"},{"location":"api/basic_json/operator_eq/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
Example

The example demonstrates comparing several JSON types against the null pointer (JSON null).

#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

Output:

[1,2,3] == nullptr false\n{\"A\":\"a\",\"B\":\"b\"} == nullptr false\n17 == nullptr false\n\"foo\" == nullptr false\nnull == nullptr true\n
"},{"location":"api/basic_json/operator_eq/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
  2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
"},{"location":"api/basic_json/operator_ge/","title":"nlohmann::basic_json::operator>=","text":"
// 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
  1. Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(lhs < rhs) (see operator<).
  2. 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.

"},{"location":"api/basic_json/operator_ge/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"

whether lhs is less than or equal to rhs

"},{"location":"api/basic_json/operator_ge/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_ge/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_ge/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_ge/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_ge/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_ge/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_gt/","title":"nlohmann::basic_json::operator>","text":"
// 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
  1. Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(lhs <= rhs) (see operator<=).
  2. 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.

"},{"location":"api/basic_json/operator_gt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"

whether lhs is greater than rhs

"},{"location":"api/basic_json/operator_gt/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_gt/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_gt/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_gt/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_gt/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_gt/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_le/","title":"nlohmann::basic_json::operator<=","text":"
// 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
  1. Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(rhs < lhs) (see operator<).
  2. 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.

"},{"location":"api/basic_json/operator_le/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"

whether lhs is less than or equal to rhs

"},{"location":"api/basic_json/operator_le/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_le/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_le/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_le/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_le/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_le/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_lt/","title":"nlohmann::basic_json::operator<","text":"
// 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
  1. Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:

    • If either operand is discarded, the comparison yields false.
    • If both operands have the same type, the values are compared using their respective operator<.
    • Integer and floating-point numbers are automatically converted before comparison.
    • In case lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:
      1. null
      2. boolean
      3. number (all types)
      4. object
      5. array
      6. string
      7. binary For instance, any boolean value is considered less than any string.
  2. 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.

"},{"location":"api/basic_json/operator_lt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"

whether lhs is less than rhs

"},{"location":"api/basic_json/operator_lt/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_lt/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_lt/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.

"},{"location":"api/basic_json/operator_lt/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
"},{"location":"api/basic_json/operator_lt/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_lt/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
  2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
"},{"location":"api/basic_json/operator_ne/","title":"nlohmann::basic_json::operator!=","text":"
// 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
  1. Compares two JSON values for inequality according to the following rules:

    • The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
    • Otherwise, returns the result of !(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).
  2. 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.

"},{"location":"api/basic_json/operator_ne/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are not equal

"},{"location":"api/basic_json/operator_ne/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_ne/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_ne/#notes","title":"Notes","text":"

Comparing NaN

NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.

"},{"location":"api/basic_json/operator_ne/#examples","title":"Examples","text":"Example

The example demonstrates comparing several JSON types.

#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

Output:

[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
Example

The example demonstrates comparing several JSON types against the null pointer (JSON null).

#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

Output:

[1,2,3] != nullptr true\n{\"A\":\"a\",\"B\":\"b\"} != nullptr true\n17 != nullptr true\n\"foo\" != nullptr true\nnull != nullptr false\n
"},{"location":"api/basic_json/operator_ne/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
  2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
"},{"location":"api/basic_json/operator_spaceship/","title":"nlohmann::basic_json::operator<=>","text":"
// 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
  1. 3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:

    • Two JSON values compare with a result of std::partial_ordering::unordered if either value is discarded.
    • If both JSON values are of the same type, the result is produced by 3-way comparing their stored values using their respective operator<=>.
    • Integer and floating-point numbers are converted to their common type and then 3-way compared using their respective operator<=>. 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.
    • Otherwise, yields a result by comparing the type (see value_t).
  2. 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).

"},{"location":"api/basic_json/operator_spaceship/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"rhs (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"

the std::partial_ordering of the 3-way comparison of *this and rhs

"},{"location":"api/basic_json/operator_spaceship/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/operator_spaceship/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/operator_spaceship/#notes","title":"Notes","text":"

Comparing NaN

"},{"location":"api/basic_json/operator_spaceship/#examples","title":"Examples","text":"Example: (1) comparing JSON values

The example demonstrates comparing several JSON values.

#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

Output:

[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
Example: (2) comparing JSON values and scalars

The example demonstrates comparing several JSON values and scalars.

#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

Output:

false <=> true := less\n17 <=> 17.000000 := equivalent\n17 <=> nan := unordered\n\"17\" <=> 17 := greater\n
"},{"location":"api/basic_json/operator_spaceship/#see-also","title":"See also","text":""},{"location":"api/basic_json/operator_spaceship/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 3.11.0.
"},{"location":"api/basic_json/operator_value_t/","title":"nlohmann::basic_json::operator value_t","text":"
constexpr operator value_t() const noexcept;\n

Return the type of the JSON value as a value from the value_t enumeration.

"},{"location":"api/basic_json/operator_value_t/#return-value","title":"Return value","text":"

the type of the JSON value

Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/operator_value_t/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/operator_value_t/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/operator_value_t/#examples","title":"Examples","text":"Example

The following code exemplifies operator value_t() for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n
"},{"location":"api/basic_json/operator_value_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/other_error/","title":"nlohmann::basic_json::other_error","text":"
class other_error : public exception;\n

This exception is thrown in case of errors that cannot be classified with the other exception types.

Exceptions have ids 5xx (see list of other errors).

"},{"location":"api/basic_json/other_error/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/other_error/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/other_error/#examples","title":"Examples","text":"Example

The following code shows how a other_error exception can be caught.

#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

Output:

message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n
"},{"location":"api/basic_json/other_error/#see-also","title":"See also","text":""},{"location":"api/basic_json/other_error/#version-history","title":"Version history","text":""},{"location":"api/basic_json/out_of_range/","title":"nlohmann::basic_json::out_of_range","text":"
class out_of_range : public exception;\n

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.

Exceptions have ids 4xx (see list of out-of-range errors).

"},{"location":"api/basic_json/out_of_range/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/out_of_range/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/out_of_range/#examples","title":"Examples","text":"Example

The following code shows how a out_of_range exception can be caught.

#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

Output:

message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n
"},{"location":"api/basic_json/out_of_range/#see-also","title":"See also","text":""},{"location":"api/basic_json/out_of_range/#version-history","title":"Version history","text":""},{"location":"api/basic_json/parse/","title":"nlohmann::basic_json::parse","text":"
// (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
  1. Deserialize from a compatible input.
  2. Deserialize from a pair of character iterators

    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.

"},{"location":"api/basic_json/parse/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType

a compatible iterator type, for instance.

"},{"location":"api/basic_json/parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. cb (in) a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"

Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.

"},{"location":"api/basic_json/parse/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/parse/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/parse/#complexity","title":"Complexity","text":"

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 cb or reading from (1) the input i or (2) the iterator range [first, last] has a super-linear complexity.

"},{"location":"api/basic_json/parse/#notes","title":"Notes","text":"

(1) A UTF-8 byte order mark is silently ignored.

Runtime assertion

The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion.

"},{"location":"api/basic_json/parse/#examples","title":"Examples","text":"Parsing from a character array

The example below demonstrates the parse() function reading from an array.

#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

Output:

{\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
Parsing from a string

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
Parsing from an input stream

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
Parsing from a contiguous container

The example below demonstrates the parse() function reading from a contiguous container.

#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

Output:

[\n    1,\n    2,\n    3\n]\n
Parsing from a non null-terminated string

The example below demonstrates the parse() function reading from a string that is not null-terminated.

#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

Output:

[\n    1,\n    2,\n    3\n]\n
Parsing from an iterator pair

The example below demonstrates the parse() function reading from an iterator pair.

#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

Output:

[\n    1,\n    2,\n    3\n]\n
Effect of allow_exceptions parameter

The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function.

#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

Output:

[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
"},{"location":"api/basic_json/parse/#see-also","title":"See also","text":""},{"location":"api/basic_json/parse/#version-history","title":"Version history","text":"

Deprecation

Overload (2) replaces calls to parse 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 parse({ptr, ptr+len}, ...); with parse(ptr, ptr+len, ...);.

You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.

"},{"location":"api/basic_json/parse_error/","title":"nlohmann::basic_json::parse_error","text":"
class parse_error : public exception;\n

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.

Member byte holds the byte index of the last read character in the input file (see note below).

Exceptions have ids 1xx (see list of parse errors).

"},{"location":"api/basic_json/parse_error/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/parse_error/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/parse_error/#notes","title":"Notes","text":"

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.

"},{"location":"api/basic_json/parse_error/#examples","title":"Examples","text":"Example

The following code shows how a parse_error exception can be caught.

#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

Output:

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
"},{"location":"api/basic_json/parse_error/#see-also","title":"See also","text":""},{"location":"api/basic_json/parse_error/#version-history","title":"Version history","text":""},{"location":"api/basic_json/parse_event_t/","title":"nlohmann::basic_json::parse_event_t","text":"
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

The parser callback distinguishes the following events:

"},{"location":"api/basic_json/parse_event_t/#examples","title":"Examples","text":""},{"location":"api/basic_json/parse_event_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/parser_callback_t/","title":"nlohmann::basic_json::parser_callback_t","text":"
template<typename BasicJsonType>\nusing parser_callback_t =\n    std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n

With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.

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 depth, event, and parsed.

parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value

Discarding a value (i.e., returning false) has different effects depending on the context in which function was called:

"},{"location":"api/basic_json/parser_callback_t/#parameters","title":"Parameters","text":"depth (in) the depth of the recursion during parsing event (in) an event of type parse_event_t indicating the context in the callback function has been called parsed (in, out) the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"

Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.

"},{"location":"api/basic_json/parser_callback_t/#examples","title":"Examples","text":"Example

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
"},{"location":"api/basic_json/parser_callback_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/patch/","title":"nlohmann::basic_json::patch","text":"
basic_json patch(const basic_json& json_patch) const;\n

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.

"},{"location":"api/basic_json/patch/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch/#return-value","title":"Return value","text":"

patched document

"},{"location":"api/basic_json/patch/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/patch/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/patch/#complexity","title":"Complexity","text":"

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.

"},{"location":"api/basic_json/patch/#notes","title":"Notes","text":"

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.

"},{"location":"api/basic_json/patch/#examples","title":"Examples","text":"Example

The following code shows how a JSON patch is applied to a value.

#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

Output:

{\n    \"baz\": \"qux\",\n    \"foo\": \"bar\"\n}\n\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"api/basic_json/patch/#see-also","title":"See also","text":""},{"location":"api/basic_json/patch/#version-history","title":"Version history","text":""},{"location":"api/basic_json/patch_inplace/","title":"nlohmann::basic_json::patch_inplace","text":"
void patch_inplace(const basic_json& json_patch) const;\n

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.

"},{"location":"api/basic_json/patch_inplace/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch_inplace/#exception-safety","title":"Exception safety","text":"

No guarantees, value may be corrupted by an unsuccessful patch operation.

"},{"location":"api/basic_json/patch_inplace/#exceptions","title":"Exceptions","text":""},{"location":"api/basic_json/patch_inplace/#complexity","title":"Complexity","text":"

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.

"},{"location":"api/basic_json/patch_inplace/#notes","title":"Notes","text":"

Unlike patch, patch_inplace 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.

"},{"location":"api/basic_json/patch_inplace/#examples","title":"Examples","text":"Example

The following code shows how a JSON patch is applied to a value.

#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

Output:

Before\n{\n    \"baz\": \"qux\",\n    \"foo\": \"bar\"\n}\n\nAfter\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"api/basic_json/patch_inplace/#see-also","title":"See also","text":""},{"location":"api/basic_json/patch_inplace/#version-history","title":"Version history","text":""},{"location":"api/basic_json/push_back/","title":"nlohmann::basic_json::push_back","text":"
// (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
  1. Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.

  2. Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.

  3. This function allows using push_back with an initializer list. In case

    1. the current value is an object,
    2. the initializer list init contains only two elements, and
    3. the first element of init is a string,

    init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).

"},{"location":"api/basic_json/push_back/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"

All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use push_back() with number\"

"},{"location":"api/basic_json/push_back/#complexity","title":"Complexity","text":"
  1. Amortized constant.
  2. Logarithmic in the size of the container, O(log(size())).
  3. Linear in the size of the initializer list init.
"},{"location":"api/basic_json/push_back/#notes","title":"Notes","text":"

(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.

"},{"location":"api/basic_json/push_back/#examples","title":"Examples","text":"Example: (1) add element to array

The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.

#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

Output:

[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n
Example: (2) add element to object

The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n
Example: (3) add to object from initializer list

The example shows how initializer lists are treated as objects when possible.

#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

Output:

{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n
"},{"location":"api/basic_json/push_back/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.0.0.
"},{"location":"api/basic_json/rbegin/","title":"nlohmann::basic_json::rbegin","text":"
reverse_iterator rbegin() noexcept;\nconst_reverse_iterator rbegin() const noexcept;\n

Returns an iterator to the reverse-beginning; that is, the last element.

"},{"location":"api/basic_json/rbegin/#return-value","title":"Return value","text":"

reverse iterator to the first element

"},{"location":"api/basic_json/rbegin/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/rbegin/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/rbegin/#examples","title":"Examples","text":"Example

The following code shows an example for rbegin().

#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

Output:

5\n
"},{"location":"api/basic_json/rbegin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/rend/","title":"nlohmann::basic_json::rend","text":"
reverse_iterator rend() noexcept;\nconst_reverse_iterator rend() const noexcept;\n

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.

"},{"location":"api/basic_json/rend/#return-value","title":"Return value","text":"

reverse iterator to the element following the last element

"},{"location":"api/basic_json/rend/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/rend/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/rend/#examples","title":"Examples","text":"Example

The following code shows an example for eend().

#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

Output:

1\n
"},{"location":"api/basic_json/rend/#version-history","title":"Version history","text":""},{"location":"api/basic_json/sax_parse/","title":"nlohmann::basic_json::sax_parse","text":"
// (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

Read from input and generate SAX events

  1. Read from a compatible input.
  2. Read from a pair of character iterators

    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.

The SAX event lister must follow the interface of json_sax.

"},{"location":"api/basic_json/sax_parse/#template-parameters","title":"Template parameters","text":"InputType

A compatible input, for instance:

IteratorType Description SAX Description"},{"location":"api/basic_json/sax_parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. sax (in) SAX event listener format (in) the format to parse (JSON, CBOR, MessagePack, or UBJSON) (optional, input_format_t::json by default), see input_format_t for more information strict (in) whether the input has to be consumed completely (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/sax_parse/#return-value","title":"Return value","text":"

return value of the last processed SAX event

"},{"location":"api/basic_json/sax_parse/#exception-safety","title":"Exception safety","text":""},{"location":"api/basic_json/sax_parse/#complexity","title":"Complexity","text":"

Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.

"},{"location":"api/basic_json/sax_parse/#notes","title":"Notes","text":"

A UTF-8 byte order mark is silently ignored.

"},{"location":"api/basic_json/sax_parse/#examples","title":"Examples","text":"Example

The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer.

#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

Output:

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
"},{"location":"api/basic_json/sax_parse/#version-history","title":"Version history","text":"

Deprecation

Overload (2) replaces calls to sax_parse 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 sax_parse({ptr, ptr+len}); with sax_parse(ptr, ptr+len);.

"},{"location":"api/basic_json/size/","title":"nlohmann::basic_json::size","text":"
size_type size() const noexcept;\n

Returns the number of elements in a JSON value.

"},{"location":"api/basic_json/size/#return-value","title":"Return value","text":"

The return value depends on the different types and is defined as follows:

Value type return value null 0 boolean 1 string 1 number 1 binary 1 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":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/basic_json/size/#complexity","title":"Complexity","text":"

Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.

"},{"location":"api/basic_json/size/#notes","title":"Notes","text":"

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 1 in the case of a string.

"},{"location":"api/basic_json/size/#examples","title":"Examples","text":"Example

The following code calls size() on the different value types.

#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

Output:

0\n1\n1\n1\n2\n0\n5\n0\n1\n
"},{"location":"api/basic_json/size/#version-history","title":"Version history","text":""},{"location":"api/basic_json/std_hash/","title":"std::hash<nlohmann::basic_json>","text":"
namespace std {\n    struct hash<nlohmann::basic_json>;\n}\n

Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.

"},{"location":"api/basic_json/std_hash/#examples","title":"Examples","text":"Example

The example shows how to calculate hash values for different JSON values.

#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

Output:

hash(null) = 2654435769\nhash(false) = 2654436030\nhash(0) = 2654436095\nhash(0U) = 2654436156\nhash(\"\") = 6142509191626859748\nhash({}) = 2654435832\nhash([]) = 2654435899\nhash({\"hello\": \"world\"}) = 4469488738203676328\n

Note the output is platform-dependent.

"},{"location":"api/basic_json/std_hash/#version-history","title":"Version history","text":""},{"location":"api/basic_json/std_swap/","title":"std::swap<basic_json>","text":"
namespace std {\n    void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2);\n}\n

Exchanges the values of two JSON objects.

"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"
void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2)\n{\n    j1.swap(j2);\n}\n
"},{"location":"api/basic_json/std_swap/#examples","title":"Examples","text":"Example

The following code shows how two values are swapped with std::swap.

#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

Output:

j1 = {\"one\":1,\"two\":2} | j2 = [1,2,4,8,16]\nj1 = [1,2,4,8,16] | j2 = {\"one\":1,\"two\":2}\n
"},{"location":"api/basic_json/std_swap/#see-also","title":"See also","text":""},{"location":"api/basic_json/std_swap/#version-history","title":"Version history","text":""},{"location":"api/basic_json/string_t/","title":"nlohmann::basic_json::string_t","text":"
using string_t = StringType;\n

The type used to store JSON strings.

RFC 8259 describes JSON strings as follows:

A string is a sequence of zero or more Unicode characters.

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.

"},{"location":"api/basic_json/string_t/#template-parameters","title":"Template parameters","text":"StringType the container to store strings (e.g., std::string). 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":"

With the default values for StringType (std::string), the default value for string_t is std::string.

"},{"location":"api/basic_json/string_t/#encoding","title":"Encoding","text":"

Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.

"},{"location":"api/basic_json/string_t/#string-comparison","title":"String comparison","text":"

RFC 8259 states:

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 \"a\\\\b\" and \"a\\u005Cb\" are not equal.

This implementation is interoperable as it does compare strings code unit by code unit.

"},{"location":"api/basic_json/string_t/#storage","title":"Storage","text":"

String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.

"},{"location":"api/basic_json/string_t/#examples","title":"Examples","text":"Example

The following code shows that string_t is by default, a typedef to std::string.

#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

Output:

true\n
"},{"location":"api/basic_json/string_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/swap/","title":"nlohmann::basic_json::swap","text":"
// (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
  1. Exchanges the contents of the JSON value with those of other. 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.
  2. Exchanges the contents of the JSON value from left with those of right. 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.
  3. Exchanges the contents of a JSON array with those of other. 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.
  4. Exchanges the contents of a JSON object with those of other. 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.
  5. Exchanges the contents of a JSON string with those of other. 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.
  6. Exchanges the contents of a binary value with those of other. 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.
  7. Exchanges the contents of a binary value with those of other. 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.
"},{"location":"api/basic_json/swap/#parameters","title":"Parameters","text":"other (in, out) value to exchange the contents with left (in, out) value to exchange the contents with right (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"
  1. No-throw guarantee: this function never throws exceptions.
  2. No-throw guarantee: this function never throws exceptions.
  3. Throws type_error.310 if called on JSON values other than arrays; example: \"cannot use swap() with boolean\"
  4. Throws type_error.310 if called on JSON values other than objects; example: \"cannot use swap() with boolean\"
  5. Throws type_error.310 if called on JSON values other than strings; example: \"cannot use swap() with boolean\"
  6. Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
  7. Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
"},{"location":"api/basic_json/swap/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/swap/#examples","title":"Examples","text":"Example: Swap JSON value (1, 2)

The example below shows how JSON values can be swapped with swap().

#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

Output:

j1 = {\"e\":2.718281828459045,\"pi\":3.141592653589793}\nj2 = [1,2,3,4,5]\n
Example: Swap array (3)

The example below shows how arrays can be swapped with swap().

#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

Output:

value = {\"array\":[\"Snap\",\"Crackle\",\"Pop\"]}\narray = [1,2,3,4]\n
Example: Swap object (4)

The example below shows how objects can be swapped with swap().

#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

Output:

value = {\"translation\":{\"cow\":\"Kuh\",\"dog\":\"Hund\"}}\nobject = {\"one\":\"eins\",\"two\":\"zwei\"}\n
Example: Swap string (5)

The example below shows how strings can be swapped with swap().

#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

Output:

value = [\"the good\",\"the fast\",\"the ugly\"]\nstring = the bad\n
Example: Swap string (6)

The example below shows how binary values can be swapped with swap().

#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

Output:

value = {\"bytes\":[4,5,6],\"subtype\":null}\nbinary = {\"bytes\":[1,2,3],\"subtype\":null}\n
"},{"location":"api/basic_json/swap/#see-also","title":"See also","text":""},{"location":"api/basic_json/swap/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 1.0.0.
  4. Since version 1.0.0.
  5. Since version 1.0.0.
  6. Since version 3.8.0.
  7. Since version 3.8.0.
"},{"location":"api/basic_json/to_bjdata/","title":"nlohmann::basic_json::to_bjdata","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the BJData serialization.
  2. Writes the BJData serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"
  1. BJData serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_bjdata/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_bjdata/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_bjdata/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in BJData format.

#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"api/basic_json/to_bjdata/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_bson/","title":"nlohmann::basic_json::to_bson","text":"
// (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

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).

  1. Returns a byte vector containing the BSON serialization.
  2. Writes the BSON serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"
  1. BSON serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_bson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_bson/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_bson/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in BSON format.

#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

Output:

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
"},{"location":"api/basic_json/to_bson/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_cbor/","title":"nlohmann::basic_json::to_cbor","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the CBOR serialization.
  2. Writes the CBOR serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"
  1. CBOR serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_cbor/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_cbor/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_cbor/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in CBOR format.

#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

Output:

0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"api/basic_json/to_cbor/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_msgpack/","title":"nlohmann::basic_json::to_msgpack","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the MessagePack serialization.
  2. Writes the MessagePack serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"
  1. MessagePack serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_msgpack/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_msgpack/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_msgpack/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in MessagePack format.

#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

Output:

0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"api/basic_json/to_msgpack/#version-history","title":"Version history","text":""},{"location":"api/basic_json/to_string/","title":"to_string(basic_json)","text":"
template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j);\n

This function implements a user-defined to_string for JSON objects.

"},{"location":"api/basic_json/to_string/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/basic_json/to_string/#return-value","title":"Return value","text":"

string containing the serialization of the JSON value

"},{"location":"api/basic_json/to_string/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/to_string/#exceptions","title":"Exceptions","text":"

Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded

"},{"location":"api/basic_json/to_string/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/to_string/#possible-implementation","title":"Possible implementation","text":"
template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j)\n{\n    return j.dump();\n}\n
"},{"location":"api/basic_json/to_string/#examples","title":"Examples","text":"Example

The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup.

#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

Output:

{\"one\":1,\"two\":2}\n\n42\n
"},{"location":"api/basic_json/to_string/#see-also","title":"See also","text":""},{"location":"api/basic_json/to_string/#version-history","title":"Version history","text":"

Added in version 3.7.0.

"},{"location":"api/basic_json/to_ubjson/","title":"nlohmann::basic_json::to_ubjson","text":"
// (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

Serializes a given JSON value j 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.

  1. Returns a byte vector containing the UBJSON serialization.
  2. Writes the UBJSON serialization to an output adapter.

The exact mapping and its limitations is described on a dedicated page.

"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"
  1. UBJSON serialization as byte vector
  2. (none)
"},{"location":"api/basic_json/to_ubjson/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

"},{"location":"api/basic_json/to_ubjson/#complexity","title":"Complexity","text":"

Linear in the size of the JSON value j.

"},{"location":"api/basic_json/to_ubjson/#examples","title":"Examples","text":"Example

The example shows the serialization of a JSON value to a byte vector in UBJSON format.

#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"api/basic_json/to_ubjson/#version-history","title":"Version history","text":""},{"location":"api/basic_json/type/","title":"nlohmann::basic_json::type","text":"
constexpr value_t type() const noexcept;\n

Return the type of the JSON value as a value from the value_t enumeration.

"},{"location":"api/basic_json/type/#return-value","title":"Return value","text":"

the type of the JSON value

Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/type/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/type/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/type/#examples","title":"Examples","text":"Example

The following code exemplifies type() for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n
"},{"location":"api/basic_json/type/#version-history","title":"Version history","text":""},{"location":"api/basic_json/type_error/","title":"nlohmann::basic_json::type_error","text":"
class type_error : public exception;\n

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.

Exceptions have ids 3xx (see list of type errors).

"},{"location":"api/basic_json/type_error/#member-functions","title":"Member functions","text":""},{"location":"api/basic_json/type_error/#member-variables","title":"Member variables","text":""},{"location":"api/basic_json/type_error/#examples","title":"Examples","text":"Example

The following code shows how a type_error exception can be caught.

#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

Output:

message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n
"},{"location":"api/basic_json/type_error/#see-also","title":"See also","text":""},{"location":"api/basic_json/type_error/#version-history","title":"Version history","text":""},{"location":"api/basic_json/type_name/","title":"nlohmann::basic_json::type_name","text":"
const char* type_name() const noexcept;\n

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.

"},{"location":"api/basic_json/type_name/#return-value","title":"Return value","text":"

a string representation of the type (value_t):

Value type return value null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\""},{"location":"api/basic_json/type_name/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/type_name/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/basic_json/type_name/#examples","title":"Examples","text":"Example

The following code exemplifies type_name() for all JSON types.

#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

Output:

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
"},{"location":"api/basic_json/type_name/#version-history","title":"Version history","text":""},{"location":"api/basic_json/unflatten/","title":"nlohmann::basic_json::unflatten","text":"
basic_json unflatten() const;\n

The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints:

  1. The value must be an object.
  2. The keys must be JSON pointers (see RFC 6901)
  3. The mapped values must be primitive JSON types.
"},{"location":"api/basic_json/unflatten/#return-value","title":"Return value","text":"

the original JSON from a flattened version

"},{"location":"api/basic_json/unflatten/#exception-safety","title":"Exception safety","text":"

Strong exception safety: if an exception occurs, the original value stays intact.

"},{"location":"api/basic_json/unflatten/#exceptions","title":"Exceptions","text":"

The function can throw the following exceptions:

"},{"location":"api/basic_json/unflatten/#complexity","title":"Complexity","text":"

Linear in the size the JSON value.

"},{"location":"api/basic_json/unflatten/#notes","title":"Notes","text":"

Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j, the following is always true: j == j.flatten().unflatten().

"},{"location":"api/basic_json/unflatten/#examples","title":"Examples","text":"Example

The following code shows how a flattened JSON object is unflattened into the original nested JSON object.

#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

Output:

{\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
"},{"location":"api/basic_json/unflatten/#see-also","title":"See also","text":""},{"location":"api/basic_json/unflatten/#version-history","title":"Version history","text":""},{"location":"api/basic_json/update/","title":"nlohmann::basic_json::update","text":"
// (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
  1. Inserts all values from JSON object j.
  2. Inserts all values from range [first, last)

When merge_objects is false (default), existing keys are overwritten. When merge_objects is true, recursively merges objects with common keys.

The function is motivated by Python's dict.update function.

"},{"location":"api/basic_json/update/#parameters","title":"Parameters","text":"j (in) JSON object to read values from merge_objects (in) when true, existing keys are not overwritten, but contents of objects are merged recursively (default: false) first (in) begin of the range of elements to insert last (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
  2. The function can throw the following exceptions:
    • Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
    • Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
    • Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
"},{"location":"api/basic_json/update/#complexity","title":"Complexity","text":"
  1. O(N*log(size() + N)), where N is the number of elements to insert.
  2. O(N*log(size() + N)), where N is the number of elements to insert.
"},{"location":"api/basic_json/update/#examples","title":"Examples","text":"Example

The example shows how update() is used.

#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

Output:

{\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
Example

The example shows how update() is used.

#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

Output:

{\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
Example

One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects:

{\n    \"color\": \"red\",\n    \"active\": true,\n    \"name\": {\"de\": \"Maus\", \"en\": \"mouse\"}\n}\n

The user may override the default settings selectively:

{\n    \"color\": \"blue\",\n    \"name\": {\"es\": \"rat\u00f3n\"},\n}\n

Then update manages the merging of default settings and user settings:

auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings);\n

Now effective_settings contains the default settings, but those keys set by the user are overwritten:

{\n    \"color\": \"blue\",\n    \"active\": true,\n    \"name\": {\"es\": \"rat\u00f3n\"}\n}\n

Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true:

auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings, true);\n
{\n    \"color\": \"blue\",\n    \"active\": true,\n    \"name\": {\"de\": \"Maus\", \"en\": \"mouse\", \"es\": \"rat\u00f3n\"}\n}\n
"},{"location":"api/basic_json/update/#version-history","title":"Version history","text":""},{"location":"api/basic_json/value/","title":"nlohmann::basic_json::value","text":"
// (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
  1. Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.

    The function is basically equivalent to executing

    try {\n   return at(key);\n} catch(out_of_range) {\n   return default_value;\n}\n

  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.

  3. Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists.

    The function is basically equivalent to executing

    try {\n   return at(ptr);\n} catch(out_of_range) {\n   return default_value;\n}\n

Differences to at and operator[]

"},{"location":"api/basic_json/value/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17). ValueType type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"key (in) key of the element to access default_value (in) the value to return if key/ptr found no value ptr (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"
  1. copy of the element at key key or default_value if key is not found
  2. copy of the element at key key or default_value if key is not found
  3. copy of the element at JSON Pointer ptr or default_value if no value for ptr is found
"},{"location":"api/basic_json/value/#exception-safety","title":"Exception safety","text":"

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

"},{"location":"api/basic_json/value/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.302 if default_value does not match the type of the value at key
    • Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.
  2. See 1.
  3. The function can throw the following exceptions:
    • Throws type_error.302 if default_value does not match the type of the value at ptr
    • Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.
"},{"location":"api/basic_json/value/#complexity","title":"Complexity","text":"
  1. Logarithmic in the size of the container.
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
"},{"location":"api/basic_json/value/#examples","title":"Examples","text":"Example: (1) access specified object element with default value

The example below shows how object elements can be queried with a default value.

#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

Output:

1 42.23 oops false\n
Example: (2) access specified object element using string_view with default value

The example below shows how object elements can be queried with a default value.

#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

Output:

1 42.23 oops false\n
Example: (3) access specified object element via JSON Pointer with default value

The example below shows how object elements can be queried with a default value.

#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

Output:

1 42.23 oops false\n
"},{"location":"api/basic_json/value/#see-also","title":"See also","text":""},{"location":"api/basic_json/value/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Changed parameter default_value type from const ValueType& to ValueType&& in version 3.11.0.
  2. Added in version 3.11.0. Made ValueType the first template parameter in version 3.11.2.
  3. Added in version 2.0.2.
"},{"location":"api/basic_json/value_t/","title":"nlohmann::basic_json::value_t","text":"
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

This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions is_null, is_object, is_array, is_string, is_boolean, is_number (with is_number_integer, is_number_unsigned, and is_number_float), is_discarded, is_binary, is_primitive, and is_structured rely on it.

"},{"location":"api/basic_json/value_t/#notes","title":"Notes","text":"

Ordering

The order of types is as follows:

  1. null
  2. boolean
  3. number_integer, number_unsigned, number_float
  4. object
  5. array
  6. string
  7. binary

discarded is unordered.

Types of numbers

There are three enumerators for numbers (number_integer, number_unsigned, and number_float) to distinguish between different types of numbers:

Comparison operators

operator< and operator<=> (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 operator<=> during overload resolution, while others do not. For predictable and portable behavior use:

"},{"location":"api/basic_json/value_t/#examples","title":"Examples","text":"Example

The following code how type() queries the value_t for all JSON types.

#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

Output:

true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n
"},{"location":"api/basic_json/value_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/~basic_json/","title":"nlohmann::basic_json::~basic_json","text":"
~basic_json() noexcept;\n

Destroys the JSON value and frees all allocated memory.

"},{"location":"api/basic_json/~basic_json/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this member function never throws exceptions.

"},{"location":"api/basic_json/~basic_json/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/~basic_json/#version-history","title":"Version history","text":""},{"location":"api/byte_container_with_subtype/","title":"nlohmann::byte_container_with_subtype","text":"
template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n

This type extends the template parameter BinaryType provided to basic_json 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.

"},{"location":"api/byte_container_with_subtype/#template-parameters","title":"Template parameters","text":"BinaryType container to store bytes (std::vector<std::uint8_t> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":""},{"location":"api/byte_container_with_subtype/#member-functions","title":"Member functions","text":""},{"location":"api/byte_container_with_subtype/#version-history","title":"Version history","text":""},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/","title":"nlohmann::byte_container_with_subtype::byte_container_with_subtype","text":"
// (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
  1. Create empty binary container without subtype.
  2. Create binary container without subtype.
  3. Create binary container with subtype.
"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#parameters","title":"Parameters","text":"container (in) binary container subtype (in) subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how byte containers can be created.

#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

Output:

{\"bytes\":[],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":42}\n
"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/clear_subtype/","title":"nlohmann::byte_container_with_subtype::clear_subtype","text":"
void clear_subtype() noexcept;\n

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.

"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how clear_subtype can remove subtypes.

#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

Output:

before calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":42}\nafter calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":null}\n
"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/has_subtype/","title":"nlohmann::byte_container_with_subtype::has_subtype","text":"
constexpr bool has_subtype() const noexcept;\n

Returns whether the value has a subtype.

"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","title":"Return value","text":"

whether the value has a subtype

"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how has_subtype can check whether a subtype was set.

#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

Output:

c1.has_subtype() = false\nc2.has_subtype() = true\n
"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/set_subtype/","title":"nlohmann::byte_container_with_subtype::set_subtype","text":"
void set_subtype(subtype_type subtype) noexcept;\n

Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.

"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","title":"Parameters","text":"subtype (in) subtype to set"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how a subtype can be set with set_subtype.

#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

Output:

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
"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","title":"Version history","text":"

Since version 3.8.0.

"},{"location":"api/byte_container_with_subtype/subtype/","title":"nlohmann::byte_container_with_subtype::subtype","text":"
constexpr subtype_type subtype() const noexcept;\n

Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return subtype_type(-1) as a sentinel value.

"},{"location":"api/byte_container_with_subtype/subtype/#return-value","title":"Return value","text":"

the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set

"},{"location":"api/byte_container_with_subtype/subtype/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/byte_container_with_subtype/subtype/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/byte_container_with_subtype/subtype/#examples","title":"Examples","text":"Example

The example below demonstrates how the subtype can be retrieved with subtype. Note how subtype_type(-1) is returned for container c1.

#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

Output:

c1.subtype() = 18446744073709551615\nc2.subtype() = 42\n
"},{"location":"api/byte_container_with_subtype/subtype/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/","title":"nlohmann::json_pointer","text":"
template<typename RefStringType>\nclass json_pointer;\n

A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.

"},{"location":"api/json_pointer/#template-parameters","title":"Template parameters","text":"RefStringType the string type used for the reference tokens making up the JSON pointer

Deprecation

For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.

"},{"location":"api/json_pointer/#member-types","title":"Member types","text":""},{"location":"api/json_pointer/#member-functions","title":"Member functions","text":""},{"location":"api/json_pointer/#literals","title":"Literals","text":""},{"location":"api/json_pointer/#see-also","title":"See also","text":""},{"location":"api/json_pointer/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/back/","title":"nlohmann::json_pointer::back","text":"
const string_t& back() const;\n

Return last reference token.

"},{"location":"api/json_pointer/back/#return-value","title":"Return value","text":"

Last reference token.

"},{"location":"api/json_pointer/back/#exceptions","title":"Exceptions","text":"

Throws out_of_range.405 if JSON pointer has no parent.

"},{"location":"api/json_pointer/back/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/json_pointer/back/#examples","title":"Examples","text":"Example

The example shows the usage of back.

#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

Output:

last reference token of \"/foo\" is \"foo\"\nlast reference token of \"/foo/0\" is \"0\"\n
"},{"location":"api/json_pointer/back/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/empty/","title":"nlohmann::json_pointer::empty","text":"
bool empty() const noexcept;\n

Return whether pointer points to the root document.

"},{"location":"api/json_pointer/empty/#return-value","title":"Return value","text":"

true iff the JSON pointer points to the root document.

"},{"location":"api/json_pointer/empty/#exception-safety","title":"Exception safety","text":"

No-throw guarantee: this function never throws exceptions.

"},{"location":"api/json_pointer/empty/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/json_pointer/empty/#examples","title":"Examples","text":"Example

The example shows the result of empty for different JSON Pointers.

#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

Output:

\"\": true\n\"\": true\n\"/foo\": false\n\"/foo/0\": false\n
"},{"location":"api/json_pointer/empty/#version-history","title":"Version history","text":"

Added in version 3.6.0.

"},{"location":"api/json_pointer/json_pointer/","title":"nlohmann::json_pointer::json_pointer","text":"
explicit json_pointer(const string_t& s = \"\");\n

Create a JSON pointer according to the syntax described in Section 3 of RFC6901.

"},{"location":"api/json_pointer/json_pointer/#parameters","title":"Parameters","text":"s (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":""},{"location":"api/json_pointer/json_pointer/#examples","title":"Examples","text":"Example

The example shows the construction several valid JSON pointers as well as the exceptional behavior.

#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

Output:

[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
"},{"location":"api/json_pointer/json_pointer/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/operator_eq/","title":"nlohmann::json_pointer::operator==","text":"
// 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
  1. Compares two JSON pointers for equality by comparing their reference tokens.

  2. 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.

"},{"location":"api/json_pointer/operator_eq/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are equal

"},{"location":"api/json_pointer/operator_eq/#exception-safety","title":"Exception safety","text":"
  1. No-throw guarantee: this function never throws exceptions.
  2. Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/json_pointer/operator_eq/#exceptions","title":"Exceptions","text":"
  1. (none)
  2. The function can throw the following exceptions:
  3. Throws parse_error.107 if the given JSON pointer s is nonempty and does not begin with a slash (/); see example below.
  4. Throws parse_error.108 if a tilde (~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.
"},{"location":"api/json_pointer/operator_eq/#complexity","title":"Complexity","text":"

Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.

"},{"location":"api/json_pointer/operator_eq/#notes","title":"Notes","text":"

Deprecation

Overload 2 is deprecated and will be removed in a future major version release.

"},{"location":"api/json_pointer/operator_eq/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointers

The example demonstrates comparing JSON pointers.

#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

Output:

\"\" == \"\": true\n\"\" == \"\": true\n\"\" == \"/foo\": false\n\"/foo\" == \"/foo\": true\n
Example: (2) Comparing JSON pointers and strings

The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.

#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

Output:

\"\" == \"\": 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
"},{"location":"api/json_pointer/operator_eq/#version-history","title":"Version history","text":"
  1. Added in version 2.1.0. Added C++20 member functions in version 3.11.2.
  2. Added for backward compatibility and deprecated in version 3.11.2.
"},{"location":"api/json_pointer/operator_ne/","title":"nlohmann::json_pointer::operator!=","text":"
// 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
  1. Compares two JSON pointers for inequality by comparing their reference tokens.

  2. 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.

"},{"location":"api/json_pointer/operator_ne/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"

whether the values lhs/*this and rhs are not equal

"},{"location":"api/json_pointer/operator_ne/#exception-safety","title":"Exception safety","text":"
  1. No-throw guarantee: this function never throws exceptions.
  2. Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/json_pointer/operator_ne/#exceptions","title":"Exceptions","text":"
  1. (none)
  2. The function can throw the following exceptions:
  3. Throws parse_error.107 if the given JSON pointer s is nonempty and does not begin with a slash (/); see example below.
  4. Throws parse_error.108 if a tilde (~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.
"},{"location":"api/json_pointer/operator_ne/#complexity","title":"Complexity","text":"

Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.

"},{"location":"api/json_pointer/operator_ne/#notes","title":"Notes","text":"

Operator overload resolution

Since C++20 overload resolution will consider the rewritten candidate generated from operator==.

Deprecation

Overload 2 is deprecated and will be removed in a future major version release.

"},{"location":"api/json_pointer/operator_ne/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointers

The example demonstrates comparing JSON pointers.

#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

Output:

\"\" != \"\": false\n\"\" != \"\": false\n\"\" != \"/foo\": true\n\"/foo\" != \"/foo\": false\n
Example: (2) Comparing JSON pointers and strings

The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.

#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

Output:

\"\" != \"\": 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
"},{"location":"api/json_pointer/operator_ne/#version-history","title":"Version history","text":"
  1. Added in version 2.1.0.
  2. Added for backward compatibility and deprecated in version 3.11.2.
"},{"location":"api/json_pointer/operator_slash/","title":"nlohmann::json_pointer::operator/","text":"
// (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
  1. create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  2. create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  3. create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
"},{"location":"api/json_pointer/operator_slash/#parameters","title":"Parameters","text":"lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slash/#return-value","title":"Return value","text":"
  1. a new JSON pointer with rhs appended to lhs
  2. a new JSON pointer with unescaped token appended to lhs
  3. a new JSON pointer with array_idx appended to lhs
"},{"location":"api/json_pointer/operator_slash/#complexity","title":"Complexity","text":"
  1. Linear in the length of lhs and rhs.
  2. Linear in the length of lhs.
  3. Linear in the length of lhs.
"},{"location":"api/json_pointer/operator_slash/#examples","title":"Examples","text":"Example

The example shows the usage of operator/.

#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

Output:

\"/foo/bar/baz\"\n\"/foo/fob\"\n\"/foo/42\"\n
"},{"location":"api/json_pointer/operator_slash/#version-history","title":"Version history","text":"
  1. Added in version 3.6.0.
  2. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.
  3. Added in version 3.6.0.
"},{"location":"api/json_pointer/operator_slasheq/","title":"nlohmann::json_pointer::operator/=","text":"
// (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
  1. append another JSON pointer at the end of this JSON pointer
  2. append an unescaped reference token at the end of this JSON pointer
  3. append an array index at the end of this JSON pointer
"},{"location":"api/json_pointer/operator_slasheq/#parameters","title":"Parameters","text":"ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"
  1. JSON pointer with ptr appended
  2. JSON pointer with token appended without escaping token
  3. JSON pointer with array_idx appended
"},{"location":"api/json_pointer/operator_slasheq/#complexity","title":"Complexity","text":"
  1. Linear in the length of ptr.
  2. Amortized constant.
  3. Amortized constant.
"},{"location":"api/json_pointer/operator_slasheq/#examples","title":"Examples","text":"Example

The example shows the usage of operator/=.

#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

Output:

\"/foo\"\n\"/foo/bar/baz\"\n\"/foo/bar/baz/fob\"\n\"/foo/bar/baz/fob/42\"\n
"},{"location":"api/json_pointer/operator_slasheq/#version-history","title":"Version history","text":"
  1. Added in version 3.6.0.
  2. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.
  3. Added in version 3.6.0.
"},{"location":"api/json_pointer/operator_string_t/","title":"nlohmann::json_pointer::operator string_t","text":"
operator string_t() const\n

Return a string representation of the JSON pointer.

"},{"location":"api/json_pointer/operator_string_t/#return-value","title":"Return value","text":"

A string representation of the JSON pointer

"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","title":"Possible implementation","text":"
operator string_t() const\n{\n    return to_string();\n}\n
"},{"location":"api/json_pointer/operator_string_t/#notes","title":"Notes","text":"

Deprecation

This function is deprecated in favor of to_string and will be removed in a future major version release.

"},{"location":"api/json_pointer/operator_string_t/#examples","title":"Examples","text":"Example

The example shows how JSON Pointers can be implicitly converted to strings.

#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

Output:

/foo/0\n/a~1b\n
"},{"location":"api/json_pointer/operator_string_t/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/parent_pointer/","title":"nlohmann::json_pointer::parent_pointer","text":"
json_pointer parent_pointer() const;\n

Returns the parent of this JSON pointer.

"},{"location":"api/json_pointer/parent_pointer/#return-value","title":"Return value","text":"

Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.

"},{"location":"api/json_pointer/parent_pointer/#complexity","title":"Complexity","text":"

Linear in the length of the JSON pointer.

"},{"location":"api/json_pointer/parent_pointer/#examples","title":"Examples","text":"Example

The example shows the result of parent_pointer for different JSON Pointers.

#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

Output:

parent of \"\" is \"\"\nparent of \"/foo\" is \"\"\nparent of \"/foo/0\" is \"/foo\"\n
"},{"location":"api/json_pointer/parent_pointer/#version-history","title":"Version history","text":"

Added in version 3.6.0.

"},{"location":"api/json_pointer/pop_back/","title":"nlohmann::json_pointer::pop_back","text":"
void pop_back();\n

Remove last reference token.

"},{"location":"api/json_pointer/pop_back/#exceptions","title":"Exceptions","text":"

Throws out_of_range.405 if JSON pointer has no parent.

"},{"location":"api/json_pointer/pop_back/#complexity","title":"Complexity","text":"

Constant.

"},{"location":"api/json_pointer/pop_back/#examples","title":"Examples","text":"Example

The example shows the usage of pop_back.

#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

Output:

\"/foo/bar/baz\"\n\"/foo/bar\"\n\"/foo\"\n\"\"\n
"},{"location":"api/json_pointer/pop_back/#version-history","title":"Version history","text":"

Added in version 3.6.0.

"},{"location":"api/json_pointer/push_back/","title":"nlohmann::json_pointer::push_back","text":"
void push_back(const string_t& token);\n\nvoid push_back(string_t&& token);\n

Append an unescaped token at the end of the reference pointer.

"},{"location":"api/json_pointer/push_back/#parameters","title":"Parameters","text":"token (in) token to add"},{"location":"api/json_pointer/push_back/#complexity","title":"Complexity","text":"

Amortized constant.

"},{"location":"api/json_pointer/push_back/#examples","title":"Examples","text":"Example

The example shows the result of push_back for different JSON Pointers.

#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

Output:

\"\"\n\"/foo\"\n\"/foo/0\"\n\"/foo/0/bar\"\n
"},{"location":"api/json_pointer/push_back/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/string_t/","title":"nlohmann::json_pointer::string_t","text":"
using string_t = RefStringType;\n

The string type used for the reference tokens making up the JSON pointer.

See basic_json::string_t for more information.

"},{"location":"api/json_pointer/string_t/#examples","title":"Examples","text":"Example

The example shows the type string_t and its relation to basic_json::string_t.

#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

Output:

This is a string.\ntrue\n
"},{"location":"api/json_pointer/string_t/#version-history","title":"Version history","text":""},{"location":"api/json_pointer/to_string/","title":"nlohmann::json_pointer::to_string","text":"
string_t to_string() const;\n

Return a string representation of the JSON pointer.

"},{"location":"api/json_pointer/to_string/#return-value","title":"Return value","text":"

A string representation of the JSON pointer

"},{"location":"api/json_pointer/to_string/#notes","title":"Notes","text":"

For each JSON pointer ptr, it holds:

ptr == json_pointer(ptr.to_string());\n
"},{"location":"api/json_pointer/to_string/#examples","title":"Examples","text":"Example

The example shows the result of to_string.

#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

Output:

\"\"\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
"},{"location":"api/json_pointer/to_string/#version-history","title":"Version history","text":""},{"location":"api/json_sax/","title":"nlohmann::json_sax","text":"
template<typename BasicJsonType>\nstruct json_sax;\n

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.

"},{"location":"api/json_sax/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/json_sax/#member-types","title":"Member types","text":""},{"location":"api/json_sax/#member-functions","title":"Member functions","text":""},{"location":"api/json_sax/#version-history","title":"Version history","text":""},{"location":"api/json_sax/binary/","title":"nlohmann::json_sax::binary","text":"
virtual bool binary(binary_t& val) = 0;\n

A binary value was read.

"},{"location":"api/json_sax/binary/#parameters","title":"Parameters","text":"val (in) binary value"},{"location":"api/json_sax/binary/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/binary/#notes","title":"Notes","text":"

It is safe to move the passed binary value.

"},{"location":"api/json_sax/binary/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

binary(val=[...])\n\nresult: true\n
"},{"location":"api/json_sax/binary/#version-history","title":"Version history","text":""},{"location":"api/json_sax/boolean/","title":"nlohmann::json_sax::boolean","text":"
virtual bool boolean(bool val) = 0;\n

A boolean value was read.

"},{"location":"api/json_sax/boolean/#parameters","title":"Parameters","text":"val (in) boolean value"},{"location":"api/json_sax/boolean/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/boolean/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/boolean/#version-history","title":"Version history","text":""},{"location":"api/json_sax/end_array/","title":"nlohmann::json_sax::end_array","text":"
virtual bool end_array() = 0;\n

The end of an array was read.

"},{"location":"api/json_sax/end_array/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/end_array/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/end_array/#version-history","title":"Version history","text":""},{"location":"api/json_sax/end_object/","title":"nlohmann::json_sax::end_object","text":"
virtual bool end_object() = 0;\n

The end of an object was read.

"},{"location":"api/json_sax/end_object/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/end_object/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/end_object/#version-history","title":"Version history","text":""},{"location":"api/json_sax/key/","title":"nlohmann::json_sax::key","text":"
virtual bool key(string_t& val) = 0;\n

An object key was read.

"},{"location":"api/json_sax/key/#parameters","title":"Parameters","text":"val (in) object key"},{"location":"api/json_sax/key/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/key/#notes","title":"Notes","text":"

It is safe to move the passed object key value.

"},{"location":"api/json_sax/key/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/key/#version-history","title":"Version history","text":""},{"location":"api/json_sax/null/","title":"nlohmann::json_sax::null","text":"
virtual bool null() = 0;\n

A null value was read.

"},{"location":"api/json_sax/null/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/null/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/null/#version-history","title":"Version history","text":""},{"location":"api/json_sax/number_float/","title":"nlohmann::json_sax::number_float","text":"
virtual bool number_float(number_float_t val, const string_t& s) = 0;\n

A floating-point number was read.

"},{"location":"api/json_sax/number_float/#parameters","title":"Parameters","text":"val (in) floating-point value s (in) string representation of the original input"},{"location":"api/json_sax/number_float/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/number_float/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/number_float/#version-history","title":"Version history","text":""},{"location":"api/json_sax/number_integer/","title":"nlohmann::json_sax::number_integer","text":"
virtual bool number_integer(number_integer_t val) = 0;\n

An integer number was read.

"},{"location":"api/json_sax/number_integer/#parameters","title":"Parameters","text":"val (in) integer value"},{"location":"api/json_sax/number_integer/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/number_integer/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/number_integer/#version-history","title":"Version history","text":""},{"location":"api/json_sax/number_unsigned/","title":"nlohmann::json_sax::number_unsigned","text":"
virtual bool number_unsigned(number_unsigned_t val) = 0;\n

An unsigned integer number was read.

"},{"location":"api/json_sax/number_unsigned/#parameters","title":"Parameters","text":"val (in) unsigned integer value"},{"location":"api/json_sax/number_unsigned/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/number_unsigned/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/number_unsigned/#version-history","title":"Version history","text":""},{"location":"api/json_sax/parse_error/","title":"nlohmann::json_sax::parse_error","text":"
virtual bool parse_error(std::size_t position,\n                         const std::string& last_token,\n                         const detail::exception& ex) = 0;\n

A parse error occurred.

"},{"location":"api/json_sax/parse_error/#parameters","title":"Parameters","text":"position (in) the position in the input where the error occurs last_token (in) the last read token ex (in) an exception object describing the error"},{"location":"api/json_sax/parse_error/#return-value","title":"Return value","text":"

Whether parsing should proceed (must return false).

"},{"location":"api/json_sax/parse_error/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/parse_error/#version-history","title":"Version history","text":""},{"location":"api/json_sax/start_array/","title":"nlohmann::json_sax::start_array","text":"
virtual bool start_array(std::size_t elements) = 0;\n

The beginning of an array was read.

"},{"location":"api/json_sax/start_array/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_array/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/start_array/#notes","title":"Notes","text":"

Binary formats may report the number of elements.

"},{"location":"api/json_sax/start_array/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/start_array/#version-history","title":"Version history","text":""},{"location":"api/json_sax/start_object/","title":"nlohmann::json_sax::start_object","text":"
virtual bool start_object(std::size_t elements) = 0;\n

The beginning of an object was read.

"},{"location":"api/json_sax/start_object/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_object/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/start_object/#notes","title":"Notes","text":"

Binary formats may report the number of elements.

"},{"location":"api/json_sax/start_object/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/start_object/#version-history","title":"Version history","text":""},{"location":"api/json_sax/string/","title":"nlohmann::json_sax::string","text":"
virtual bool string(string_t& val) = 0;\n

A string value was read.

"},{"location":"api/json_sax/string/#parameters","title":"Parameters","text":"val (in) string value"},{"location":"api/json_sax/string/#return-value","title":"Return value","text":"

Whether parsing should proceed.

"},{"location":"api/json_sax/string/#notes","title":"Notes","text":"

It is safe to move the passed string value.

"},{"location":"api/json_sax/string/#examples","title":"Examples","text":"Example

The example below shows how the SAX interface is used.

#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

Output:

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
"},{"location":"api/json_sax/string/#version-history","title":"Version history","text":""},{"location":"api/macros/","title":"Macros","text":"

Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page.

"},{"location":"api/macros/#runtime-assertions","title":"Runtime assertions","text":""},{"location":"api/macros/#exceptions","title":"Exceptions","text":""},{"location":"api/macros/#language-support","title":"Language support","text":""},{"location":"api/macros/#library-version","title":"Library version","text":""},{"location":"api/macros/#library-namespace","title":"Library namespace","text":""},{"location":"api/macros/#type-conversions","title":"Type conversions","text":""},{"location":"api/macros/#comparison-behavior","title":"Comparison behavior","text":""},{"location":"api/macros/#serializationdeserialization-macros","title":"Serialization/deserialization macros","text":""},{"location":"api/macros/json_assert/","title":"JSON_ASSERT","text":"
#define JSON_ASSERT(x) /* value */\n

This macro controls which code is executed for runtime assertions of the library.

"},{"location":"api/macros/json_assert/#parameters","title":"Parameters","text":"x (in) expression of scalar type"},{"location":"api/macros/json_assert/#default-definition","title":"Default definition","text":"

The default value is assert(x).

#define JSON_ASSERT(x) assert(x)\n

Therefore, assertions can be switched off by defining NDEBUG.

"},{"location":"api/macros/json_assert/#notes","title":"Notes","text":""},{"location":"api/macros/json_assert/#examples","title":"Examples","text":"Example 1: default behavior

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n
Example 2: user-defined behavior

The assertion reporting can be changed by defining JSON_ASSERT(x) differently.

#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

Output:

assertion error in operator[]\n
"},{"location":"api/macros/json_assert/#version-history","title":"Version history","text":""},{"location":"api/macros/json_diagnostics/","title":"JSON_DIAGNOSTICS","text":"
#define JSON_DIAGNOSTICS /* value */\n

This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).

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.

"},{"location":"api/macros/json_diagnostics/#default-definition","title":"Default definition","text":"

The default value is 0 (extended diagnostics are switched off).

#define JSON_DIAGNOSTICS 0\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_diagnostics/#notes","title":"Notes","text":"

ABI compatibility

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.

This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior.

Where possible, it is still recommended that all code define this the same way for maximum interoperability.

CMake option

Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which defines JSON_DIAGNOSTICS accordingly.

"},{"location":"api/macros/json_diagnostics/#examples","title":"Examples","text":"Example 1: default behavior
#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

Output:

[json.exception.type_error.302] type must be number, but is string\n

This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.

Example 2: extended diagnostic messages
#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

Output:

[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n

Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.

"},{"location":"api/macros/json_diagnostics/#version-history","title":"Version history","text":""},{"location":"api/macros/json_disable_enum_serialization/","title":"JSON_DISABLE_ENUM_SERIALIZATION","text":"
#define JSON_DISABLE_ENUM_SERIALIZATION /* value */\n

When defined to 1, default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details).

Parsing or serializing an enum will result in a compiler error.

This works for both unscoped and scoped enums.

"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","title":"Default definition","text":"

The default value is 0.

#define JSON_DISABLE_ENUM_SERIALIZATION 0\n
"},{"location":"api/macros/json_disable_enum_serialization/#notes","title":"Notes","text":"

CMake option

Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization (OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.

"},{"location":"api/macros/json_disable_enum_serialization/#examples","title":"Examples","text":"Example 1: Disabled behavior

The code below forces the library not to create default serialization/deserialization functions from_json and to_json, meaning the code below does not compile.

#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
Example 2: Serialize enum macro

The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses NLOHMANN_JSON_SERIALIZE_ENUM to parse and serialize the enum.

#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
Example 3: User-defined serialization/deserialization functions

The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses user-defined functions to parse and serialize the enum.

#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
"},{"location":"api/macros/json_disable_enum_serialization/#see-also","title":"See also","text":""},{"location":"api/macros/json_disable_enum_serialization/#version-history","title":"Version history","text":""},{"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":"
#define JSON_HAS_CPP_11\n#define JSON_HAS_CPP_14\n#define JSON_HAS_CPP_17\n#define JSON_HAS_CPP_20\n

The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view 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.

"},{"location":"api/macros/json_has_cpp_11/#default-definition","title":"Default definition","text":"

The default value is detected based on preprocessor macros such as __cplusplus, _HAS_CXX17, or _MSVC_LANG.

"},{"location":"api/macros/json_has_cpp_11/#notes","title":"Notes","text":""},{"location":"api/macros/json_has_cpp_11/#examples","title":"Examples","text":"Example

The code below forces the library to use the C++14 standard:

#define JSON_HAS_CPP_14 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_cpp_11/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_filesystem/","title":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"
#define JSON_HAS_FILESYSTEM /* value */\n#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */\n

When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.

"},{"location":"api/macros/json_has_filesystem/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macros __cpp_lib_filesystem, __cpp_lib_experimental_filesystem, __has_include(<filesystem>), or __has_include(<experimental/filesystem>).

"},{"location":"api/macros/json_has_filesystem/#notes","title":"Notes","text":""},{"location":"api/macros/json_has_filesystem/#examples","title":"Examples","text":"Example

The code below forces the library to use the header <experimental/filesystem>.

#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_filesystem/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_ranges/","title":"JSON_HAS_RANGES","text":"
#define JSON_HAS_RANGES /* value */\n

This macro indicates whether the standard library has any support for ranges. Implies support for concepts. Possible values are 1 when supported or 0 when unsupported.

"},{"location":"api/macros/json_has_ranges/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macro __cpp_lib_ranges.

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_has_ranges/#examples","title":"Examples","text":"Example

The code below forces the library to enable support for ranges:

#define JSON_HAS_RANGES 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_ranges/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_static_rtti/","title":"JSON_HAS_STATIC_RTTI","text":"
#define JSON_HAS_STATIC_RTTI /* value */\n

This macro indicates whether the standard library has any support for RTTI (run time type information). Possible values are 1 when supported or 0 when unsupported.

"},{"location":"api/macros/json_has_static_rtti/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI.

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_has_static_rtti/#examples","title":"Examples","text":"Example

The code below forces the library to enable support for libraries with RTTI dependence:

#define JSON_HAS_STATIC_RTTI 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_static_rtti/#version-history","title":"Version history","text":""},{"location":"api/macros/json_has_three_way_comparison/","title":"JSON_HAS_THREE_WAY_COMPARISON","text":"
#define JSON_HAS_THREE_WAY_COMPARISON /* value */\n

This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.

"},{"location":"api/macros/json_has_three_way_comparison/#default-definition","title":"Default definition","text":"

The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison.

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_has_three_way_comparison/#examples","title":"Examples","text":"Example

The code below forces the library to use 3-way comparison:

#define JSON_HAS_THREE_WAY_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_has_three_way_comparison/#version-history","title":"Version history","text":""},{"location":"api/macros/json_no_io/","title":"JSON_NO_IO","text":"
#define JSON_NO_IO\n

When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> 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)).

"},{"location":"api/macros/json_no_io/#default-definition","title":"Default definition","text":"

By default, JSON_NO_IO is not defined.

#undef JSON_NO_IO\n
"},{"location":"api/macros/json_no_io/#examples","title":"Examples","text":"Example

The code below forces the library not to use the headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream>.

#define JSON_NO_IO 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_no_io/#version-history","title":"Version history","text":""},{"location":"api/macros/json_noexception/","title":"JSON_NOEXCEPTION","text":"
#define JSON_NOEXCEPTION\n

Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION. When defining JSON_NOEXCEPTION, try is replaced by if (true), catch is replaced by if (false), and throw is replaced by std::abort().

The same effect is achieved by setting the compiler flag -fno-exceptions.

"},{"location":"api/macros/json_noexception/#default-definition","title":"Default definition","text":"

By default, the macro is not defined.

#undef JSON_NOEXCEPTION\n
"},{"location":"api/macros/json_noexception/#notes","title":"Notes","text":"

The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.

"},{"location":"api/macros/json_noexception/#examples","title":"Examples","text":"Example

The code below switches off exceptions in the library.

#define JSON_NOEXCEPTION 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_noexception/#see-also","title":"See also","text":""},{"location":"api/macros/json_noexception/#version-history","title":"Version history","text":"

Added in version 2.1.0.

"},{"location":"api/macros/json_skip_library_version_check/","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"
#define JSON_SKIP_LIBRARY_VERSION_CHECK\n

When defined, the library will not create a compiler warning when a different version of the library was already included.

"},{"location":"api/macros/json_skip_library_version_check/#default-definition","title":"Default definition","text":"

By default, the macro is not defined.

#undef JSON_SKIP_LIBRARY_VERSION_CHECK\n
"},{"location":"api/macros/json_skip_library_version_check/#notes","title":"Notes","text":"

ABI compatibility

Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.

"},{"location":"api/macros/json_skip_library_version_check/#examples","title":"Examples","text":"

Example

The following warning will be shown in case a different version of the library was already included:

Already included a different version of the library!\n
"},{"location":"api/macros/json_skip_library_version_check/#version-history","title":"Version history","text":"

Added in version 3.11.0.

"},{"location":"api/macros/json_skip_unsupported_compiler_check/","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n

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.

"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","title":"Default definition","text":"

By default, the macro is not defined.

#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n
"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","title":"Examples","text":"Example

The code below switches off the check whether the compiler is supported.

#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","title":"Version history","text":"

Added in version 3.2.0.

"},{"location":"api/macros/json_throw_user/","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER","text":"
// (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

Controls how exceptions are handled by the library.

  1. This macro overrides catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.
  2. This macro overrides throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
  3. This macro overrides try calls inside the library. It has no arguments and is always followed by a scope.
"},{"location":"api/macros/json_throw_user/#parameters","title":"Parameters","text":"exception (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"

By default, the macros map to their respective C++ keywords:

#define JSON_CATCH_USER(exception) catch(exception)\n#define JSON_THROW_USER(exception) throw exception\n#define JSON_TRY_USER              try\n

When exceptions are switched off, the try block is executed unconditionally, and throwing exceptions is replaced by calling std::abort to make reaching the throw branch abort the process.

#define JSON_THROW_USER(exception) std::abort()\n#define JSON_TRY_USER              if (true)\n#define JSON_CATCH_USER(exception) if (false)\n
"},{"location":"api/macros/json_throw_user/#examples","title":"Examples","text":"Example

The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.

#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
"},{"location":"api/macros/json_throw_user/#see-also","title":"See also","text":""},{"location":"api/macros/json_throw_user/#version-history","title":"Version history","text":""},{"location":"api/macros/json_use_global_udls/","title":"JSON_USE_GLOBAL_UDLS","text":"
#define JSON_USE_GLOBAL_UDLS /* value */\n

When defined to 1, the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals.

"},{"location":"api/macros/json_use_global_udls/#default-definition","title":"Default definition","text":"

The default value is 1.

#define JSON_USE_GLOBAL_UDLS 1\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_use_global_udls/#notes","title":"Notes","text":"

Future behavior change

The user-defined string literals will be removed from the global namespace in the next major release of the library.

To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details.

CMake option

The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs (ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.

"},{"location":"api/macros/json_use_global_udls/#examples","title":"Examples","text":"Example 1: Default behavior

The code below shows the default behavior using the _json UDL.

#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

Output:

42\n
Example 2: Namespaced UDLs

The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0.

#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

Output:

42\n
"},{"location":"api/macros/json_use_global_udls/#see-also","title":"See also","text":""},{"location":"api/macros/json_use_global_udls/#version-history","title":"Version history","text":""},{"location":"api/macros/json_use_implicit_conversions/","title":"JSON_USE_IMPLICIT_CONVERSIONS","text":"
#define JSON_USE_IMPLICIT_CONVERSIONS /* value */\n

When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType.

"},{"location":"api/macros/json_use_implicit_conversions/#default-definition","title":"Default definition","text":"

By default, implicit conversions are enabled.

#define JSON_USE_IMPLICIT_CONVERSIONS 1\n
"},{"location":"api/macros/json_use_implicit_conversions/#notes","title":"Notes","text":"

Future behavior change

Implicit conversions will be switched off by default in the next major release of the library.

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.

CMake option

Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions (ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.

"},{"location":"api/macros/json_use_implicit_conversions/#examples","title":"Examples","text":"Example

This is an example for an implicit conversion:

json j = \"Hello, world!\";\nstd::string s = j;\n

When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0, the code above does no longer compile. Instead, it must be written like this:

json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n
"},{"location":"api/macros/json_use_implicit_conversions/#see-also","title":"See also","text":""},{"location":"api/macros/json_use_implicit_conversions/#version-history","title":"Version history","text":""},{"location":"api/macros/json_use_legacy_discarded_value_comparison/","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON","text":"
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */\n

This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default).

When enabled, comparisons involving at least one discarded JSON value yield results as follows:

Operator Result == false != true < false <= true >= true > false

Otherwise, comparisons involving at least one discarded JSON value always yield false.

"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#default-definition","title":"Default definition","text":"

The default value is 0.

#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","title":"Notes","text":"

Inconsistent behavior in C++20 and beyond

When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.

Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in inconsistent and unpredictable behavior.

See operator<=> for more information on 3-way comparison.

Deprecation

The legacy comparison behavior is deprecated and may be removed in a future major version release.

New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.

CMake option

Legacy comparison can also be controlled with the CMake option JSON_LegacyDiscardedValueComparison (OFF by default) which defines JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON accordingly.

"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#examples","title":"Examples","text":"Example

The code below switches on the legacy discarded value comparison behavior in the library.

#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n
"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","title":"Version history","text":""},{"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":"
#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

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 NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.

  1. Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
  2. Will use value 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 from_json() function default constructs an object and uses its values as the defaults when calling the value function.
  3. Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
"},{"location":"api/macros/nlohmann_define_type_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (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":"

The macros add two friend functions to the class which take care of the serialization and deserialization:

friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&); // except (3)\n

See examples below for the concrete generated code.

"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","title":"Notes","text":"

Prerequisites

  1. The type type must be default constructible (except (3)). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
  2. The macro must be used inside the type (class/struct).

Implementation limits

"},{"location":"api/macros/nlohmann_define_type_intrusive/#examples","title":"Examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n

Notes:

The macro is equivalent to:

#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
Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n

Notes:

The macro is equivalent to:

#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

Note how a default-initialized person object is used in the from_json to fill missing values.

Example (3): NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n

Notes:

The macro is equivalent to:

#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
"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_define_type_intrusive/#version-history","title":"Version history","text":"
  1. Added in version 3.9.0.
  2. Added in version 3.11.0.
  3. Added in version TODO.
"},{"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":"
#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

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 NLOHMANN_DEFINE_TYPE_INTRUSIVE, it cannot access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.

  1. Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
  2. Will use value 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 from_json() function default constructs an object and uses its values as the defaults when calling the value function.
  3. Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (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":"

The macros add two functions to the namespace which take care of the serialization and deserialization:

void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&); // except (3)\n

See examples below for the concrete generated code.

"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","title":"Notes","text":"

Prerequisites

  1. The type type must be default constructible (except (3). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
  2. The macro must be used outside the type (class/struct).
  3. The passed members must be public.

Implementation limits

"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#examples","title":"Examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n

Notes:

The macro is equivalent to:

#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
Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n

Notes:

The macro is equivalent to:

#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

Note how a default-initialized person object is used in the from_json to fill missing values.

Example (3): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE

Consider the following complete example:

#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

Output:

serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n

Notes:

The macro is equivalent to:

#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
"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_define_type_non_intrusive/#version-history","title":"Version history","text":"
  1. Added in version 3.9.0.
  2. Added in version 3.11.0.
  3. Added in version TODO.
"},{"location":"api/macros/nlohmann_json_namespace/","title":"NLOHMANN_JSON_NAMESPACE","text":"
#define NLOHMANN_JSON_NAMESPACE /* value */\n

This macro evaluates to the full name of the nlohmann namespace.

"},{"location":"api/macros/nlohmann_json_namespace/#default-definition","title":"Default definition","text":"

The default value consists of the root namespace (nlohmann) and an inline ABI namespace. See nlohmann Namespace for details.

When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.

"},{"location":"api/macros/nlohmann_json_namespace/#examples","title":"Examples","text":"Example

The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.

#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

Output:

nlohmann::json_abi_v3_11_3\n
"},{"location":"api/macros/nlohmann_json_namespace/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_namespace/#version-history","title":"Version history","text":""},{"location":"api/macros/nlohmann_json_namespace_begin/","title":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END","text":"
#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */  // (1)\n#define NLOHMANN_JSON_NAMESPACE_END   /* value */  // (2)\n

These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details.

  1. Opens the namespace.
  2. Closes the namespace.
"},{"location":"api/macros/nlohmann_json_namespace_begin/#default-definition","title":"Default definition","text":"

The default definitions open and close the nlohmann namespace. The precise definition of [NLOHMANN_JSON_NAMESPACE_BEGIN] varies as described here.

  1. Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN:

    namespace nlohmann\n{\ninline namespace json_abi_v3_11_2\n{\n
  2. Default definition of NLOHMANN_JSON_NAMESPACE_END:

    }  // namespace json_abi_v3_11_2\n}  // namespace nlohmann\n

When these macros are not defined, the library will define them to their default definitions.

"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","title":"Examples","text":"Example

The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN/NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page.

#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

Output:

[1,null]\n
"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_namespace_begin/#version-history","title":"Version history","text":""},{"location":"api/macros/nlohmann_json_namespace_no_version/","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION","text":"
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */\n

If defined to 1, the version component is omitted from the inline namespace. See nlohmann Namespace for details.

"},{"location":"api/macros/nlohmann_json_namespace_no_version/#default-definition","title":"Default definition","text":"

The default value is 0.

#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0\n

When the macro is not defined, the library will define it to its default value.

"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","title":"Examples","text":"Example

The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace.

#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

Output:

nlohmann::json_abi\n
"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_namespace_no_version/#version-history","title":"Version history","text":""},{"location":"api/macros/nlohmann_json_serialize_enum/","title":"NLOHMANN_JSON_SERIALIZE_ENUM","text":"
#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)\n

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.

The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.

"},{"location":"api/macros/nlohmann_json_serialize_enum/#parameters","title":"Parameters","text":"type (in) name of the enum to serialize/deserialize conversion (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":"

The macros add two friend functions to the class which take care of the serialization and deserialization:

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
"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","title":"Notes","text":"

Prerequisites

The macro must be used inside the namespace of the enum.

Important notes

"},{"location":"api/macros/nlohmann_json_serialize_enum/#examples","title":"Examples","text":"Example 1: Basic usage

The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes:

#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

Output:

ns::TS_STOPPED -> \"stopped\", ns::Color::red -> \"red\"\n\"running\" -> 1, \"blue\" -> 2\n3.14 -> -1, 3.14 -> 3\n
Example 2: Multiple conversions for one enumerator

The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\", because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red.

#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

Output:

0 -> \"red\"\n\"rot\" -> 0\n\"red\" -> 0\n
"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_serialize_enum/#version-history","title":"Version history","text":"

Added in version 3.4.0.

"},{"location":"api/macros/nlohmann_json_version_major/","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"
#define NLOHMANN_JSON_VERSION_MAJOR /* value */\n#define NLOHMANN_JSON_VERSION_MINOR /* value */\n#define NLOHMANN_JSON_VERSION_PATCH /* value */\n

These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.

"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","title":"Default definition","text":"

The macros are defined according to the current library version.

"},{"location":"api/macros/nlohmann_json_version_major/#examples","title":"Examples","text":"Example

The example below shows how NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH are defined by the library.

#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

Output:

JSON for Modern C++ version 3.11.3\n
"},{"location":"api/macros/nlohmann_json_version_major/#see-also","title":"See also","text":""},{"location":"api/macros/nlohmann_json_version_major/#version-history","title":"Version history","text":""},{"location":"features/arbitrary_types/","title":"Arbitrary Type Conversions","text":"

Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:

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

It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:

// 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
"},{"location":"features/arbitrary_types/#basic-usage","title":"Basic usage","text":"

To make this work with one of your types, you only need to provide two functions:

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

That's all! When calling the json constructor with your type, your custom to_json method will be automatically called. Likewise, when calling template get<your_type>() or get_to(your_type&), the from_json method will be called.

Some important things:

"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","title":"Simplify your life with macros","text":"

If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate.

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:

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.

Implementation limits

Example

The to_json/from_json functions for the person struct above can be created with:

namespace ns {\n    NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n}\n

Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed:

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
"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"

This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:

The library uses JSON Serializers to convert types to json. The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).

It is implemented like this (simplified):

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

This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...

To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:

// 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

ABI compatibility

Use NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END instead of namespace nlohmann { } in code which may be linked with different versions of this library.

"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types","title":"How can I use get() for non-default constructible/non-copyable types?","text":"

There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:

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
"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"

Yes. You might want to take a look at unit-udt.cpp in the test suite, to see a few examples.

If you write your own serializer, you'll need to do a few things:

Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.

// 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

Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:

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
"},{"location":"features/assertions/","title":"Runtime Assertions","text":"

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.

"},{"location":"features/assertions/#switch-off-runtime-assertions","title":"Switch off runtime assertions","text":"

Runtime assertions can be switched off by defining the preprocessor macro NDEBUG (see the documentation of assert) which is the default for release builds.

"},{"location":"features/assertions/#change-assertion-behavior","title":"Change assertion behavior","text":"

The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header.

"},{"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":"

Function operator[] 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.

If you are not sure whether an element in an object exists, use checked access with the at function or call the contains function before.

See also the documentation on element access.

Example 1: Missing object key

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n
"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"

Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.

Example 2: Uninitialized iterator range

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n
"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"

Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.

Example 3: Uninitialized iterator

The following code will trigger an assertion at runtime:

#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n  json::iterator it;\n  ++it;\n}\n

Output:

Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n
"},{"location":"features/assertions/#reading-from-a-null-file-pointer","title":"Reading from a null FILE pointer","text":"

Reading from a null FILE pointer is undefined behavior and yields a runtime assertion. This can happen when calling std::fopen on a nonexistent file.

Example 4: Uninitialized iterator

The following code will trigger an assertion at runtime:

#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

Output:

Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.\n
"},{"location":"features/binary_values/","title":"Binary Values","text":"

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.

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.

"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"

By default, binary values are stored as std::vector<std::uint8_t>. This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t:

auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE});\nauto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n

There are several convenience functions to check and set the subtype:

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

As json::binary_t is subclassing std::vector<std::uint8_t>, all member functions are available:

binary.size();  // returns 4\nbinary[1];      // returns 0xFE\n

JSON values can be constructed from json::binary_t:

json j = binary;\n

Binary values are primitive values just like numbers or strings:

j.is_binary();    // returns true\nj.is_primitive(); // returns true\n

Given a binary JSON value, the binary_t can be accessed by reference as via get_binary():

j.get_binary().has_subtype();  // returns true\nj.get_binary().size();         // returns 4\n

For convenience, binary JSON values can be constructed via json::binary:

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
"},{"location":"features/binary_values/#serialization","title":"Serialization","text":"

Binary values are serialized differently according to the formats.

"},{"location":"features/binary_values/#json","title":"JSON","text":"

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: bytes holds an array of integers, and subtype is an integer or null.

Example

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

Output:

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": 42\n  }\n}\n

No roundtrip for binary values

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.

"},{"location":"features/binary_values/#bjdata","title":"BJData","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 20 elements:

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

The following code uses the type and size optimization for UBJSON:

// convert to UBJSON using the size and type optimization\nauto v = json::to_bjdata(j, true, true);\n

The resulting vector has 22 elements; the optimization is not effective for examples with few values:

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

Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:

{\n  \"binary\": [202, 254, 186, 190]\n}\n
"},{"location":"features/binary_values/#bson","title":"BSON","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 22 elements:

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

Note that the serialization preserves the subtype, and deserializing v would yield the following value:

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": 42\n  }\n}\n
"},{"location":"features/binary_values/#cbor","title":"CBOR","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 15 elements:

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

Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless json::cbor_tag_handler_t::ignore or json::cbor_tag_handler_t::store is passed to json::from_cbor.

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": null\n  }\n}\n
"},{"location":"features/binary_values/#messagepack","title":"MessagePack","text":"

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.

If no subtype is given, the bin family (bin8, bin16, bin32) is used.

Example

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

v is a std::vector<std::uint8t> with the following 14 elements:

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

Note that the serialization preserves the subtype, and deserializing v would yield the following value:

{\n  \"binary\": {\n    \"bytes\": [202, 254, 186, 190],\n    \"subtype\": 42\n  }\n}\n
"},{"location":"features/binary_values/#ubjson","title":"UBJSON","text":"

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.

Example

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

v is a std::vector<std::uint8t> with the following 20 elements:

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

The following code uses the type and size optimization for UBJSON:

// convert to UBJSON using the size and type optimization\nauto v = json::to_ubjson(j, true, true);\n

The resulting vector has 23 elements; the optimization is not effective for examples with few values:

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

Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:

{\n  \"binary\": [202, 254, 186, 190]\n}\n
"},{"location":"features/comments/","title":"Comments","text":"

This library does not support comments by default. It does so for three reasons:

  1. Comments are not part of the JSON specification. You may argue that // or /* */ are allowed in JavaScript, but JSON is not JavaScript.
  2. This was not an oversight: Douglas Crockford wrote on this in May 2012:

    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
  3. 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.

However, you can pass set parameter ignore_comments to true in the parse function to ignore // or /* */ comments. Comments will then be treated as whitespace.

Example

Consider the following JSON with comments.

{\n    // update in 2006: removed Pluto\n    \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n                \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n}\n

When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true, the comments are ignored during parsing:

#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

Output:

[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
{\n  \"planets\": [\n    \"Mercury\",\n    \"Venus\",\n    \"Earth\",\n    \"Mars\",\n    \"Jupiter\",\n    \"Uranus\",\n    \"Neptune\"\n  ]\n}\n
"},{"location":"features/enum_conversion/","title":"Specializing enum conversion","text":"

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.

It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:

// 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

The NLOHMANN_JSON_SERIALIZE_ENUM() macro declares a set of to_json() / from_json() functions for type TaskState while avoiding repetition and boilerplate serialization code.

"},{"location":"features/enum_conversion/#usage","title":"Usage","text":"
// 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
"},{"location":"features/enum_conversion/#notes","title":"Notes","text":"

Just as in Arbitrary Type Conversions above,

Other Important points:

"},{"location":"features/iterators/","title":"Iterators","text":""},{"location":"features/iterators/#overview","title":"Overview","text":"

A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values.

As for other containers, begin() returns an iterator to the first value and end() 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, begin() will return end().

"},{"location":"features/iterators/#iteration-order-for-objects","title":"Iteration order for objects","text":"

When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.

Example
// 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

Output:

1\n3\n2\n

The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".

"},{"location":"features/iterators/#access-object-key-during-iteration","title":"Access object key during iteration","text":"

The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown.

Example
// 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

Output:

one : 1\nthree : 3\ntwo : 2\n
"},{"location":"features/iterators/#range-based-for-loops","title":"Range-based for loops","text":"

C++11 allows using range-based for loops to iterate over a container.

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

For this reason, the items() function allows accessing iterator::key() and iterator::value() 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.

for (auto& el : j_object.items())\n{\n    std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n

The items() function also allows using structured bindings (C++17):

for (auto& [key, val] : j_object.items())\n{\n    std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n

Note

When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string.

Warning

Using items() 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.

"},{"location":"features/iterators/#reverse-iteration-order","title":"Reverse iteration order","text":"

rbegin() and rend() return iterators in the reverse sequence.

Example
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

Output:

4\n3\n2\n1\n
"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"

Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe the underlying string or binary array is empty.

Example
json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n    std::cout << *it << std::endl;\n}\n

Output:

\"Hello, world\"\n
"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators clear all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"

JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.

Example

The following code shows how a JSON patch is applied to a value.

#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

Output:

{\n    \"baz\": \"qux\",\n    \"foo\": \"bar\"\n}\n\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"features/json_patch/#diff","title":"Diff","text":"

The library can also calculate a JSON patch (i.e., a diff) given two JSON values.

Invariant

For two JSON values source and target, the following code yields always true:

source.patch(diff(source, target)) == target;\n
Example

The following code shows how a JSON patch is created as a diff for two JSON values.

#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

Output:

[\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
"},{"location":"features/json_pointer/","title":"JSON Pointer","text":""},{"location":"features/json_pointer/#introduction","title":"Introduction","text":"

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.

Consider the following JSON document

{\n    \"array\": [\"A\", \"B\", \"C\"],\n    \"nested\": {\n        \"one\": 1,\n        \"two\": 2,\n        \"three\": [true, false]\n    }\n}\n

Then every value inside the JSON document can be identified as follows:

JSON Pointer JSON value `` {\"array\":[\"A\",\"B\",\"C\"],\"nested\":{\"one\":1,\"two\":2,\"three\":[true,false]}} /array [\"A\",\"B\",\"C\"] /array/0 A /array/1 B /array/2 C /nested {\"one\":1,\"two\":2,\"three\":[true,false]} /nested/one 1 /nested/two 2 /nested/three [true,false] /nested/three/0 true /nested/three/1 false

Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\". See RFC 6901 for more information.

"},{"location":"features/json_pointer/#json-pointer-creation","title":"JSON Pointer creation","text":"

JSON Pointers can be created from a string:

json::json_pointer p = \"/nested/one\";\n

Furthermore, a user-defined string literal can be used to achieve the same result:

auto p = \"/nested/one\"_json_pointer;\n

The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.

"},{"location":"features/json_pointer/#value-access","title":"Value access","text":"

JSON Pointers can be used in the at, operator[], and value functions just like object keys or array indices.

// 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
"},{"location":"features/json_pointer/#flatten-unflatten","title":"Flatten / unflatten","text":"

The library implements a function flatten 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).

// 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

The resulting value j_flat is:

{\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

The reverse function, unflatten recreates the original value.

auto j_original = j_flat.unflatten();\n
"},{"location":"features/json_pointer/#see-also","title":"See also","text":""},{"location":"features/macros/","title":"Supported Macros","text":"

Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.

"},{"location":"features/macros/#json_assertx","title":"JSON_ASSERT(x)","text":"

This macro controls which code is executed for runtime assertions of the library.

See full documentation of JSON_ASSERT(x).

"},{"location":"features/macros/#json_catch_userexception","title":"JSON_CATCH_USER(exception)","text":"

This macro overrides catch calls inside the library.

See full documentation of JSON_CATCH_USER(exception).

"},{"location":"features/macros/#json_diagnostics","title":"JSON_DIAGNOSTICS","text":"

This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).

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.

The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which sets JSON_DIAGNOSTICS accordingly.

See full documentation of JSON_DIAGNOSTICS.

"},{"location":"features/macros/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20","text":"

The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view 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.

See full documentation of JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, and JSON_HAS_CPP_20.

"},{"location":"features/macros/#json_has_filesystem-json_has_experimental_filesystem","title":"JSON_HAS_FILESYSTEM, JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"

When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.

See full documentation of JSON_HAS_FILESYSTEM and JSON_HAS_EXPERIMENTAL_FILESYSTEM.

"},{"location":"features/macros/#json_noexception","title":"JSON_NOEXCEPTION","text":"

Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION.

See full documentation of JSON_NOEXCEPTION.

"},{"location":"features/macros/#json_disable_enum_serialization","title":"JSON_DISABLE_ENUM_SERIALIZATION","text":"

When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM.

See full documentation of JSON_DISABLE_ENUM_SERIALIZATION.

"},{"location":"features/macros/#json_no_io","title":"JSON_NO_IO","text":"

When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> 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)).

See full documentation of JSON_NO_IO.

"},{"location":"features/macros/#json_skip_library_version_check","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"

When defined, the library will not create a compiler warning when a different version of the library was already included.

See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK.

"},{"location":"features/macros/#json_skip_unsupported_compiler_check","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"

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.

See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK.

"},{"location":"features/macros/#json_throw_userexception","title":"JSON_THROW_USER(exception)","text":"

This macro overrides throw calls inside the library. The argument is the exception to be thrown.

See full documentation of JSON_THROW_USER(exception).

"},{"location":"features/macros/#json_try_user","title":"JSON_TRY_USER","text":"

This macro overrides try calls inside the library.

See full documentation of JSON_TRY_USER.

"},{"location":"features/macros/#json_use_implicit_conversions","title":"JSON_USE_IMPLICIT_CONVERSIONS","text":"

When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on.

See full documentation of JSON_USE_IMPLICIT_CONVERSIONS.

"},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)","text":"

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.

The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.

See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE.

"},{"location":"features/macros/#nlohmann_define_type_intrusive_with_defaulttype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.

See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT.

"},{"location":"features/macros/#nlohmann_define_type_intrusive_only_serializetype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE 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.

See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE.

"},{"location":"features/macros/#nlohmann_define_type_non_intrusivetype-member","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)","text":"

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.

The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members.

See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.

"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_with_defaulttype-member","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.

See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.

"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_only_serializetype-member","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"

This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE 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.

See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE.

"},{"location":"features/macros/#nlohmann_json_serialize_enumtype","title":"NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)","text":"

This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information.

See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM.

"},{"location":"features/macros/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"

These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.

See full documentation of NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH.

"},{"location":"features/merge_patch/","title":"JSON Merge Patch","text":"

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.

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.

Example

The following code shows how a JSON Merge Patch is applied to a JSON document.

#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

Output:

{\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
"},{"location":"features/namespace/","title":"nlohmann Namespace","text":"

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.

"},{"location":"features/namespace/#structure","title":"Structure","text":"

The complete default namespace name is derived as follows:

For example, the namespace name for version 3.11.2 with JSON_DIAGNOSTICS defined to 1 is:

nlohmann::json_abi_diag_v3_11_2\n
"},{"location":"features/namespace/#purpose","title":"Purpose","text":"

Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS. This is illustrated in the diagram below.

In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library 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.

"},{"location":"features/namespace/#limitations","title":"Limitations","text":"

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.

There is an exception when forward declarations are used (i.e., when including json_fwd.hpp) in which case the linker may complain about undefined references.

"},{"location":"features/namespace/#disabling-the-version-component","title":"Disabling the version component","text":"

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.

To do so, define NLOHMANN_JSON_NAMESPACE_NO_VERSION to 1.

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 NLOHMANN_JSON_NAMESPACE_NO_VERSION macro.

Use at your own risk

Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!

"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"

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 NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows:

#define NLOHMANN_JSON_NAMESPACE_BEGIN  namespace nlohmann {\n#define NLOHMANN_JSON_NAMESPACE_END    }\n

Use at your own risk

Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!

"},{"location":"features/namespace/#version-history","title":"Version history","text":""},{"location":"features/object_order/","title":"Object Order","text":"

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.

"},{"location":"features/object_order/#default-behavior-sort-keys","title":"Default behavior: sort keys","text":"

The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.

Example
#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

Output:

{\n  \"one\": 1,\n  \"three\": 3,\n  \"two\": 2\n}\n
"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","title":"Alternative behavior: preserve insertion order","text":"

If you do want to preserve the insertion order, you can try the type nlohmann::ordered_json.

Example
#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

Output:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n

Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map (integration) or nlohmann::fifo_map (integration).

"},{"location":"features/object_order/#notes-on-parsing","title":"Notes on parsing","text":"

Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n

Right way

The following code correctly calls the parse function from nlohmann::ordered_json:

std::ifstream i(\"input.json\");\nauto j = nlohmann::ordered_json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n

The output will be:

{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}\n
Wrong way

The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file.

std::ifstream i(\"input.json\");\nnlohmann::ordered_json j = nlohmann::json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n

The output will be:

{\n  \"one\": 1,\n  \"three\": 3\n  \"two\": 2,\n}\n
"},{"location":"features/binary_formats/","title":"Binary Formats","text":"

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

to efficiently encode JSON values to byte vectors and to decode such vectors.

"},{"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

See binary values for more information.

"},{"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 %

Sizes compared to minified JSON value.

"},{"location":"features/binary_formats/bjdata/","title":"BJData","text":"

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 - [u] - uint16, [m] - uint32, [M] - uint64 and [h] - float16 - 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.

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.

References

"},{"location":"features/binary_formats/bjdata/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to BJData types according to the BJData specification:

JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map {

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a BJData value.

Any BJData output created by to_bjdata can be successfully parsed by from_bjdata.

Size constraints

The following values can not be converted to a BJData value:

Unused BJData markers

The following markers are not used in the conversion:

NaN/infinity handling

If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.

Endianness

A breaking difference between BJData and UBJSON is the endianness of numerical values. In BJData, all numerical data types (integers UiuImlML and floating-point values hdD) 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.

Optimized formats

Optimized formats for containers are supported via two parameters of to_bjdata:

Note that use_size = true 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.

ND-array optimized format

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 uint8 integer array [[1,2],[3,4],[5,6]], stored as nested optimized array in UBJSON [ [$U#i2 1 2 [$U#i2 3 4 [$U#i2 5 6 ], can be further compressed in BJData to [$U#[$i#i2 2 3 1 2 3 4 5 6 or [$U#[i2 i3] 1 2 3 4 5 6.

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 from_bjdata. For example, the above 2-D uint8 array can be parsed and accessed as

{\n    \"_ArrayType_\": \"uint8\",\n    \"_ArraySize_\": [2,3],\n    \"_ArrayData_\": [1,2,3,4,5,6]\n}\n

Likewise, when a JSON object in the above form is serialzed using to_bjdata, it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated.

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.

Restrictions in optimized data types for arrays and objects

Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ 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 UiuImlMLhdDC. This also means other variable ([{SH) or zero-length types (TFN) can not be used in an optimized array or object in BJData.

Binary values

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.

Example
#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"features/binary_formats/bjdata/#deserialization","title":"Deserialization","text":"

The library maps BJData types to JSON value types as follows:

BJData type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) {

Complete mapping

The mapping is complete in the sense that any BJData value can be converted to a JSON value.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/bson/","title":"BSON","text":"

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.

References

"},{"location":"features/binary_formats/bson/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to BSON types:

JSON value type value/range BSON type marker null null null 0x0A boolean true, false 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

Incomplete mapping

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.

Example
#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

Output:

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
"},{"location":"features/binary_formats/bson/#deserialization","title":"Deserialization","text":"

The library maps BSON record types to JSON value types as follows:

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

Incomplete mapping

The mapping is incomplete. The unsupported mappings are indicated in the table above.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/cbor/","title":"CBOR","text":"

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.

References

"},{"location":"features/binary_formats/cbor/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049):

JSON value type value/range CBOR type first byte null null Null 0xF6 boolean true True 0xF5 boolean false 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

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.

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a CBOR value.

NaN/infinity handling

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 null.

Unused CBOR types

The following CBOR types are not used in the conversion:

Tagged items

Binary subtypes will be serialized as tagged items. See binary values for an example.

Example
#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

Output:

0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"features/binary_formats/cbor/#deserialization","title":"Deserialization","text":"

The library maps CBOR types to JSON value types as follows:

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 false 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB

Incomplete mapping

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:

Object keys

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.

Tagged items

Tagged items will throw a parse error by default. They can be ignored by passing cbor_tag_handler_t::ignore to function from_cbor. They can be stored by passing cbor_tag_handler_t::store to function from_cbor.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/messagepack/","title":"MessagePack","text":"

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.

References

"},{"location":"features/binary_formats/messagepack/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification:

JSON value type value/range MessagePack type first byte null null nil 0xC0 boolean true true 0xC3 boolean false 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

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value.

Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.

Size constraints

The following values can not be converted to a MessagePack value:

NaN/infinity handling

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 null.

Example
#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

Output:

0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n
"},{"location":"features/binary_formats/messagepack/#deserialization","title":"Deserialization","text":"

The library maps MessagePack types to JSON value types as follows:

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 null 0xC0 false false 0xC2 true true 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

Info

Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/binary_formats/ubjson/","title":"UBJSON","text":"

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.

References

"},{"location":"features/binary_formats/ubjson/#serialization","title":"Serialization","text":"

The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:

JSON value type value/range UBJSON type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map {

Complete mapping

The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.

Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson.

Size constraints

The following values can not be converted to a UBJSON value:

Unused UBJSON markers

The following markers are not used in the conversion:

NaN/infinity handling

If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.

Optimized formats

The optimized formats for containers are supported: Parameter use_size adds size information to the beginning of a container and removes the closing marker. Parameter use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The use_type parameter must only be used together with use_size = true.

Note that use_size = true 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.

Binary values

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.

Example
#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

Output:

{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n
"},{"location":"features/binary_formats/ubjson/#deserialization","title":"Deserialization","text":"

The library maps UBJSON types to JSON value types as follows:

UBJSON type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) {

Complete mapping

The mapping is complete in the sense that any UBJSON value can be converted to a JSON value.

Example
#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

Output:

{\n  \"compact\": true,\n  \"schema\": 0\n}\n
"},{"location":"features/element_access/","title":"Element Access","text":"

There are many ways elements in a JSON value can be accessed:

"},{"location":"features/element_access/checked_access/","title":"Checked access: at","text":""},{"location":"features/element_access/checked_access/#overview","title":"Overview","text":"

The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise.

Read access

Consider the following JSON value:

{\n    \"name\": \"Mary Smith\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

Assume the value is parsed to a json variable j.

expression value j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j.at(\"name\") \"Mary Smith\" j.at(\"age\") 42 j.at(\"hobbies\") [\"hiking\", \"reading\"] j.at(\"hobbies\").at(0) \"hiking\" j.at(\"hobbies\").at(1) \"reading\"

The return value is a reference, so it can be modified by the original value.

Write access
j.at(\"name\") = \"John Smith\";\n

This code produces the following JSON value:

{\n    \"name\": \"John Smith\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

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.

Accessing via invalid index or missing key
j.at(\"hobbies\").at(3) = \"cooking\";\n

This code produces the following exception:

[json.exception.out_of_range.401] array index 3 is out of range\n

When you extended diagnostic messages are enabled by defining JSON_DIAGNOSTICS, the exception further gives information where the key or index is missing or out of range.

[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n
"},{"location":"features/element_access/checked_access/#notes","title":"Notes","text":"

Exceptions

"},{"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 basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown access to invalid array index basic_json::out_of_range exception is thrown basic_json::out_of_range 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":"

In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present.

Example

Consider the following JSON value:

{\n    \"logOutput\": \"result.log\",\n    \"append\": true\n}\n

Assume the value is parsed to a json variable j.

expression value j {\"logOutput\": \"result.log\", \"append\": true} j.value(\"logOutput\", \"logfile.log\") \"result.log\" j.value(\"append\", true) true j.value(\"append\", false) true j.value(\"logLevel\", \"verbose\") \"verbose\""},{"location":"features/element_access/default_value/#note","title":"Note","text":"

Exceptions

"},{"location":"features/element_access/unchecked_access/","title":"Unchecked access: operator[]","text":""},{"location":"features/element_access/unchecked_access/#overview","title":"Overview","text":"

Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std::map and a std::vector, respectively.

Read access

Consider the following JSON value:

{\n    \"name\": \"Mary Smith\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

Assume the value is parsed to a json variable j.

expression value j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j[\"name\"] \"Mary Smith\" j[\"age\"] 42 j[\"hobbies\"] [\"hiking\", \"reading\"] j[\"hobbies\"][0] \"hiking\" j[\"hobbies\"][1] \"reading\"

The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten.

Write access
j[\"name\"] = \"John Smith\";\nj[\"maidenName\"] = \"Jones\";\n

This code produces the following JSON value:

{\n    \"name\": \"John Smith\",\n    \"maidenName\": \"Jones\",\n    \"age\": 42,\n    \"hobbies\": [\"hiking\", \"reading\"]\n}\n

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 null.

Filling up arrays with null values
j[\"hobbies\"][0] = \"running\";\nj[\"hobbies\"][3] = \"cooking\";\n

This code produces the following JSON value:

{\n    \"name\": \"John Smith\",\n    \"maidenName\": \"Jones\",\n    \"age\": 42,\n    \"hobbies\": [\"running\", \"reading\", null, \"cooking\"]\n}\n
"},{"location":"features/element_access/unchecked_access/#notes","title":"Notes","text":"

Design rationale

The library behaves differently to std::vector and std::map:

The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.

Info

The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.

Danger

Exceptions

operator[] can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown.

"},{"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 null value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted null value is returned; any index between previous maximal index and passed index are filled with null undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"

Note

This page is under construction.

"},{"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":"

See parsing and exceptions.

"},{"location":"features/parsing/json_lines/","title":"JSON Lines","text":"

The JSON Lines format is a text format of newline-delimited JSON. In particular:

  1. The input must be UTF-8 encoded.
  2. Every line must be a valid JSON value.
  3. The line separator must be \\n. As \\r is silently ignored, \\r\\n is also supported.
  4. The final character may be \\n, but is not required to be one.

JSON Text example

{\"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

JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used:

Example: Parse JSON Text input line by line

The example below demonstrates how JSON Lines can be processed.

#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

Output:

{\"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

Note

Using operator>> like

json j;\nwhile (input >> j)\n{\n    std::cout << j << std::endl;\n}\n

with a JSON Lines input does not work, because the parser will try to parse one value after the last one.

"},{"location":"features/parsing/parse_exceptions/","title":"Parsing and Exceptions","text":"

When the input is not valid JSON, an exception of type parse_error 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 try/catch block, like

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

In case exceptions are undesired or not supported by the environment, there are different ways to proceed:

"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"

The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs (true, default) or whether a discarded value should be returned (false).

json j = json::parse(my_input, nullptr, false);\nif (j.is_discarded())\n{\n    std::cerr << \"parse error\" << std::endl;\n}\n

Note there is no diagnostic information available in this scenario.

"},{"location":"features/parsing/parse_exceptions/#use-accept-function","title":"Use accept() function","text":"

Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON.

if (!json::accept(my_input))\n{\n    std::cerr << \"parse error\" << std::endl;\n}\n

Again, there is no diagnostic information available.

"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","title":"User-defined SAX interface","text":"

Finally, you can implement the SAX interface and decide what should happen in case of a parse error.

This function has the following interface:

bool parse_error(std::size_t position,\n                 const std::string& last_token,\n                 const json::exception& ex);\n

The return value indicates whether the parsing should continue, so the function should usually return false.

Example
#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

Output:

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
"},{"location":"features/parsing/parser_callbacks/","title":"Parser Callbacks","text":""},{"location":"features/parsing/parser_callbacks/#overview","title":"Overview","text":"

With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.

The type of the callback function is:

template<typename BasicJsonType>\nusing parser_callback_t =\n    std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n
"},{"location":"features/parsing/parser_callbacks/#callback-event-types","title":"Callback event types","text":"

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 depth, event, and parsed.

parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example

When parsing the following JSON text,

{\n    \"name\": \"Berlin\",\n    \"location\": [\n        52.519444,\n        13.406667\n    ]\n}\n

these calls are made to the callback function:

event depth parsed object_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [52.519444,13.406667] object_end 0 {\"location\":[52.519444,13.406667],\"name\":\"Berlin\"}"},{"location":"features/parsing/parser_callbacks/#return-value","title":"Return value","text":"

Discarding a value (i.e., returning false) has different effects depending on the context in which the function was called:

Example

The example below demonstrates the parse() function with and without callback function.

#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

Output:

{\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
"},{"location":"features/parsing/sax_interface/","title":"SAX Interface","text":"

The library uses a SAX-like interface with the following functions:

// 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

The return value of each function determines whether parsing should proceed.

To implement your own SAX handler, proceed as follows:

  1. Implement the SAX interface in a class. You can use class nlohmann::json_sax<json> as base class, but you can also use any class where the functions described above are implemented and public.
  2. Create an object of your SAX interface class, e.g. my_sax.
  3. Call bool json::sax_parse(input, &my_sax); 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.

Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return json 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 parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file json_sax.hpp.

"},{"location":"features/parsing/sax_interface/#see-also","title":"See also","text":""},{"location":"features/types/","title":"Types","text":"

This page gives an overview how JSON values are stored and how this can be configured.

"},{"location":"features/types/#overview","title":"Overview","text":"

By default, JSON values are stored as follows:

JSON type C++ type object std::map<std::string, basic_json> array std::vector<basic_json> null std::nullptr_t string std::string boolean bool number std::int64_t, std::uint64_t, and double

Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.

"},{"location":"features/types/#storage","title":"Storage","text":""},{"location":"features/types/#template-arguments","title":"Template arguments","text":"

The data types to store a JSON value are derived from the template arguments passed to class basic_json:

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

Type json is an alias for basic_json<> and uses the default types.

From the template arguments, the following types are derived:

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
"},{"location":"features/types/#objects","title":"Objects","text":"

RFC 8259 describes JSON objects as follows:

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.

"},{"location":"features/types/#default-type","title":"Default type","text":"

With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:

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
"},{"location":"features/types/#behavior","title":"Behavior","text":"

The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:

"},{"location":"features/types/#key-order","title":"Key order","text":"

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 std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.

"},{"location":"features/types/#limits","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON object.

"},{"location":"features/types/#storage_1","title":"Storage","text":"

Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.

"},{"location":"features/types/#arrays","title":"Arrays","text":"

RFC 8259 describes JSON arrays as follows:

An array is an ordered sequence of zero or more values.

"},{"location":"features/types/#default-type_1","title":"Default type","text":"

With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:

std::vector<\n  basic_json, // value_type\n  std::allocator<basic_json> // allocator_type\n>\n
"},{"location":"features/types/#limits_1","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the maximum depth of nesting.

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 max_size function of a JSON array.

"},{"location":"features/types/#storage_2","title":"Storage","text":"

Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.

"},{"location":"features/types/#strings","title":"Strings","text":"

RFC 8259 describes JSON strings as follows:

A string is a sequence of zero or more Unicode characters.

Unicode values are split by the JSON class into byte-sized characters during deserialization.

"},{"location":"features/types/#default-type_2","title":"Default type","text":"

With the default values for StringType (std::string), the default value for string_t is std::string.

"},{"location":"features/types/#encoding","title":"Encoding","text":"

Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.

"},{"location":"features/types/#string-comparison","title":"String comparison","text":"

RFC 8259 states:

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 \"a\\\\b\" and \"a\\u005Cb\" are not equal.

This implementation is interoperable as it does compare strings code unit by code unit.

"},{"location":"features/types/#storage_3","title":"Storage","text":"

String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.

"},{"location":"features/types/#booleans","title":"Booleans","text":"

RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.

"},{"location":"features/types/#default-type_3","title":"Default type","text":"

With the default values for BooleanType (bool), the default value for boolean_t is bool.

"},{"location":"features/types/#storage_4","title":"Storage","text":"

Boolean values are stored directly inside a basic_json type.

"},{"location":"features/types/#numbers","title":"Numbers","text":"

See the number handling article for a detailed discussion on how numbers are handled by this library.

RFC 8259 describes numbers as follows:

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.

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, number_integer_t, number_unsigned_t, and number_float_t are used.

"},{"location":"features/types/#default-types","title":"Default types","text":"

With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t. With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t. With the default values for NumberFloatType (double), the default value for number_float_t is double.

"},{"location":"features/types/#default-behavior","title":"Default behavior","text":""},{"location":"features/types/#limits_2","title":"Limits","text":"

RFC 8259 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (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 number_unsigned_t or number_float_t.

When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. 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 number_integer_t or number_float_t.

RFC 8259 further states:

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.

As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.

RFC 8259 states:

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.

This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.

"},{"location":"features/types/#storage_5","title":"Storage","text":"

Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.

"},{"location":"features/types/number_handling/","title":"Number Handling","text":"

This document describes how the library is handling numbers.

"},{"location":"features/types/number_handling/#background","title":"Background","text":"

This section briefly summarizes how the JSON specification describes how numbers should be handled.

"},{"location":"features/types/number_handling/#json-number-syntax","title":"JSON number syntax","text":"

JSON defines the syntax of numbers as follows:

RFC 8259, Section 6

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.

A fraction part is a decimal point followed by one or more digits.

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.

The following railroad diagram from json.org visualizes the number syntax:

"},{"location":"features/types/number_handling/#number-interoperability","title":"Number interoperability","text":"

On number interoperability, the following remarks are made:

RFC 8259, Section 6

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.

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.

"},{"location":"features/types/number_handling/#library-implementation","title":"Library implementation","text":"

This section describes how the above number specification is implemented by this library.

"},{"location":"features/types/number_handling/#number-storage","title":"Number storage","text":"

In the default json type, numbers are stored as std::uint64_t, std::int64_t, and double, respectively. Thereby, std::uint64_t and std::int64_t 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 double.

Notes

Examples

"},{"location":"features/types/number_handling/#number-limits","title":"Number limits","text":"

Interoperability

"},{"location":"features/types/number_handling/#zeros","title":"Zeros","text":"

The JSON number grammar allows for different ways to express zero, and this library will store zeros differently:

Literal Stored value and type Serialization 0 std::uint64_t(0) 0 -0 std::int64_t(0) 0 0.0 double(0.0) 0.0 -0.0 double(-0.0) -0.0 0E0 double(0.0) 0.0 -0E0 double(-0.0) -0.0

That is, -0 is stored as a signed integer, but the serialization does not reproduce the -.

"},{"location":"features/types/number_handling/#number-serialization","title":"Number serialization","text":"

Notes regarding precision of floating-point numbers

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:

All examples here can be reproduced by passing the original double value to

std::printf(\"%.*g\\n\", std::numeric_limits<double>::max_digits10, double_value);\n
"},{"location":"features/types/number_handling/#nan-handling","title":"NaN handling","text":"

NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded:

RFC 8259, Section 6

Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.

That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment.

This library serializes NaN values as null. This corresponds to the behavior of JavaScript's JSON.stringify function.

Example

The following example shows how a NaN value is stored in a json value.

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

output:

val=nan\nj=null\nval=nan\n
"},{"location":"features/types/number_handling/#number-comparison","title":"Number comparison","text":"

Floating-point inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default.

Alternative comparison functions

To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance

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
Or you can self-define an operator equal function like this:

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

(see #703 for more information.)

Note

NaN values never compare equal to themselves or to other NaN values. See #514.

"},{"location":"features/types/number_handling/#number-conversion","title":"Number conversion","text":"

Just like the C++ language itself, the get family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising.

Unconditional number conversions

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

Note the last line with throw a json.exception.type_error.302 exception if jd is not a numerical type, for instance a string.

The rationale is twofold:

  1. JSON does not define a number type or precision (see above).
  2. C++ also allows to silently convert between number types.

Conditional number conversion

The code above can be solved by explicitly checking the nature of the value with members such as is_number_integer() or is_number_unsigned():

// 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

Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.

(Example taken from #777.)

"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"

As the example in Number conversion shows, there are different functions to determine the type of the stored number:

function unsigned integer signed integer floating-point string is_number() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"

The number types can be changed with template parameters.

position number type default type possible values 5 signed integers std::int64_t std::int32_t, std::int16_t, etc. 6 unsigned integers std::uint64_t std::uint32_t, std::uint16_t, etc. 7 floating-point double float, long double

Constraints on number types

Example

A basic_json type that uses long double as floating-point type.

using json_ld = nlohmann::basic_json<std::map, std::vector, std::string, bool,\n                                     std::int64_t, std::uint64_t, long double>;\n

Note values should then be parsed with json_ld::parse rather than json::parse as the latter would parse floating-point values to double before then converting them to long double.

"},{"location":"home/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"home/code_of_conduct/#our-pledge","title":"Our Pledge","text":"

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.

"},{"location":"home/code_of_conduct/#our-standards","title":"Our Standards","text":"

Examples of behavior that contributes to creating a positive environment include:

Examples of unacceptable behavior by participants include:

"},{"location":"home/code_of_conduct/#our-responsibilities","title":"Our Responsibilities","text":"

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.

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.

"},{"location":"home/code_of_conduct/#scope","title":"Scope","text":"

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.

"},{"location":"home/code_of_conduct/#enforcement","title":"Enforcement","text":"

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.

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.

"},{"location":"home/code_of_conduct/#attribution","title":"Attribution","text":"

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4

"},{"location":"home/design_goals/","title":"Design goals","text":"

There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:

Other aspects were not so important to us:

See the contribution guidelines for more information.

"},{"location":"home/exceptions/","title":"Exceptions","text":""},{"location":"home/exceptions/#overview","title":"Overview","text":""},{"location":"home/exceptions/#base-type","title":"Base type","text":"

All exceptions inherit from class json::exception (which in turn inherits from std::exception). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions.

"},{"location":"home/exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"

Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION. In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw), JSON_TRY_USER (overriding try), and JSON_CATCH_USER (overriding catch).

Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.

Example

The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.

#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

Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.

See documentation of JSON_TRY_USER, JSON_CATCH_USER and JSON_THROW_USER for more information.

"},{"location":"home/exceptions/#extended-diagnostic-messages","title":"Extended diagnostic messages","text":"

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.

Example
#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

Output:

[json.exception.type_error.302] type must be number, but is string\n

This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.

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.

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 JSON_DIAGNOSTICS to 1 before including json.hpp.

Example
#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

Output:

[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n

Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.

See documentation of JSON_DIAGNOSTICS for more information.

"},{"location":"home/exceptions/#parse-errors","title":"Parse errors","text":"

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.

Exceptions have ids 1xx.

Byte index

Member byte holds the byte index of the last read character in the input file.

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).

Example

The following code shows how a parse_error exception can be caught.

#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

Output:

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
"},{"location":"home/exceptions/#jsonexceptionparse_error101","title":"json.exception.parse_error.101","text":"

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 byte indicates the error position.

Example message

Input ended prematurely:

[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal\n

No input:

[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

Control character was not escaped:

[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

String was not closed:

[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

Invalid number format:

[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

\\u was not be followed by four hex digits:

[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

Invalid UTF-8 surrogate pair:

[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

Invalid UTF-8 byte:

[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

Tip

"},{"location":"home/exceptions/#jsonexceptionparse_error102","title":"json.exception.parse_error.102","text":"

JSON uses the \\uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \\uxxxx entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.

Example message

parse error at 14: missing or wrong low surrogate\n

Note

This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.

"},{"location":"home/exceptions/#jsonexceptionparse_error103","title":"json.exception.parse_error.103","text":"

Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.

Example message

parse error: code points above 0x10FFFF are invalid\n

Note

This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.

"},{"location":"home/exceptions/#jsonexceptionparse_error104","title":"json.exception.parse_error.104","text":"

RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.

Example message

[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\n
"},{"location":"home/exceptions/#jsonexceptionparse_error105","title":"json.exception.parse_error.105","text":"

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.

Example message

[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'\n
[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'\n
[json.exception.parse_error.105] parse error: operation value 'foo' is invalid\n

"},{"location":"home/exceptions/#jsonexceptionparse_error106","title":"json.exception.parse_error.106","text":"

An array index in a JSON Pointer (RFC 6901) may be 0 or any number without a leading 0.

Example message

[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n
"},{"location":"home/exceptions/#jsonexceptionparse_error107","title":"json.exception.parse_error.107","text":"

A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character.

Example message

[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n
"},{"location":"home/exceptions/#jsonexceptionparse_error108","title":"json.exception.parse_error.108","text":"

In a JSON Pointer, only ~0 and ~1 are valid escape sequences.

Example message

[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n
"},{"location":"home/exceptions/#jsonexceptionparse_error109","title":"json.exception.parse_error.109","text":"

A JSON Pointer array index must be a number.

Example messages

[json.exception.parse_error.109] parse error: array index 'one' is not a number\n
[json.exception.parse_error.109] parse error: array index '+1' is not a number\n

"},{"location":"home/exceptions/#jsonexceptionparse_error110","title":"json.exception.parse_error.110","text":"

When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.

Example message

[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input\n
[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A\n

"},{"location":"home/exceptions/#jsonexceptionparse_error112","title":"json.exception.parse_error.112","text":"

An unexpected byte was read in a binary format or length information is invalid (BSON).

Example messages

[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C\n
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1\n
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02\n
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02\n
[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
[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

"},{"location":"home/exceptions/#jsonexceptionparse_error113","title":"json.exception.parse_error.113","text":"

While parsing a map key, a value that is not a string has been read.

Example messages

[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
[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
[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

"},{"location":"home/exceptions/#jsonexceptionparse_error114","title":"json.exception.parse_error.114","text":"

The parsing of the corresponding BSON record type is not implemented (yet).

Example message

[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF\n
"},{"location":"home/exceptions/#jsonexceptionparse_error115","title":"json.exception.parse_error.115","text":"

A UBJSON high-precision number could not be parsed.

Example message

[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A\n
"},{"location":"home/exceptions/#iterator-errors","title":"Iterator errors","text":"

This exception is thrown if iterators passed to a library function do not match the expected semantics.

Exceptions have ids 2xx.

Example

The following code shows how an invalid_iterator exception can be caught.

#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

Output:

message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","title":"json.exception.invalid_iterator.201","text":"

The iterators passed to constructor basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.

Example message

[json.exception.invalid_iterator.201] iterators are not compatible\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","title":"json.exception.invalid_iterator.202","text":"

In the erase or insert function, the passed iterator pos 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.

Example messages

[json.exception.invalid_iterator.202] iterator does not fit current value\n
[json.exception.invalid_iterator.202] iterators first and last must point to objects\n

"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","title":"json.exception.invalid_iterator.203","text":"

Either iterator passed to function erase(IteratorType first, IteratorType last) 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.

Example message

[json.exception.invalid_iterator.203] iterators do not fit current value\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","title":"json.exception.invalid_iterator.204","text":"

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 (begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid.

Example message

[json.exception.invalid_iterator.204] iterators out of range\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","title":"json.exception.invalid_iterator.205","text":"

When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.

Example message

[json.exception.invalid_iterator.205] iterator out of range\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","title":"json.exception.invalid_iterator.206","text":"

The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.

Example message

[json.exception.invalid_iterator.206] cannot construct with iterators from null\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","title":"json.exception.invalid_iterator.207","text":"

The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.

Example message

[json.exception.invalid_iterator.207] cannot use key() for non-object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","title":"json.exception.invalid_iterator.208","text":"

The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.

Example message

[json.exception.invalid_iterator.208] cannot use operator[] for object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","title":"json.exception.invalid_iterator.209","text":"

The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.

Example message

[json.exception.invalid_iterator.209] cannot use offsets with object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","title":"json.exception.invalid_iterator.210","text":"

The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.

Example message

[json.exception.invalid_iterator.210] iterators do not fit\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","title":"json.exception.invalid_iterator.211","text":"

The iterator range passed to the insert function must not be a subrange of the container to insert to.

Example message

[json.exception.invalid_iterator.211] passed iterators may not belong to container\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","title":"json.exception.invalid_iterator.212","text":"

When two iterators are compared, they must belong to the same container.

Example message

[json.exception.invalid_iterator.212] cannot compare iterators of different containers\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","title":"json.exception.invalid_iterator.213","text":"

The order of object iterators cannot be compared, because JSON objects are unordered.

Example message

[json.exception.invalid_iterator.213] cannot compare order of object iterators\n
"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","title":"json.exception.invalid_iterator.214","text":"

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 begin().

Example message

[json.exception.invalid_iterator.214] cannot get value\n
"},{"location":"home/exceptions/#type-errors","title":"Type errors","text":"

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.

Exceptions have ids 3xx.

Example

The following code shows how a type_error exception can be caught.

#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

Output:

message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n
"},{"location":"home/exceptions/#jsonexceptiontype_error301","title":"json.exception.type_error.301","text":"

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.

Example message

[json.exception.type_error.301] cannot create object from initializer list\n
"},{"location":"home/exceptions/#jsonexceptiontype_error302","title":"json.exception.type_error.302","text":"

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.

Example messages

[json.exception.type_error.302] type must be object, but is null\n
[json.exception.type_error.302] type must be string, but is object\n

"},{"location":"home/exceptions/#jsonexceptiontype_error303","title":"json.exception.type_error.303","text":"

To retrieve a reference to a value stored in a basic_json object with get_ref, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t &.

Example messages

[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object\n
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"\n

"},{"location":"home/exceptions/#jsonexceptiontype_error304","title":"json.exception.type_error.304","text":"

The at() member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.304] cannot use at() with string\n
[json.exception.type_error.304] cannot use at() with number\n

"},{"location":"home/exceptions/#jsonexceptiontype_error305","title":"json.exception.type_error.305","text":"

The operator[] member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.305] cannot use operator[] with a string argument with array\n
[json.exception.type_error.305] cannot use operator[] with a numeric argument with object\n

"},{"location":"home/exceptions/#jsonexceptiontype_error306","title":"json.exception.type_error.306","text":"

The value() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.306] cannot use value() with number\n
"},{"location":"home/exceptions/#jsonexceptiontype_error307","title":"json.exception.type_error.307","text":"

The erase() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.307] cannot use erase() with string\n
"},{"location":"home/exceptions/#jsonexceptiontype_error308","title":"json.exception.type_error.308","text":"

The push_back() and operator+= member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.308] cannot use push_back() with string\n
"},{"location":"home/exceptions/#jsonexceptiontype_error309","title":"json.exception.type_error.309","text":"

The insert() member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.309] cannot use insert() with array\n
[json.exception.type_error.309] cannot use insert() with number\n

"},{"location":"home/exceptions/#jsonexceptiontype_error310","title":"json.exception.type_error.310","text":"

The swap() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.310] cannot use swap() with number\n
"},{"location":"home/exceptions/#jsonexceptiontype_error311","title":"json.exception.type_error.311","text":"

The emplace() and emplace_back() member functions can only be executed for certain JSON types.

Example messages

[json.exception.type_error.311] cannot use emplace() with number\n
[json.exception.type_error.311] cannot use emplace_back() with number\n

"},{"location":"home/exceptions/#jsonexceptiontype_error312","title":"json.exception.type_error.312","text":"

The update() member functions can only be executed for certain JSON types.

Example message

[json.exception.type_error.312] cannot use update() with array\n
"},{"location":"home/exceptions/#jsonexceptiontype_error313","title":"json.exception.type_error.313","text":"

The unflatten 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.

Example message

[json.exception.type_error.313] invalid value to unflatten\n
"},{"location":"home/exceptions/#jsonexceptiontype_error314","title":"json.exception.type_error.314","text":"

The unflatten function only works for an object whose keys are JSON Pointers.

Example message

Calling unflatten() on an array [1,2,3]:

[json.exception.type_error.314] only objects can be unflattened\n
"},{"location":"home/exceptions/#jsonexceptiontype_error315","title":"json.exception.type_error.315","text":"

The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive.

Example message

Calling unflatten() on an object {\"/1\", [1,2,3]}:

[json.exception.type_error.315] values in object must be primitive\n
"},{"location":"home/exceptions/#jsonexceptiontype_error316","title":"json.exception.type_error.316","text":"

The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded.

Example message

Calling dump() on a JSON value containing an ISO 8859-1 encoded string:

[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F\n

Tip

"},{"location":"home/exceptions/#jsonexceptiontype_error317","title":"json.exception.type_error.317","text":"

The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON)

Example messages

Serializing null to BSON:

[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n
Serializing [1,2,3] to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n

Tip

Encapsulate the JSON value in an object. That is, instead of serializing true, serialize {\"value\": true}

"},{"location":"home/exceptions/#out-of-range","title":"Out of range","text":"

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.

Exceptions have ids 4xx.

Example

The following code shows how an out_of_range exception can be caught.

#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

Output:

message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range401","title":"json.exception.out_of_range.401","text":"

The provided array index i is larger than size-1.

Example message

array index 3 is out of range\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range402","title":"json.exception.out_of_range.402","text":"

The special array index - 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.

Example message

array index '-' (3) is out of range\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range403","title":"json.exception.out_of_range.403","text":"

The provided key was not found in the JSON object.

Example message

key 'foo' not found\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range404","title":"json.exception.out_of_range.404","text":"

A reference token in a JSON Pointer could not be resolved.

Example message

unresolved reference token 'foo'\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range405","title":"json.exception.out_of_range.405","text":"

The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.

Example message

JSON pointer has no parent\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range406","title":"json.exception.out_of_range.406","text":"

A parsed number could not be stored as without changing it to NaN or INF.

Example message

number overflow parsing '10E1000'\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range407","title":"json.exception.out_of_range.407","text":"

UBJSON and BSON only support integer numbers up to 9223372036854775807.

Example message

number overflow serializing '9223372036854775808'\n

Note

Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.

"},{"location":"home/exceptions/#jsonexceptionout_of_range408","title":"json.exception.out_of_range.408","text":"

The size (following #) of an UBJSON array or object exceeds the maximal capacity.

Example message

excessive array size: 8658170730974374167\n
"},{"location":"home/exceptions/#jsonexceptionout_of_range409","title":"json.exception.out_of_range.409","text":"

Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.

Example message

BSON key cannot contain code point U+0000 (at byte 2)\n
"},{"location":"home/exceptions/#further-exceptions","title":"Further exceptions","text":"

This exception is thrown in case of errors that cannot be classified with the other exception types.

Exceptions have ids 5xx.

Example

The following code shows how an other_error exception can be caught.

#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

Output:

message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n
"},{"location":"home/exceptions/#jsonexceptionother_error501","title":"json.exception.other_error.501","text":"

A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.

Example message

Executing {\"op\":\"test\", \"path\":\"/baz\", \"value\":\"bar\"} on {\"baz\": \"qux\"}:

[json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}\n
"},{"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":"

Question

Why does

json j{true};\n

and

json j(true);\n

yield different results ([true] vs. true)?

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

json array = {1, 2, 3, 4};\n

for arrays and

json object = {{\"one\", 1}, {\"two\", 2}}; \n

for objects.

Tip

To avoid any confusion and ensure portable code, do not use brace initialization with the types basic_json, json, or ordered_json unless you want to create an object or array as shown in the examples above.

"},{"location":"home/faq/#limitations","title":"Limitations","text":""},{"location":"home/faq/#relaxed-parsing","title":"Relaxed parsing","text":"

Question

Can you add an option to ignore trailing commas?

This library does not support any feature which would jeopardize interoperability.

"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","title":"Parse errors reading non-ASCII characters","text":"

Questions

The library supports Unicode input as follows:

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.

"},{"location":"home/faq/#wide-string-handling","title":"Wide string handling","text":"

Question

Why are wide strings (e.g., std::wstring) dumped as arrays of numbers?

As described above, the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding.

Example

#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

The result is:

{\n  \"encoded\": \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\",\n  \"original\": [36554, 66, 49, 50, 51, 52, 32, 12371, 12435, 12395, 12385, 12399]\n}\n
"},{"location":"home/faq/#exceptions","title":"Exceptions","text":""},{"location":"home/faq/#parsing-without-exceptions","title":"Parsing without exceptions","text":"

Question

Is it possible to indicate a parse error without throwing an exception?

Yes, see Parsing and exceptions.

"},{"location":"home/faq/#key-name-in-exceptions","title":"Key name in exceptions","text":"

Question

Can I get the key of the object item that caused an exception?

Yes, you can. Please define the symbol JSON_DIAGNOSTICS to get extended diagnostics messages.

"},{"location":"home/faq/#serialization-issues","title":"Serialization issues","text":""},{"location":"home/faq/#number-precision","title":"Number precision","text":"

Question

The library uses std::numeric_limits<number_float_t>::digits10 (15 for IEEE doubles) 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.

cppreference.com

The value of std::numeric_limits<T>::digits10 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.

Tip

The website https://float.exposed gives a good insight into the internal storage of floating-point numbers.

See this section on the library's number handling for more information.

"},{"location":"home/faq/#compilation-issues","title":"Compilation issues","text":""},{"location":"home/faq/#android-sdk","title":"Android SDK","text":"

Question

Why does the code not compile with Android SDK?

Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.

APP_STL := c++_shared\nNDK_TOOLCHAIN_VERSION := clang3.6\nAPP_CPPFLAGS += -frtti -fexceptions\n

The code compiles successfully with Android NDK, Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.

"},{"location":"home/faq/#missing-stl-function","title":"Missing STL function","text":"

Questions

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 APP_STL := gnustl_static, please refer to this discussion.

"},{"location":"home/license/","title":"License","text":"

The class is licensed under the MIT License:

Copyright \u00a9 2013-2022 Niels Lohmann

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.

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

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

The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0.

"},{"location":"home/releases/","title":"Releases","text":""},{"location":"home/releases/#v373","title":"v3.7.3","text":"

Files

Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)

"},{"location":"home/releases/#summary","title":"Summary","text":"

This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes","title":"Bug Fixes","text":""},{"location":"home/releases/#deprecated-functions","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v372","title":"v3.7.2","text":"

Files

Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)

"},{"location":"home/releases/#summary_1","title":"Summary","text":"

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.

"},{"location":"home/releases/#bug-fixes_1","title":"Bug Fixes","text":""},{"location":"home/releases/#further-changes","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_1","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v371","title":"v3.7.1","text":"

Files

Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)

"},{"location":"home/releases/#summary_2","title":"Summary","text":"

This release fixes several small bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_2","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements","title":"Improvements","text":""},{"location":"home/releases/#further-changes_1","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_2","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v370","title":"v3.7.0","text":"

Files

Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)

"},{"location":"home/releases/#summary_3","title":"Summary","text":"

This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.

"},{"location":"home/releases/#new-features","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_3","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_1","title":"Improvements","text":""},{"location":"home/releases/#further-changes_2","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_3","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v361","title":"v3.6.1","text":"

Files

Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)

"},{"location":"home/releases/#summary_4","title":"Summary","text":"

This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_4","title":"Bug Fixes","text":""},{"location":"home/releases/#further-changes_3","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_4","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v360","title":"v3.6.0","text":"

Files

Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip)

\u2139\ufe0f This release introduced a regression. Please update to version 3.6.1!

"},{"location":"home/releases/#summary_5","title":"Summary","text":"

This release adds some convenience functions for JSON Pointers, introduces a contains 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.

"},{"location":"home/releases/#new-features_1","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_5","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_2","title":"Improvements","text":""},{"location":"home/releases/#further-changes_4","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_5","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v350","title":"v3.5.0","text":"

Files

Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)

"},{"location":"home/releases/#summary_6","title":"Summary","text":"

This release introduces the support for structured bindings and reading from FILE*. Besides, a few bugs have been fixed. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_2","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_6","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_3","title":"Improvements","text":""},{"location":"home/releases/#further-changes_5","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_6","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v340","title":"v3.4.0","text":"

Files

Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)

"},{"location":"home/releases/#summary_7","title":"Summary","text":"

This release introduces three new features:

Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_3","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_7","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_4","title":"Improvements","text":""},{"location":"home/releases/#further-changes_6","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_7","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v330","title":"v3.3.0","text":"

Files

Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)

"},{"location":"home/releases/#summary_8","title":"Summary","text":"

This release adds support for GCC 4.8. Furthermore, it adds a function get_to to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented.

Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_4","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_8","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_5","title":"Improvements","text":""},{"location":"home/releases/#further-changes_7","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_8","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v320","title":"v3.2.0","text":"

Files

Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)

"},{"location":"home/releases/#summary_9","title":"Summary","text":"

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 parse, accept, from_cbor, from_msgpack, and from_ubjson 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 std::vector<bool> to track the hierarchy of structured values) which allows to process nested input more efficiently.

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.

This release further fixes several bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#new-features_5","title":"New Features","text":""},{"location":"home/releases/#bug-fixes_9","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_6","title":"Improvements","text":""},{"location":"home/releases/#further-changes_8","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_9","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v312","title":"v3.1.2","text":"

Files

Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)

"},{"location":"home/releases/#summary_10","title":"Summary","text":"

This release fixes several bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_10","title":"Bug Fixes","text":""},{"location":"home/releases/#improvements_7","title":"Improvements","text":""},{"location":"home/releases/#further-changes_9","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_10","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v311","title":"v3.1.1","text":"

Files

Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)

"},{"location":"home/releases/#summary_11","title":"Summary","text":"

This release fixes several bugs in the library. All changes are backward-compatible.

"},{"location":"home/releases/#bug-fixes_11","title":"Bug Fixes","text":""},{"location":"home/releases/#further-changes_10","title":"Further Changes","text":""},{"location":"home/releases/#deprecated-functions_11","title":"Deprecated functions","text":"

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):

"},{"location":"home/releases/#v310","title":"v3.1.0","text":"

Files

Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)

"},{"location":"home/releases/#summary_12","title":"Summary","text":"

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.

"},{"location":"home/releases/#new-features_6","title":"New features","text":""},{"location":"home/releases/#improvements_8","title":"Improvements","text":""},{"location":"home/releases/#reorganization","title":"Reorganization","text":""},{"location":"home/releases/#further-changes_11","title":"Further changes","text":""},{"location":"home/releases/#deprecated-functions_12","title":"Deprecated functions","text":"

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):

Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.

"},{"location":"home/releases/#v301","title":"v3.0.1","text":"

Files

Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c

"},{"location":"home/releases/#summary_13","title":"Summary","text":"

This release fixes small issues in the implementation of JSON Pointer and JSON Patch. All changes are backward-compatible.

"},{"location":"home/releases/#changes","title":"Changes","text":""},{"location":"home/releases/#deprecated-functions_13","title":"Deprecated functions","text":"

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):

Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.

"},{"location":"home/releases/#v300","title":"v3.0.0","text":"

Files

Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462

"},{"location":"home/releases/#summary_14","title":"Summary","text":"

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.

"},{"location":"home/releases/#breaking-changes","title":"Breaking changes","text":"

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.

"},{"location":"home/releases/#deprecated-functions_14","title":"Deprecated functions","text":"

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):

Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.

"},{"location":"home/releases/#new-features_7","title":"New features","text":"

With all this breaking and deprecation out of the way, let's talk about features!

"},{"location":"home/releases/#further-changes_12","title":"Further changes","text":"

Furthermore, there have been a lot of changes under the hood:

"},{"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":"

There are five different exceptions inheriting from json::exception:

To support these exception, the try/catch blocks of your code need to be adjusted:

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":""},{"location":"home/releases/#removal-of-deprecated-functions","title":"Removal of deprecated functions","text":"

Function explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) should be replaced by the parse function: Let ss be a stream and cb be a parse callback function.

Old code:

json j(ss, cb);\n

New code:

json j = json::parse(ss, cb);\n

If no callback function is used, also the following code works:

json j;\nj << ss;\n

or

json j;\nss >> j;\n
"},{"location":"home/releases/#v211","title":"v2.1.1","text":"

Files

Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57

"},{"location":"home/releases/#summary_15","title":"Summary","text":"

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.

"},{"location":"home/releases/#changes_1","title":"Changes","text":""},{"location":"home/releases/#v210","title":"v2.1.0","text":"

Files

"},{"location":"home/releases/#summary_16","title":"Summary","text":"

This release introduces a means to convert from/to user-defined types. The release is backwards compatible.

"},{"location":"home/releases/#changes_2","title":"Changes","text":""},{"location":"home/releases/#v2010","title":"v2.0.10","text":"

Files

"},{"location":"home/releases/#summary_17","title":"Summary","text":"

This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.

"},{"location":"home/releases/#changes_3","title":"Changes","text":""},{"location":"home/releases/#v209","title":"v2.0.9","text":"

Files

"},{"location":"home/releases/#summary_18","title":"Summary","text":"

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.

"},{"location":"home/releases/#changes_4","title":"Changes","text":""},{"location":"home/releases/#v208","title":"v2.0.8","text":"

Files

"},{"location":"home/releases/#summary_19","title":"Summary","text":"

This release combines a lot of small fixes and improvements. The fixes are backwards compatible.

"},{"location":"home/releases/#changes_5","title":"Changes","text":""},{"location":"home/releases/#v207","title":"v2.0.7","text":"

Files

"},{"location":"home/releases/#summary_20","title":"Summary","text":"

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.

"},{"location":"home/releases/#changes_6","title":"Changes","text":""},{"location":"home/releases/#v206","title":"v2.0.6","text":"

Files

"},{"location":"home/releases/#summary_21","title":"Summary","text":"

This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible.

"},{"location":"home/releases/#changes_7","title":"Changes","text":""},{"location":"home/releases/#v205","title":"v2.0.5","text":"

Files

"},{"location":"home/releases/#summary_22","title":"Summary","text":"

This release fixes a regression bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.

"},{"location":"home/releases/#changes_8","title":"Changes","text":""},{"location":"home/releases/#v204","title":"v2.0.4","text":"

Files

"},{"location":"home/releases/#summary_23","title":"Summary","text":"

This release fixes a bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.

"},{"location":"home/releases/#changes_9","title":"Changes","text":""},{"location":"home/releases/#v203","title":"v2.0.3","text":"

Files

"},{"location":"home/releases/#summary_24","title":"Summary","text":"

This release combines a lot of small fixes and improvements. The release is backwards compatible.

"},{"location":"home/releases/#changes_10","title":"Changes","text":""},{"location":"home/releases/#v202","title":"v2.0.2","text":"

Files

"},{"location":"home/releases/#summary_25","title":"Summary","text":"

This release combines a lot of small fixes and improvements. The release is backwards compatible.

"},{"location":"home/releases/#changes_11","title":"Changes","text":""},{"location":"home/releases/#v201","title":"v2.0.1","text":"

Files

"},{"location":"home/releases/#summary_26","title":"Summary","text":"

This release fixes a performance regression in the JSON serialization (function dump()). This fix is backwards compatible.

"},{"location":"home/releases/#changes_12","title":"Changes","text":""},{"location":"home/releases/#v200","title":"v2.0.0","text":"

Files

"},{"location":"home/releases/#summary_27","title":"Summary","text":"

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.

As noexcept and constexpr 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.

"},{"location":"home/releases/#changes_13","title":"Changes","text":""},{"location":"home/releases/#notes","title":"Notes","text":""},{"location":"home/releases/#v110","title":"v1.1.0","text":"

Files

"},{"location":"home/releases/#summary_28","title":"Summary","text":"

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:

"},{"location":"home/releases/#changes_14","title":"Changes","text":""},{"location":"home/releases/#notes_1","title":"Notes","text":"

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.

"},{"location":"home/releases/#v100","title":"v1.0.0","text":"

Files

"},{"location":"home/releases/#summary_29","title":"Summary","text":"

This is the first official release. Compared to the prerelease version 1.0.0-rc1, only a few minor improvements have been made:

"},{"location":"home/releases/#changes_15","title":"Changes","text":""},{"location":"home/sponsors/","title":"Sponsors","text":"

You can sponsor this library at GitHub Sponsors.

"},{"location":"home/sponsors/#named-sponsors","title":"Named Sponsors","text":"

Thanks everyone!

"},{"location":"integration/","title":"Header only","text":"

json.hpp is the single required file in single_include/nlohmann or released here. You need to add

#include <nlohmann/json.hpp>\n\n// for convenience\nusing json = nlohmann::json;\n

to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang).

You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.

"},{"location":"integration/cmake/","title":"CMake","text":""},{"location":"integration/cmake/#integration","title":"Integration","text":"

You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags.

"},{"location":"integration/cmake/#external","title":"External","text":"

To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration:

Example

CMakeLists.txt
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

The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.

"},{"location":"integration/cmake/#embedded","title":"Embedded","text":"

To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.

Example

CMakeLists.txt
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

Note

Do not use include(nlohmann_json/CMakeLists.txt), 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 include(...) for pulling in other CMake projects anyways.

"},{"location":"integration/cmake/#supporting-both","title":"Supporting Both","text":"

To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.

Example

CMakeLists.txt
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
thirdparty/CMakeLists.txt
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

thirdparty/nlohmann_json is then a complete copy of this source tree.

"},{"location":"integration/cmake/#fetchcontent","title":"FetchContent","text":"

Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type.

Example

CMakeLists.txt
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

Note

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

FetchContent_Declare(json\n    GIT_REPOSITORY https://github.com/nlohmann/json\n    GIT_TAG v3.11.3\n)\n

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.

"},{"location":"integration/cmake/#cmake-options","title":"CMake Options","text":""},{"location":"integration/cmake/#json_buildtests","title":"JSON_BuildTests","text":"

Build the unit tests when BUILD_TESTING is enabled. This option is ON 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.

"},{"location":"integration/cmake/#json_ci","title":"JSON_CI","text":"

Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.

"},{"location":"integration/cmake/#json_diagnostics","title":"JSON_Diagnostics","text":"

Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS. This option is OFF by default.

"},{"location":"integration/cmake/#json_disableenumserialization","title":"JSON_DisableEnumSerialization","text":"

Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION. This option is OFF by default.

"},{"location":"integration/cmake/#json_fasttests","title":"JSON_FastTests","text":"

Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests.

"},{"location":"integration/cmake/#json_globaludls","title":"JSON_GlobalUDLs","text":"

Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS. This option is OFF by default.

"},{"location":"integration/cmake/#json_implicitconversions","title":"JSON_ImplicitConversions","text":"

Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS. This option is ON by default.

"},{"location":"integration/cmake/#json_install","title":"JSON_Install","text":"

Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project.

"},{"location":"integration/cmake/#json_multipleheaders","title":"JSON_MultipleHeaders","text":"

Use non-amalgamated version of the library. This option is OFF by default.

"},{"location":"integration/cmake/#json_systeminclude","title":"JSON_SystemInclude","text":"

Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default.

"},{"location":"integration/cmake/#json_valgrind","title":"JSON_Valgrind","text":"

Execute test suite with Valgrind. This option is OFF by default. Depends on JSON_BuildTests.

"},{"location":"integration/migration_guide/","title":"Migration Guide","text":"

This page collects some guidelines on how to future-proof your code for future versions of this library.

"},{"location":"integration/migration_guide/#replace-deprecated-functions","title":"Replace deprecated functions","text":"

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 HEDLEY_DEPRECATED_FOR to report which function to use instead.

"},{"location":"integration/migration_guide/#parsing","title":"Parsing","text":""},{"location":"integration/migration_guide/#json-pointers","title":"JSON Pointers","text":""},{"location":"integration/migration_guide/#miscellaneous-functions","title":"Miscellaneous functions","text":""},{"location":"integration/migration_guide/#replace-implicit-conversions","title":"Replace implicit conversions","text":"

Implicit conversions via operator ValueType will be switched off by default in the next major release of the library.

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get, get_to, get_ref, or get_ptr.

DeprecatedFuture-proofFuture-proof (alternative)
nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n
nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n
nlohmann::json j = \"Hello, world!\";\nstd::string s;\nj.get_to(s);\n

You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.

"},{"location":"integration/migration_guide/#import-namespace-literals-for-udls","title":"Import namespace literals for UDLs","text":"

The user-defined string literals operator\"\"_json and operator\"\"_json_pointer will be removed from the global namespace in the next major release of the library.

DeprecatedFuture-proof
nlohmann::json j = \"[1,2,3]\"_json;\n
using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n

To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.

"},{"location":"integration/migration_guide/#do-not-hard-code-the-complete-library-namespace","title":"Do not hard-code the complete library namespace","text":"

The nlohmann namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use nlohmann as namespace or, when the exact version and configuration is relevant, use macro NLOHMANN_JSON_NAMESPACE to denote the namespace.

DangerousFuture-proofFuture-proof (alternative)
void to_json(nlohmann::json_abi_v3_11_2::json& j, const person& p)\n{\n    j[\"age\"] = p.age;\n}\n
void to_json(nlohmann::json& j, const person& p)\n{\n    j[\"age\"] = p.age;\n}\n
void to_json(NLOHMANN_JSON_NAMESPACE::json& j, const person& p)\n{\n    j[\"age\"] = p.age;\n}\n
"},{"location":"integration/migration_guide/#do-not-use-the-details-namespace","title":"Do not use the details namespace","text":"

The details 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 details namespace.

"},{"location":"integration/package_managers/","title":"Package Managers","text":"

Throughout this page, we will describe how to compile the example file example.cpp below.

#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

When executed, this program should create output similar to

{\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
"},{"location":"integration/package_managers/#homebrew","title":"Homebrew","text":"

If you are using OS X and Homebrew, just type

brew install nlohmann-json\n

and you're set. If you want the bleeding edge rather than the latest release, use

brew install nlohmann-json --HEAD\n

instead. See nlohmann-json for more information.

Example
  1. Create the following file:

    example.cpp
    #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
  2. Install the package

    brew install nlohmann-json\n
  3. Determine the include path, which defaults to /usr/local/Cellar/nlohmann-json/$version/include, where $version is the version of the library, e.g. 3.7.3. The path of the library can be determined with

    brew list nlohmann-json\n
  4. Compile the code. For instance, the code can be compiled using Clang with

    clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std=c++11 -o example\n

The formula is updated automatically.

"},{"location":"integration/package_managers/#meson","title":"Meson","text":"

If you are using the Meson Build System, add this source tree as a meson subproject. You may also use the include.zip 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 meson wrap install nlohmann_json. Please see the meson project for any issues regarding the packaging.

The provided meson.build can also be used as an alternative to cmake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly.

"},{"location":"integration/package_managers/#bazel","title":"Bazel","text":"

This repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive, git_repository, or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g. via deps attribute).

"},{"location":"integration/package_managers/#conan","title":"Conan","text":"

If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages.

Example
  1. Create the following files:

    Conanfile.txt
    [requires]\nnlohmann_json/3.7.3\n\n[generators]\ncmake\n
    CMakeLists.txt
    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
    example.cpp
    #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
  2. Build:

    mkdir build\ncd build\nconan install ..\ncmake ..\ncmake --build .\n

The package is updated automatically.

"},{"location":"integration/package_managers/#spack","title":"Spack","text":"

If you are using Spack to manage your dependencies, you can use the nlohmann-json package. Please see the spack project for any issues regarding the packaging.

"},{"location":"integration/package_managers/#hunter","title":"Hunter","text":"

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.

"},{"location":"integration/package_managers/#buckaroo","title":"Buckaroo","text":"

If you are using Buckaroo, you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json. Please file issues here. There is a demo repo here.

"},{"location":"integration/package_managers/#vcpkg","title":"vcpkg","text":"

If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with vcpkg install nlohmann-json and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging.

Example
  1. Create the following files:

    CMakeLists.txt
    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
    example.cpp
    #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
  2. Install package:

    vcpkg install nlohmann-json\n
  3. Build:

    mkdir build\ncd build\ncmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake\ncmake --build .\n

Note you need to adjust /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake to your system.

"},{"location":"integration/package_managers/#cget","title":"cget","text":"

If you are using cget, you can install the latest development version with cget install nlohmann/json. A specific version can be installed with cget install nlohmann/json@v3.1.0. Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON).

cget reads directly from the GitHub repository and is always up-to-date.

"},{"location":"integration/package_managers/#cocoapods","title":"CocoaPods","text":"

If you are using CocoaPods, you can use the library by adding pod \"nlohmann_json\", '~>3.1.2' to your podfile (see an example). Please file issues here.

"},{"location":"integration/package_managers/#nuget","title":"NuGet","text":"

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.

"},{"location":"integration/package_managers/#conda","title":"Conda","text":"

If you are using conda, you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json. Please file issues here.

"},{"location":"integration/package_managers/#msys2","title":"MSYS2","text":"

If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages.

The package is updated automatically.

"},{"location":"integration/package_managers/#macports","title":"MacPorts","text":"

If you are using MacPorts, execute sudo port install nlohmann-json to install the nlohmann-json package.

The package is updated automatically.

"},{"location":"integration/package_managers/#build2","title":"build2","text":"

If you are using build2, you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository. In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints). If you are not familiar with using dependencies in build2, please read this introduction. Please file issues here if you experience problems with the packages.

The package is updated automatically.

"},{"location":"integration/package_managers/#wsjcpp","title":"wsjcpp","text":"

If you are using wsjcpp, you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch.

wsjcpp reads directly from the GitHub repository and is always up-to-date.

"},{"location":"integration/package_managers/#cpmcmake","title":"CPM.cmake","text":"

If you are using CPM.cmake, you can check this example. After adding CPM script to your project, implement the following snippet to your CMake:

CPMAddPackage(\n    NAME nlohmann_json\n    GITHUB_REPOSITORY nlohmann/json\n    VERSION 3.9.1)\n
"},{"location":"integration/pkg-config/","title":"Pkg-config","text":"

If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed:

pkg-config nlohmann_json --cflags\n

Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config:

json = dependency('nlohmann_json', required: true)\n
"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index bfcae5f2c..5f5fa1eb1 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,1122 +2,1122 @@ https://json.nlohmann.me/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/operator_gtgt/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/operator_literal_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/operator_literal_json_pointer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/operator_ltlt/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/ordered_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/ordered_map/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/adl_serializer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/adl_serializer/from_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/adl_serializer/to_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/accept/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/array/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/array_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/at/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/back/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/basic_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/begin/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/binary/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/binary_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/boolean_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/cbegin/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/cbor_tag_handler_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/cend/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/clear/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/contains/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/count/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/crbegin/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/crend/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/default_object_comparator_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/diff/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/dump/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/emplace/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/emplace_back/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/empty/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/end/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/erase/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/error_handler_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/exception/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/find/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/flatten/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/from_bjdata/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/from_bson/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/from_cbor/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/from_msgpack/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/from_ubjson/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/front/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/get/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/get_allocator/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/get_binary/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/get_ptr/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/get_ref/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/get_to/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/input_format_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/insert/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/invalid_iterator/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_array/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_binary/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_boolean/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_discarded/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_null/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_number/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_number_float/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_number_integer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_number_unsigned/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_object/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_primitive/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_string/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/is_structured/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/items/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/json_base_class_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/json_serializer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/max_size/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/merge_patch/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/meta/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/number_float_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/number_integer_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/number_unsigned_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/object/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/object_comparator_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/object_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator%2B%3D/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator%3D/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_ValueType/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_eq/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_ge/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_gt/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_le/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_lt/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_ne/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_spaceship/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/operator_value_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/other_error/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/out_of_range/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/parse/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/parse_error/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/parse_event_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/parser_callback_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/patch/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/patch_inplace/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/push_back/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/rbegin/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/rend/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/sax_parse/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/size/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/std_hash/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/std_swap/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/string_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/swap/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/to_bjdata/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/to_bson/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/to_cbor/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/to_msgpack/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/to_string/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/to_ubjson/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/type/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/type_error/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/type_name/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/unflatten/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/update/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/value/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/value_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/basic_json/~basic_json/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/byte_container_with_subtype/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/back/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/empty/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/json_pointer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/operator_eq/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/operator_ne/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/operator_slash/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/operator_string_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/parent_pointer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/pop_back/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/push_back/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/string_t/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_pointer/to_string/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/binary/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/boolean/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/end_array/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/end_object/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/key/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/null/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/number_float/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/number_integer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/number_unsigned/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/parse_error/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/start_array/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/start_object/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/json_sax/string/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_assert/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_diagnostics/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_disable_enum_serialization/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_has_cpp_11/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_has_filesystem/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_has_ranges/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_has_static_rtti/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_has_three_way_comparison/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_no_io/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_noexception/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_skip_library_version_check/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_skip_unsupported_compiler_check/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_throw_user/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_use_global_udls/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_use_implicit_conversions/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/json_use_legacy_discarded_value_comparison/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_json_namespace/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_json_namespace_begin/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_json_namespace_no_version/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_json_serialize_enum/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/api/macros/nlohmann_json_version_major/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/arbitrary_types/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/assertions/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_values/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/comments/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/enum_conversion/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/iterators/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/json_patch/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/json_pointer/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/macros/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/merge_patch/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/namespace/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/object_order/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_formats/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_formats/bjdata/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_formats/bson/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_formats/cbor/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_formats/messagepack/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/binary_formats/ubjson/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/element_access/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/element_access/checked_access/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/element_access/default_value/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/element_access/unchecked_access/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/parsing/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/parsing/json_lines/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/parsing/parse_exceptions/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/parsing/parser_callbacks/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/parsing/sax_interface/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/types/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/features/types/number_handling/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/code_of_conduct/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/design_goals/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/exceptions/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/faq/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/license/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/releases/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/home/sponsors/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/integration/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/integration/cmake/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/integration/migration_guide/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/integration/package_managers/ - 2023-11-28 + 2024-04-10 daily https://json.nlohmann.me/integration/pkg-config/ - 2023-11-28 + 2024-04-10 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index ac5932b983ff1e7e7aad7f80b06532ccddad7006..2e77f76efbc0e19dada25f33e4bcf77888163904 100644 GIT binary patch delta 1123 zcmV-p1f2Wy4D}2MABzYG;k*`Rkq8|GoOCU)ktr{KPmi-bd*GOicOTEMFR#we*lFJz zH-0?-?aQwhKc0WOeRH!!n>e49lU@3FKII&K-fXtp?PW5VXA0@k$8nSNRNkb`dT?`f z`P2FBo3rw$7udgQj~natZM{k=m$^&cT{`QhnVh?vd2_R=A0MAhDbK#YeRuWl{l(S$ zi|eZma>{z_=rlc%8+nNQ^|9pO0e`#CZ-4j&h!+a>!{@gjfOysKWEcLj3k<}}Ux8pp zB*~6Ic1&3$$yy}IIwZ-aK$_EJ0ub{$$fPWEGPPtbT zr3r&HZ7Cp-)=fKv*$G3Q*~6ruS5%19;{uA2eqKOflFth(%7%SGMah!S5Yg63iL&f# ztd3>?u`Uj#R%!`ljsg&A3#Nf!A~;ch%5UDY%dFN;6CBmnJg0otjaAb$#uC!TOh?ig_bilzYa6DIy1*D(}svU1~%-ysH53gJP> z6X-y(?mz;Wir|AnnJ=VomYu*Nsjc*I-@X=u9;M@nF4ujg6kVx%z+~5puGBsO6`g8- zAiZbt!W3NWe8ecec=#o&?7HEXw8Be<54iGEM1HpL_|y$IN|GXn#{%KBIhtG8X+-ElKPO=oq$Os?qw6tXg`TK#0v8tkI^H@w-*Q zQP3@qq<7C<;npfW6tn$wSoJ&@$Eqd8l?8uXlHBf4-(z>>cR}Od&q*|Mt4f80R+0;R z{sFysEvwN%;y<*PYD+XE@+TK&raO_buYsv{a7!DCoypDXs(+>>iAHTv5TWztfpWde zUz;LDgO=%gW|u`Xw#dx0!z3B?sl&5qdG2?$g;pxRpcI=Ua^MsjKYk_@-AV9(DcLVP zK&}nV+8yNqCZK&U{{%!Tw)FE=;3RuWdVwpn4D>bJViFRKEVLl>HEOZ7md`$w6t$BX{A;PrQ8;Q^+cBM<>7Io%&Srh3#>Mo~ pY3t&-tf5u;tUQTV&u~9pl!vD3ac zZv1rq+t*(&KAwNReRH!!n>e49lU@3BKII&K-fXtp?PW5VXA0@k$8nSNRNkb`dT{gZ z@~89LH)rKhFR*{r9yiwO+j^B$E_0W>yL8r1GdXuT^X6t#KR!O2Ql5Q(d;RYE{l(SQ z#r4Mxa>{z_=rlc%8+nNQ?Xl$G0e|(Ex9@)e;)R0!@a63XAYS!5*@eIE0s}GgHz3#% zNwOo59a9!bvKC3Q4oR{pkmfX*0L1)ItuBPqkf-A9wgfK#*d;4Js8}y9pSC!;2?Y~H z16J4vb`UOk!;MOlwKcgH0~sP*(=e5BASvEqNfStZH%d7QMm0*JM+GtwV1ERaQ|{G7 zX~G~)TM7uIb<+-EcEXTn_An{v6%``&xPW4$pBGS=i8@;hR57cEQf3m|{_+^UhU0Yz>goyvb}*LHE@hrUfLpqJ z0)Z`)LK$@`=4?QS^AwrYmUe4lt4R>!&Us}#1gG?7zQ?rb-UMY$7wa8T*85i~J+atW z)_3s5CtpJFF>~J(+JDrR&nVxZj77gyOA@;RI)*KnYP7y1tCrp-5Mnb2YqY6l{BBin z6m-iY>D_ZzxV1_T#cV$vRy_~Kv1&hLUDp8H*Gp_R%nD8=T895}_skDm!ecM?2cO7;s6 zkZVJ;c1L-D325KTKLL@7E&Y5IILV%pUf>EX1APs*n1n-y(UZsxx5g;i zMm55LzDY&1Mza&yZL8tM;+jxmvA=8zMeSq;|5|EulsB5zc1)*dx@X~xvsquMaWTDg o+PZiyYiLzID^KFpGu)3CWg;BRe=uFQr^Na8FUNJ-C04NJC6aWAK