{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"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.

Invalid Unicode escapes and unpaired surrogates in the input are reported as parse_error.101 with a detailed message.

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);\njson operator \"\"_json(const char8_t* s, std::size_t n);  // since C++20\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/#see-also","title":"See also","text":""},{"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);\njson_pointer operator \"\"_json_pointer(const char8_t* s, std::size_t n);  // since C++20\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.
  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 pointer\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/#see-also","title":"See also","text":""},{"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/#iterator-invalidation","title":"Iterator invalidation","text":"

The type is based on ordered_map which in turn uses a std::vector to store object elements. Therefore, adding object elements can yield a reallocation in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Also, any iterator or reference after the insertion point will point to the same index, which is now a different value.

"},{"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/#iterator-invalidation","title":"Iterator invalidation","text":"

The type uses a std::vector to store object elements. Therefore, adding elements can yield a reallocation in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

"},{"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 similarly 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":"
  1. (none) -- the converted value is written to the output parameter val.
  2. the JSON value j converted to TargetType
"},{"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 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.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.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":"

All operations that add values to an array (push_back , operator+=, emplace_back, insert, and operator[] for a non-existing index) can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

For ordered_json, also all operations that add a value to an object (push_back, operator+=, emplace, insert, update, and operator[] for a non-existing key) can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

"},{"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.

Optional functions to access the diagnostic positions.

"},{"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                   const bool ignore_trailing_commas = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic bool accept(IteratorType first, IteratorType last,\n                   const bool ignore_comments = false,\n                   const bool ignore_trailing_commas = 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 a 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) ignore_trailing_commas (in) whether trailing commas in arrays or objects should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to the start of the character range last (in) iterator to the end of the 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/#exceptions","title":"Exceptions","text":"

Throws parse_error.101 in case of an empty input like a null FILE* or char* pointer.

"},{"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":"

A UTF-8 byte order mark is silently ignored.

"},{"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:
  2. The function can throw the following exceptions:
  3. See 2.
  4. The function can throw the following exceptions:
"},{"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 the case of a structured type (array or object), a reference to the last element is returned. In the 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:

    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. Each member value (object, array, string, etc.) is serialized via the corresponding to_json() overload. For objects and strings, the conversion requires that the target basic_json type's object_t::key_type (or string_t) be directly constructible from the source type's corresponding member type via is_constructible. If this requirement is not met, the conversion does not fail to compile; instead, it silently falls back to the array-conversion path, which represents objects as arrays of [key, value] pairs and strings as arrays of character codes. This is a known limitation tracked in issue #3425.

  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 a JSON object type, so interpreting it as a JSON array type is safe.

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

    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 depend on the different types a JSON value can have:

  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:

Note: For cross-basic_json conversions to produce correct results, the target basic_json's object_t::key_type and string_t must be directly constructible from the source basic_json's corresponding types. See the description of overload (4) above for details on what happens when this requirement is not met.

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) the beginning of the range to copy from (included) last (in) the 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), a 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), a 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:
  6. (none)
  7. The function can throw the following exceptions:
  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 a 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 a 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 boolean values 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 a 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 does not throw exceptions.
"},{"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/#see-also","title":"See also","text":""},{"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/#see-also","title":"See also","text":""},{"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 last 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 crend().

#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 an 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 valid bytes are copied to the output unchanged, and invalid bytes are dropped))."},{"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 an 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/#see-also","title":"See also","text":""},{"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/#iterator-invalidation","title":"Iterator invalidation","text":"

For ordered_json, adding a value to an object can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

"},{"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/#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/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/#see-also","title":"See also","text":""},{"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/#iterator-invalidation","title":"Iterator invalidation","text":"

By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise, only the end() iterator is invalidated.

"},{"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/#see-also","title":"See also","text":""},{"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/end_pos/","title":"nlohmann::basic_json::end_pos","text":"
#if JSON_DIAGNOSTIC_POSITIONS\nconstexpr std::size_t end_pos() const noexcept;\n#endif\n

Returns the position immediately following the last character of the JSON string from which the value was parsed from.

JSON type return value object position after the closing } array position after the closing ] string position after the closing \" number position after the last character boolean position after e null position after l"},{"location":"api/basic_json/end_pos/#return-value","title":"Return value","text":"

the position of the character following the last character of the given value in the parsed JSON string, if the value was created by the parse function, or std::string::npos if the value was constructed otherwise

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

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

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

Constant.

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

Note

The function is only available if macro JSON_DIAGNOSTIC_POSITIONS has been defined to 1 before including the library header.

Invalidation

The returned positions are only valid as long as the JSON value is not changed. The positions are not updated when the JSON value is changed.

"},{"location":"api/basic_json/end_pos/#examples","title":"Examples","text":"Example
#include <iostream>\n\n#define JSON_DIAGNOSTIC_POSITIONS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    std::string json_string = R\"(\n    {\n        \"address\": {\n            \"street\": \"Fake Street\",\n            \"housenumber\": 1\n        }\n    }\n    )\";\n    json j = json::parse(json_string);\n\n    std::cout << \"Root diagnostic positions: \\n\";\n    std::cout << \"\\tstart_pos: \" << j.start_pos() << '\\n';\n    std::cout << \"\\tend_pos:\" << j.end_pos() << \"\\n\";\n    std::cout << \"Original string: \\n\";\n    std::cout << \"{\\n        \\\"address\\\": {\\n            \\\"street\\\": \\\"Fake Street\\\",\\n            \\\"housenumber\\\": 1\\n        }\\n    }\" << \"\\n\";\n    std::cout << \"Parsed string: \\n\";\n    std::cout << json_string.substr(j.start_pos(), j.end_pos() - j.start_pos()) << \"\\n\\n\";\n\n    std::cout << \"address diagnostic positions: \\n\";\n    std::cout << \"\\tstart_pos:\" << j[\"address\"].start_pos() << '\\n';\n    std::cout << \"\\tend_pos:\" << j[\"address\"].end_pos() << \"\\n\\n\";\n    std::cout << \"Original string: \\n\";\n    std::cout << \"{            \\\"street\\\": \\\"Fake Street\\\",\\n            \\\"housenumber\\\": 1\\n        }\" << \"\\n\";\n    std::cout << \"Parsed string: \\n\";\n    std::cout << json_string.substr(j[\"address\"].start_pos(), j[\"address\"].end_pos() - j[\"address\"].start_pos()) << \"\\n\\n\";\n\n    std::cout << \"street diagnostic positions: \\n\";\n    std::cout << \"\\tstart_pos:\" << j[\"address\"][\"street\"].start_pos() << '\\n';\n    std::cout << \"\\tend_pos:\" << j[\"address\"][\"street\"].end_pos() << \"\\n\\n\";\n    std::cout << \"Original string: \\n\";\n    std::cout << \"\\\"Fake Street\\\"\" << \"\\n\";\n    std::cout << \"Parsed string: \\n\";\n    std::cout << json_string.substr(j[\"address\"][\"street\"].start_pos(), j[\"address\"][\"street\"].end_pos() - j[\"address\"][\"street\"].start_pos()) << \"\\n\\n\";\n\n    std::cout << \"housenumber diagnostic positions: \\n\";\n    std::cout << \"\\tstart_pos:\" << j[\"address\"][\"housenumber\"].start_pos() << '\\n';\n    std::cout << \"\\tend_pos:\" << j[\"address\"][\"housenumber\"].end_pos() << \"\\n\\n\";\n    std::cout << \"Original string: \\n\";\n    std::cout << \"1\" << \"\\n\";\n    std::cout << \"Parsed string: \\n\";\n    std::cout << json_string.substr(j[\"address\"][\"housenumber\"].start_pos(), j[\"address\"][\"housenumber\"].end_pos() - j[\"address\"][\"housenumber\"].start_pos()) << \"\\n\\n\";\n}\n

Output:

Root diagnostic positions: \n    start_pos: 5\n    end_pos:109\nOriginal string: \n{\n        \"address\": {\n            \"street\": \"Fake Street\",\n            \"housenumber\": 1\n        }\n    }\nParsed string: \n{\n        \"address\": {\n            \"street\": \"Fake Street\",\n            \"housenumber\": 1\n        }\n    }\n\naddress diagnostic positions: \n    start_pos:26\n    end_pos:103\n\nOriginal string: \n{            \"street\": \"Fake Street\",\n            \"housenumber\": 1\n        }\nParsed string: \n{\n            \"street\": \"Fake Street\",\n            \"housenumber\": 1\n        }\n\nstreet diagnostic positions: \n    start_pos:50\n    end_pos:63\n\nOriginal string: \n\"Fake Street\"\nParsed string: \n\"Fake Street\"\n\nhousenumber diagnostic positions: \n    start_pos:92\n    end_pos:93\n\nOriginal string: \n1\nParsed string: \n1\n

The output shows the start/end positions of all the objects and fields in the JSON string.

"},{"location":"api/basic_json/end_pos/#see-also","title":"See also","text":""},{"location":"api/basic_json/end_pos/#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:
  2. The function can throw the following exceptions:
  3. The function can throw the following exceptions:
  4. See 3.
  5. The function can throw the following exceptions:
"},{"location":"api/basic_json/erase/#complexity","title":"Complexity","text":"
  1. The complexity depends on the type:
  2. The complexity depends on the type:
  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/#see-also","title":"See also","text":""},{"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 valid bytes are copied to the output unchanged, and invalid bytes are dropped"},{"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.

classDiagram\n  direction LR\n\n    class std_exception [\"std::exception\"] {\n        <<interface>>\n    }\n\n    class json_exception [\"basic_json::exception\"] {\n        +const int id\n        +const char* what() const\n    }\n\n    class json_parse_error [\"basic_json::parse_error\"] {\n        +const std::size_t byte\n    }\n\n    class json_invalid_iterator [\"basic_json::invalid_iterator\"]\n    class json_type_error [\"basic_json::type_error\"]\n    class json_out_of_range [\"basic_json::out_of_range\"]\n    class json_other_error [\"basic_json::other_error\"]\n\n    std_exception <|-- json_exception\n    json_exception <|-- json_parse_error\n    json_exception <|-- json_invalid_iterator\n    json_exception <|-- json_type_error\n    json_exception <|-- json_out_of_range\n    json_exception <|-- json_other_error\n\n    style json_exception fill:#CCCCFF

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 of 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/format_as/","title":"format_as(basic_json)","text":"
template <typename BasicJsonType>\nstd::string format_as(const BasicJsonType& j);\n

This function implements the format_as customization point used by the {fmt} library (fmtlib). It has no dependency on any fmt header and no effect at all unless a caller's translation unit also includes fmt and calls fmt::format/fmt::print on a JSON value.

"},{"location":"api/basic_json/format_as/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/basic_json/format_as/#return-value","title":"Return value","text":"

string containing the serialization of the JSON value (same as dump())

"},{"location":"api/basic_json/format_as/#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/format_as/#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/format_as/#complexity","title":"Complexity","text":"

Linear.

"},{"location":"api/basic_json/format_as/#possible-implementation","title":"Possible implementation","text":"
template <typename BasicJsonType>\nstd::string format_as(const BasicJsonType& j)\n{\n    return j.dump();\n}\n
"},{"location":"api/basic_json/format_as/#notes","title":"Notes","text":"

Version-dependent effect on fmt

fmt only picks up a format_as overload that returns a std::string in fmt 10.0.0 through 11.0.2. Starting with fmt 11.1.0, fmt restricts automatic format_as pickup to overloads that return an arithmetic type, so this function has no effect there (it is simply unused, not a compile error).

If you use fmt >= 11.1.0, or want the same pretty-print spec support that std::formatter<basic_json> has (\"{:#}\", a width to set the indent such as \"{:2}\"/\"{:#2}\", and fill-and-align to pick the indent character such as \"{:.>#}\"), define your own fmt::formatter specialization mirroring the same logic:

template <>\nstruct fmt::formatter<nlohmann::json>\n{\n    // -1 means compact output (dump()); any value >= 0 means pretty-printed\n    // output with that many spaces (or indent_char) per level.\n    int indent = -1;\n    char indent_char = ' ';\n\n    constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator\n    {\n        auto it = ctx.begin();\n        const auto end = ctx.end();\n        constexpr auto is_align = [](char c)\n        {\n            return c == '<' || c == '>' || c == '^';\n        };\n\n        // [[fill] align] - repurposed here to pick a custom indent character\n        if (it != end && it + 1 != end && is_align(it[1]))\n        {\n            indent_char = *it;\n            it += 2;\n        }\n        else if (it != end && is_align(*it))\n        {\n            ++it;\n        }\n\n        // ['#'] - \"alternate form\", used here to request pretty-printing with a\n        // default indent of 4 (overridden by an explicit width below, if given)\n        if (it != end && *it == '#')\n        {\n            indent = 4;\n            ++it;\n        }\n\n        // [width] - repurposed here to pick the indent size; a width without '#'\n        // implies pretty-printing since an indent otherwise has no meaning\n        if (it != end && *it >= '1' && *it <= '9')\n        {\n            indent = 0;\n            while (it != end && *it >= '0' && *it <= '9')\n            {\n                indent = (indent * 10) + (*it - '0');\n                ++it;\n            }\n        }\n\n        if (it != end && *it != '}')\n        {\n            throw fmt::format_error(\"invalid format args for nlohmann::json\");\n        }\n\n        return it;\n    }\n\n    auto format(const nlohmann::json& j, format_context& ctx) const\n    {\n        const auto dumped = j.dump(indent, indent_char);\n        return fmt::format_to(ctx.out(), \"{}\", dumped);\n    }\n};\n

This recipe isn't shipped by the library itself, since doing so would make fmt a build dependency (see the FAQ entry on using JSON values with std::format or fmt for more background) \u2014 but it is compiled and exercised against a real, current fmt release as part of the library's own test suite (tests/fmt_formatter, via CMake FetchContent), so it's kept in sync with std::formatter<basic_json> and verified to actually work, not just illustrative.

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

The following code shows how the library's format_as() function integrates with fmt::format, allowing argument-dependent lookup.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON value\n    json j = {{\"one\", 1}, {\"two\", 2}};\n\n    // format_as() is found via argument-dependent lookup, the same way\n    // fmt::format/fmt::print would find it\n    auto j_str = format_as(j);\n\n    std::cout << j_str << std::endl;\n}\n

Output:

{\"one\":1,\"two\":2}\n
"},{"location":"api/basic_json/format_as/#see-also","title":"See also","text":"