Sponsors¶
You can sponsor this library at GitHub Sponsors.
Named Sponsors¶
Thanks everyone!
From 836d436a40eea9b969e152e2b831082c0139995e Mon Sep 17 00:00:00 2001
From: nlohmann You can sponsor this library at GitHub Sponsors. Thanks everyone! You can sponsor this library at GitHub Sponsors. Thanks everyone! This type is the default specialization of the basic_json class which uses the standard template types. The example below demonstrates how to use the type Output: Since version 1.0.0. Deserializes an input stream to a JSON value. the stream Linear in the length of the input. The parser is a predictive LL(1) parser. A UTF-8 byte order mark is silently ignored. Deprecation This function replaces function The example below shows how a JSON value is constructed by reading a serialization from a stream. Output: This operator implements a user-defined string literal for JSON objects. It can be used by adding It is recommended to bring the operator into scope using any of the following lines: Sponsors¶
Named Sponsors¶
Sponsors¶
Priority Sponsor¶
Named Sponsors¶
using json = basic_json<>;\nnlohmann::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
"},{"location":"api/json/#version-history","title":"Version history","text":"{\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}\nstd::istream& operator>>(std::istream& i, basic_json& j);\ni (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":"i
"},{"location":"api/operator_gtgt/#complexity","title":"Complexity","text":"parse_error.101 in case of an unexpected token.parse_error.102 if to_unicode fails or surrogate error.parse_error.103 if to_unicode fails.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;.#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
"},{"location":"api/operator_gtgt/#see-also","title":"See also","text":"{\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/#version-history","title":"Version history","text":"
"},{"location":"api/operator_literal_json/","title":"nlohmann::operator\"\"_json","text":"json operator \"\"_json(const char* s, std::size_t n);\n_json to a string literal and returns a json object if no parse error occurred.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.
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
The function can throw anything that parse(s, s+n) would throw.
Linear.
"},{"location":"api/operator_literal_json/#examples","title":"Examples","text":"ExampleThe following code shows how to create JSON values from string literals.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n json j = R\"( {\"hello\": \"world\", \"answer\": 42} )\"_json;\n\n std::cout << std::setw(2) << j << '\\n';\n}\n Output:
{\n \"answer\": 42,\n \"hello\": \"world\"\n}\n"},{"location":"api/operator_literal_json/#version-history","title":"Version history","text":"nlohmann::literals::json_literals in 3.11.0.json_pointer operator \"\"_json_pointer(const char* s, std::size_t n);\n This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred.
It is recommended to bring the operator into scope using any of the following lines:
using nlohmann::literals::operator \"\"_json_pointer;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS for details."},{"location":"api/operator_literal_json_pointer/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON Pointer n (in) length of string s"},{"location":"api/operator_literal_json_pointer/#return-value","title":"Return value","text":"json_pointer value parsed from s
The function can throw anything that json_pointer::json_pointer would throw.
Linear.
"},{"location":"api/operator_literal_json_pointer/#examples","title":"Examples","text":"ExampleThe 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":"nlohmann::literals::json_literals in 3.11.0.std::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)\n j to the output stream o. The JSON value will be serialized using the dump member function.width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).fill of the output stream o. For instance, the manipulator std::setfill('\\\\t') sets indentation to use a tab character rather than the default space character.ptr to the output stream o. The string representation is obtained using the to_string member function.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
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.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;.
The example below shows the serialization with different parameters to width to adjust the indentation level.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // serialize without indentation\n std::cout << j_object << \"\\n\\n\";\n std::cout << j_array << \"\\n\\n\";\n\n // serialize with indentation\n std::cout << std::setw(4) << j_object << \"\\n\\n\";\n std::cout << std::setw(2) << j_array << \"\\n\\n\";\n std::cout << std::setw(1) << std::setfill('\\t') << j_object << \"\\n\\n\";\n}\n Output:
{\"one\":1,\"two\":2}\n\n[1,2,4,8,16]\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\n{\n \"one\": 1,\n \"two\": 2\n}\n Example: (2) write JSON pointer to stream The example below shows how to write a JSON pointer to a stream.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON poiner\n json::json_pointer ptr(\"/foo/bar/baz\");\n\n // write string representation to stream\n std::cout << ptr << std::endl;\n}\n Output:
/foo/bar/baz\n"},{"location":"api/operator_ltlt/#version-history","title":"Version history","text":"std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.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.
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":"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>).
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.
Key)T)std::vector<std::pair<const Key, T>, Allocator>)std::equal_to<Key> // until C++14\n\nstd::equal_to<> // since C++14\nThe 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":"nlohmann::ordered_json.template<typename, typename>\nstruct adl_serializer;\n Serializer that uses ADL (Argument-Dependent Lookup) to choose to_json/from_json functions from the types' namespaces.
It is implemented similar to
template<typename ValueType>\nstruct adl_serializer {\n template<typename BasicJsonType>\n static void to_json(BasicJsonType& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n template<typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n"},{"location":"api/adl_serializer/#member-functions","title":"Member functions","text":"// (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).
j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"Copy of the JSON value, converted to ValueType
The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when template get<ns::person>() is called.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid from_json(const json& j, person& p)\n{\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n}\n} // namespace ns\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n Example: (2) Non-default-constructible type The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n"},{"location":"api/adl_serializer/from_json/#see-also","title":"See also","text":"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":"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":"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.
The class satisfies the following concept requirements:
"},{"location":"api/basic_json/#basic","title":"Basic","text":"==, see operator==.<, see operator<.swap.std::nullptr_t objects which are used to model the null value.basic_json valuesbasic_json classvalue_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":"Functions to inspect the type of a JSON value.
Direct access to the stored value of a JSON value.
Access to the JSON value
to_string function for JSON valuesThe 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":"// (1)\ntemplate<typename InputType>\nstatic bool accept(InputType&& i,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic bool accept(IteratorType first, IteratorType last,\n const bool ignore_comments = false);\n Checks whether the input is valid JSON.
Reads from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.
InputType A compatible input, for instance:
std::istream objectFILE pointer (throws if null)std::stringobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type, for instance.
std::string::iterator or std::vector<std::uint8_t>::iteratorptr and ptr + leni (in) Input to parse from. ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"Whether the input is valid JSON.
"},{"location":"api/basic_json/accept/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/accept/#exceptions","title":"Exceptions","text":"Throws parse_error.101 in case of an empty input like a null FILE* or char* pointer.
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":"ExampleThe 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":"ignore_comments added in version 3.9.0.FILE* null pointers to exception in version 3.11.4.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.
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.
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.
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:
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":"basic_json(initializer_list_t) - create a JSON value from an initializer listobject - create a JSON object value from an initializer listusing 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.
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.
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":"// (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 idx, with bounds checking.key, with bounds checking.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr, with bounds checking.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":"idxkeykeyptrStrong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/at/#exceptions","title":"Exceptions","text":"type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.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":"operator[] for unchecked access by referencevalue for access with default valuereference back();\n\nconst_reference back() const;\n Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to
auto tmp = c.end();\n--tmp;\nreturn *tmp;\n"},{"location":"api/basic_json/back/#return-value","title":"Return value","text":"In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.
"},{"location":"api/basic_json/back/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/back/#exceptions","title":"Exceptions","text":"If the JSON value is null, exception invalid_iterator.214 is thrown.
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.
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":"// (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 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 nullnull boolean false string \"\" number 0 object {} array [] binary empty array The postcondition of this constructor can be restored by calling clear().
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.
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:
array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.string_t, string literals, and all compatible string containers can be used.number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.boolean_t / bool can be used.binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type.See the examples below.
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.
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:
{} is created.The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
{} which is exactly an empty JSON object.With the rules described above, the following JSON values cannot be expressed by an initializer list:
[]): use array(initializer_list_t) with an empty initializer list in this casearray(initializer_list_t) with the same initializer list in this caseFunction array() and object() force array and object creation from initializer lists, respectively.
Constructs a JSON array value by creating cnt copies of a passed value. In case cnt is 0, an empty array is created.
Constructs the JSON value with the contents of the range [first, last). The semantics depends on the different types a JSON value can have:
null type, invalid_iterator.206 is thrown.first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.Creates a copy of a given JSON value.
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.
CompatibleType a type such that:
CompatibleType is not derived from std::istream,CompatibleType is not basic_json (to avoid hijacking copy/move constructors),CompatibleType is not a different basic_json type (i.e. with different template arguments)CompatibleType is not a basic_json nested type (e.g., json_pointer, iterator, etc.)json_serializer<U> (with U = uncvref_t<CompatibleType>) has a to_json(basic_json_t&, CompatibleType&&) methodBasicJsonType: a type such that:
BasicJsonType is a basic_json type.BasicJsonType has different template arguments than basic_json_t.U: uncvref_t<CompatibleType>"},{"location":"api/basic_json/basic_json/#parameters","title":"Parameters","text":"v (in) the type of the value to create val (in) the value to be forwarded to the respective constructor init (in) initializer list with JSON values type_deduction (in) internal parameter; when set to true, the type of the JSON value is deducted from the initializer list init; when set to false, the type provided via manual_type is forced. This mode is used by the functions array(initializer_list_t) and object(initializer_list_t). manual_type (in) internal parameter; when type_deduction is set to false, the created JSON value will use the provided type (only value_t::array and value_t::object are valid); when type_deduction is set to true, this parameter has no effect cnt (in) the number of JSON copies of val to create first (in) begin of the range to copy from (included) last (in) end of the range to copy from (excluded) other (in) the JSON value to copy/move"},{"location":"api/basic_json/basic_json/#exception-safety","title":"Exception safety","text":"to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.type_error.301 if type_deduction is false, manual_type is value_t::object, but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.val, also depending on the implementation of the called to_json() method.val, also depending on the implementation of the called to_json() method.init.cnt.first and last.other.Overload 5:
Empty initializer list
When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value.
Overload 7:
Preconditions
first and last must be initialized. **This precondition is enforced with a runtime assertion.[first, last) is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior.Runtime assertion
A precondition is enforced with a runtime assertion.
Overload 8:
Postcondition
*this == other
Overload 9:
Postconditions
`*this has the same value as other before the call.other is a JSON null valueThe 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 listThe example below shows how JSON values are created from initializer lists.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_empty_init_list = json({});\n json j_object = { {\"one\", 1}, {\"two\", 2} };\n json j_array = {1, 2, 3, 4};\n json j_nested_object = { {\"one\", {1}}, {\"two\", {1, 2}} };\n json j_nested_array = { {{1}, \"one\"}, {{1, 2}, \"two\"} };\n\n // serialize the JSON value\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_nested_object << '\\n';\n std::cout << j_nested_array << '\\n';\n}\n Output:
{}\n{\"one\":1,\"two\":2}\n[1,2,3,4]\n{\"one\":[1],\"two\":[1,2]}\n[[[1],\"one\"],[[1,2],\"two\"]]\n Example: (6) construct an array with count copies of given value The following code shows examples for creating arrays with several copies of a given value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array by creating copies of a JSON value\n json value = \"Hello\";\n json array_0 = json(0, value);\n json array_1 = json(1, value);\n json array_5 = json(5, value);\n\n // serialize the JSON arrays\n std::cout << array_0 << '\\n';\n std::cout << array_1 << '\\n';\n std::cout << array_5 << '\\n';\n}\n Output:
[]\n[\"Hello\"]\n[\"Hello\",\"Hello\",\"Hello\",\"Hello\",\"Hello\"]\n Example: (7) construct a JSON container given an iterator range The example below shows several ways to create JSON values by specifying a subrange with iterators.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_array = {\"alpha\", \"bravo\", \"charly\", \"delta\", \"easy\"};\n json j_number = 42;\n json j_object = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n\n // create copies using iterators\n json j_array_range(j_array.begin() + 1, j_array.end() - 2);\n json j_number_range(j_number.begin(), j_number.end());\n json j_object_range(j_object.begin(), j_object.find(\"two\"));\n\n // serialize the values\n std::cout << j_array_range << '\\n';\n std::cout << j_number_range << '\\n';\n std::cout << j_object_range << '\\n';\n\n // example for an exception\n try\n {\n json j_invalid(j_number.begin() + 1, j_number.end());\n }\n catch (const json::invalid_iterator& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[\"bravo\",\"charly\"]\n42\n{\"one\":\"eins\"}\n[json.exception.invalid_iterator.204] iterators out of range\n Example: (8) copy constructor The following code shows an example for the copy constructor.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j1 = {\"one\", \"two\", 3, 4.5, false};\n\n // create a copy\n json j2(j1);\n\n // serialize the JSON array\n std::cout << j1 << \" = \" << j2 << '\\n';\n std::cout << std::boolalpha << (j1 == j2) << '\\n';\n}\n Output:
[\"one\",\"two\",3,4.5,false] = [\"one\",\"two\",3,4.5,false]\ntrue\n Example: (9) move constructor The code below shows the move constructor explicitly called via std::move.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json a = 23;\n\n // move contents of a to b\n json b(std::move(a));\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n Output:
null\n23\n"},{"location":"api/basic_json/basic_json/#version-history","title":"Version history","text":"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":"ExampleThe 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":"// (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 Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"JSON binary array value
"},{"location":"api/basic_json/binary/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/binary/#complexity","title":"Complexity","text":"Linear in the size of init; constant for typename binary_t::container_type&& init versions.
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.
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":"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++.
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>.
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.
CBOR
MessagePack
BSON
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":"std::uint64_t in version 3.10.0.using boolean_t = BooleanType;\n The type used to store JSON booleans.
RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.
To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.
With the default values for BooleanType (bool), the default value for boolean_t is bool.
Boolean values are stored directly inside a basic_json type.
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":"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":"ExampleThe 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":"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:
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":"store in 3.10.0.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":"ExampleThe 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":"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():
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":"ExampleThe 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":"// (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 key. If the element is not found or the JSON value is not an object, false is returned.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr can be resolved in the current JSON value.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":"true if an element with specified key exists. If no such element with such key is found or the JSON value is not an object, false is returned.true if the JSON pointer can be resolved to a stored value, false otherwise.Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/contains/#exceptions","title":"Exceptions","text":"parse_error.106 if an array index begins with 0.parse_error.109 if an array index was not a number.Logarithmic in the size of the JSON object.
"},{"location":"api/basic_json/contains/#notes","title":"Notes","text":"false when executed on a JSON type that is not an object.Postconditions
If j.contains(x) returns true for a key or JSON pointer x, then it is safe to call j[x].
The example shows how contains() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create some JSON values\n json j_object = R\"( {\"key\": \"value\"} )\"_json;\n json j_array = R\"( [1, 2, 3] )\"_json;\n\n // call contains\n std::cout << std::boolalpha <<\n \"j_object contains 'key': \" << j_object.contains(\"key\") << '\\n' <<\n \"j_object contains 'another': \" << j_object.contains(\"another\") << '\\n' <<\n \"j_array contains 'key': \" << j_array.contains(\"key\") << std::endl;\n}\n Output:
j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n Example: (2) check with key using string_view The example shows how contains() is used.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create some JSON values\n json j_object = R\"( {\"key\": \"value\"} )\"_json;\n json j_array = R\"( [1, 2, 3] )\"_json;\n\n // call contains\n std::cout << std::boolalpha <<\n \"j_object contains 'key': \" << j_object.contains(\"key\"sv) << '\\n' <<\n \"j_object contains 'another': \" << j_object.contains(\"another\"sv) << '\\n' <<\n \"j_array contains 'key': \" << j_array.contains(\"key\"sv) << std::endl;\n}\n Output:
j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n Example: (3) check with JSON pointer The example shows how contains() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n std::cout << std::boolalpha\n << j.contains(\"/number\"_json_pointer) << '\\n'\n << j.contains(\"/string\"_json_pointer) << '\\n'\n << j.contains(\"/array\"_json_pointer) << '\\n'\n << j.contains(\"/array/1\"_json_pointer) << '\\n'\n << j.contains(\"/array/-\"_json_pointer) << '\\n'\n << j.contains(\"/array/4\"_json_pointer) << '\\n'\n << j.contains(\"/baz\"_json_pointer) << std::endl;\n\n try\n {\n // try to use an array index with leading '0'\n j.contains(\"/array/01\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n try\n {\n // try to use an array index that is not a number\n j.contains(\"/array/one\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
true\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/contains/#version-history","title":"Version history","text":"KeyType to support comparable types in version 3.11.0.// (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 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).KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.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.
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.
The example shows how count() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call count()\n auto count_two = j_object.count(\"two\");\n auto count_three = j_object.count(\"three\");\n\n // print values\n std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n Output:
number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n Example: (2) count number of elements using string_view The example shows how count() is used.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call count()\n auto count_two = j_object.count(\"two\"sv);\n auto count_three = j_object.count(\"three\"sv);\n\n // print values\n std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n Output:
number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n"},{"location":"api/basic_json/count/#version-history","title":"Version history","text":"key type to KeyType&& in version 3.11.0.const_reverse_iterator crbegin() const noexcept;\n Returns an iterator to the reverse-beginning; that is, the last element.
"},{"location":"api/basic_json/crbegin/#return-value","title":"Return value","text":"reverse iterator to the first element
"},{"location":"api/basic_json/crbegin/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/crbegin/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/crbegin/#examples","title":"Examples","text":"ExampleThe 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":"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":"ExampleThe following code shows an example for eend().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-end\n json::const_reverse_iterator it = array.crend();\n\n // increment the iterator to point to the first element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n Output:
1\n"},{"location":"api/basic_json/crend/#version-history","title":"Version history","text":"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.
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":"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
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.
Currently, only remove, add, and replace operations are generated.
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":"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.
indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are three possible values (see error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged))."},{"location":"api/basic_json/dump/#return-value","title":"Return value","text":"string containing the serialization of the JSON value
"},{"location":"api/basic_json/dump/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/dump/#exceptions","title":"Exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict
Linear.
"},{"location":"api/basic_json/dump/#notes","title":"Notes","text":"Binary values are serialized as object containing two keys:
null if the binary has no subtypeThe following example shows the effect of different indent, indent_char, and ensure_ascii parameters to the result of the serialization.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hell\u00f6 \ud83d\ude00!\";\n\n // call dump()\n std::cout << \"objects:\" << '\\n'\n << j_object.dump() << \"\\n\\n\"\n << j_object.dump(-1) << \"\\n\\n\"\n << j_object.dump(0) << \"\\n\\n\"\n << j_object.dump(4) << \"\\n\\n\"\n << j_object.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"arrays:\" << '\\n'\n << j_array.dump() << \"\\n\\n\"\n << j_array.dump(-1) << \"\\n\\n\"\n << j_array.dump(0) << \"\\n\\n\"\n << j_array.dump(4) << \"\\n\\n\"\n << j_array.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"strings:\" << '\\n'\n << j_string.dump() << '\\n'\n << j_string.dump(-1, ' ', true) << '\\n';\n\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"\u00e4\\xA9\u00fc\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}\n Output:
objects:\n{\"one\":1,\"two\":2}\n\n{\"one\":1,\"two\":2}\n\n{\n\"one\": 1,\n\"two\": 2\n}\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\narrays:\n[1,2,4,8,16]\n\n[1,2,4,8,16]\n\n[\n1,\n2,\n4,\n8,\n16\n]\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\nstrings:\n\"Hell\u00f6 \ud83d\ude00!\"\n\"Hell\\u00f6 \\ud83d\\ude00!\"\n[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n"},{"location":"api/basic_json/dump/#version-history","title":"Version history","text":"indent_char, option ensure_ascii and exceptions added in version 3.0.0.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.
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.
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.
Throws type_error.311 when called on a type other than JSON object or null; example: \"cannot use emplace() with number\"
Logarithmic in the size of the container, O(log(size())).
The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n auto res1 = object.emplace(\"three\", 3);\n null.emplace(\"A\", \"a\");\n null.emplace(\"B\", \"b\");\n\n // the following call will not add an object, because there is already\n // a value stored at key \"B\"\n auto res2 = null.emplace(\"B\", \"c\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << *res1.first << \" \" << std::boolalpha << res1.second << '\\n';\n\n std::cout << null << '\\n';\n std::cout << *res2.first << \" \" << std::boolalpha << res2.second << '\\n';\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"one\":1,\"three\":3,\"two\":2}\n3 true\n{\"A\":\"a\",\"B\":\"b\"}\n\"b\" false\n"},{"location":"api/basic_json/emplace/#version-history","title":"Version history","text":"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.
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.
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\"
Amortized constant.
"},{"location":"api/basic_json/emplace_back/#examples","title":"Examples","text":"ExampleThe 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":"bool empty() const noexcept;\n Checks if a JSON value has no elements (i.e. whether its size() is 0).
The return value depends on the different types and is defined as follows:
Value type return value nulltrue 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.
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.
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":"false for binary types in version 3.8.0.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":"ExampleThe 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":"// (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 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.
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.
Removes an element from a JSON object by key.
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.
Removes an element from a JSON array by index.
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":"pos refers to the last element, the end() iterator is returned.last refers to the last element, the end() iterator is returned.ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/erase/#exceptions","title":"Exceptions","text":"type_error.307 if called on a null value; example: \"cannot use erase() with null\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: \"iterator out of range\"type_error.307 if called on a null value; example: \"cannot use erase() with null\"invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: \"iterators do not fit current value\"invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: \"iterators out of range\"type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"out_of_range.401 when idx >= size(); example: \"array index 17 is out of range\"pos and the end of the containerlog(size()) + std::distance(first, last)first and last, plus linear in the distance between last and end of the containerlog(size()) + count(key)log(size()) + count(key)idx and the end of the container.erase, including the end() iterator.The example shows the effect of erase() for different JSON types using an iterator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call erase()\n j_boolean.erase(j_boolean.begin());\n j_number_integer.erase(j_number_integer.begin());\n j_number_float.erase(j_number_float.begin());\n j_object.erase(j_object.find(\"two\"));\n j_array.erase(j_array.begin() + 2);\n j_string.erase(j_string.begin());\n\n // print values\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n Output:
null\nnull\nnull\n{\"one\":1}\n[1,2,8,16]\nnull\n Example: (2) remove elements given an iterator range The example shows the effect of erase() for different JSON types using an iterator range.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call erase()\n j_boolean.erase(j_boolean.begin(), j_boolean.end());\n j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());\n j_number_float.erase(j_number_float.begin(), j_number_float.end());\n j_object.erase(j_object.find(\"two\"), j_object.end());\n j_array.erase(j_array.begin() + 1, j_array.begin() + 3);\n j_string.erase(j_string.begin(), j_string.end());\n\n // print values\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n Output:
null\nnull\nnull\n{\"one\":1}\n[1,8,16]\nnull\n Example: (3) remove element from a JSON object given a key The example shows the effect of erase() for different JSON types using an object key.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call erase()\n auto count_one = j_object.erase(\"one\");\n auto count_three = j_object.erase(\"three\");\n\n // print values\n std::cout << j_object << '\\n';\n std::cout << count_one << \" \" << count_three << '\\n';\n}\n Output:
{\"two\":2}\n1 0\n Example: (4) remove element from a JSON object given a key using string_view The example shows the effect of erase() for different JSON types using an object key.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call erase()\n auto count_one = j_object.erase(\"one\"sv);\n auto count_three = j_object.erase(\"three\"sv);\n\n // print values\n std::cout << j_object << '\\n';\n std::cout << count_one << \" \" << count_three << '\\n';\n}\n Output:
{\"two\":2}\n1 0\n Example: (5) remove element from a JSON array given an index The example shows the effect of erase() using an array index.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j_array = {0, 1, 2, 3, 4, 5};\n\n // call erase()\n j_array.erase(2);\n\n // print values\n std::cout << j_array << '\\n';\n}\n Output:
[0,1,3,4,5]\n"},{"location":"api/basic_json/erase/#version-history","title":"Version history","text":"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:
type_error exception in case of invalid UTF-8 replace replace invalid UTF-8 sequences with U+FFFD (\ufffd REPLACEMENT CHARACTER) ignore ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged"},{"location":"api/basic_json/error_handler_t/#examples","title":"Examples","text":"Example The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"\u00e4\\xA9\u00fc\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}\n Output:
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n"},{"location":"api/basic_json/error_handler_t/#version-history","title":"Version history","text":"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:
parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsTo 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.
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":"// (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 key. If the element is not found or the JSON value is not an object, end() is returned.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.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.
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.
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":"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.
an object that maps JSON pointers to primitive values
"},{"location":"api/basic_json/flatten/#exception-safety","title":"Exception safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/flatten/#complexity","title":"Complexity","text":"Linear in the size the JSON value.
"},{"location":"api/basic_json/flatten/#notes","title":"Notes","text":"Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.
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":"// (1)\ntemplate<typename InputType>\nstatic basic_json from_bjdata(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_bjdata(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_bjdata/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bjdata/#parameters","title":"Parameters","text":"i (in) an input in BJData format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bjdata/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_bjdata/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_bjdata/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in BJData format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with BJData\n json j = json::from_bjdata(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_bjdata/#version-history","title":"Version history","text":"// (1)\ntemplate<typename InputType>\nstatic basic_json from_bson(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_bson(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_bson/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bson/#parameters","title":"Parameters","text":"i (in) an input in BSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bson/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_bson/#exceptions","title":"Exceptions","text":"Throws parse_error.114 if an unsupported BSON record type is encountered.
Linear in the size of the input.
"},{"location":"api/basic_json/from_bson/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in BSON format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d,\n 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73,\n 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00\n };\n\n // deserialize it with BSON\n json j = json::from_bson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_bson/#see-also","title":"See also","text":"Deprecation
from_bson with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_bson(ptr, len, ...); with from_bson(ptr, ptr+len, ...);.from_bson 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 from_bson({ptr, ptr+len}, ...); with from_bson(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)\ntemplate<typename InputType>\nstatic basic_json from_cbor(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);\n\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_cbor(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);\n Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_cbor/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_cbor/#parameters","title":"Parameters","text":"i (in) an input in CBOR format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) tag_handler (in) how to treat CBOR tags (optional, error by default); see cbor_tag_handler_t for more information"},{"location":"api/basic_json/from_cbor/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_cbor/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_cbor/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in CBOR format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with CBOR\n json j = json::from_cbor(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_cbor/#version-history","title":"Version history","text":"start_index since version 2.1.1.start_index parameter, and added strict parameter in version 3.0.0.allow_exceptions parameter in version 3.2.0.tag_handler parameter in version 3.9.0.Deprecation
from_cbor with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_cbor(ptr, len, ...); with from_cbor(ptr, ptr+len, ...);.from_cbor 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 from_cbor({ptr, ptr+len}, ...); with from_cbor(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)\ntemplate<typename InputType>\nstatic basic_json from_msgpack(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_msgpack(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the MessagePack serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_msgpack/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_msgpack/#parameters","title":"Parameters","text":"i (in) an input in MessagePack format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_msgpack/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_msgpack/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_msgpack/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in MessagePack format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_msgpack/#version-history","title":"Version history","text":"start_index since version 2.1.1.start_index parameter, and added strict parameter in version 3.0.0.allow_exceptions parameter in version 3.2.0.Deprecation
from_msgpack with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_msgpack(ptr, len, ...); with from_msgpack(ptr, ptr+len, ...);.from_cbor 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 from_msgpack({ptr, ptr+len}, ...); with from_msgpack(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)\ntemplate<typename InputType>\nstatic basic_json from_ubjson(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_ubjson(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_ubjson/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_ubjson/#parameters","title":"Parameters","text":"i (in) an input in UBJSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_ubjson/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_ubjson/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_ubjson/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in UBJSON format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with UBJSON\n json j = json::from_ubjson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_ubjson/#version-history","title":"Version history","text":"allow_exceptions parameter in version 3.2.0.Deprecation
from_ubjson with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_ubjson(ptr, len, ...); with from_ubjson(ptr, ptr+len, ...);.from_ubjson 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 from_ubjson({ptr, ptr+len}, ...); with from_ubjson(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
reference front();\nconst_reference front() const;\n Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().
In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.
"},{"location":"api/basic_json/front/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/front/#exceptions","title":"Exceptions","text":"If the JSON value is null, exception invalid_iterator.214 is thrown.
Constant.
"},{"location":"api/basic_json/front/#notes","title":"Notes","text":"Precondition
The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.
The following code shows an example for front().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call front()\n //std::cout << j_null.front() << '\\n'; // would throw\n std::cout << j_boolean.front() << '\\n';\n std::cout << j_number_integer.front() << '\\n';\n std::cout << j_number_float.front() << '\\n';\n std::cout << j_object.front() << '\\n';\n //std::cout << j_object_empty.front() << '\\n'; // undefined behavior\n std::cout << j_array.front() << '\\n';\n //std::cout << j_array_empty.front() << '\\n'; // undefined behavior\n std::cout << j_string.front() << '\\n';\n}\n Output:
true\n17\n23.42\n1\n1\n\"Hello, world\"\n"},{"location":"api/basic_json/front/#see-also","title":"See also","text":"// (1)\ntemplate<typename ValueType>\nValueType get() const noexcept(\n noexcept(JSONSerializer<ValueType>::from_json(\n std::declval<const basic_json_t&>(), std::declval<ValueType&>())));\n\n// (2)\ntemplate<typename BasicJsonType>\nBasicJsonType get() const;\n\n// (3)\ntemplate<typename PointerType>\nPointerType get_ptr();\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing
ValueType ret;\nJSONSerializer<ValueType>::from_json(*this, ret);\nreturn ret;\n This overload is chosen if:
ValueType is not basic_json,json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&), andjson_serializer<ValueType> does not have a from_json() method of the form ValueType from_json(const basic_json&)If the type is not CopyConstructible and not DefaultConstructible, the value is converted by calling the json_serializer<ValueType> from_json() method.
The function is then equivalent to executing
return JSONSerializer<ValueTypeCV>::from_json(*this);\n This overload is chosen if:
ValueType is not basic_json andjson_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.
Overload for basic_json specializations. The function is equivalent to executing
return *this;\n Explicit pointer access to the internally stored JSON value. No copies are made.
ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get/#return-value","title":"Return value","text":"ValueType*this, converted into BasicJsonTypenullptr otherwiseDepends on what json_serializer<ValueType> from_json() method throws
Undefined behavior
Writing data to the pointee (overload 3) of the result yields an undefined state.
"},{"location":"api/basic_json/get/#examples","title":"Examples","text":"ExampleThe example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use explicit conversions\n auto v1 = json_types[\"boolean\"].template get<bool>();\n auto v2 = json_types[\"number\"][\"integer\"].template get<int>();\n auto v3 = json_types[\"number\"][\"integer\"].template get<short>();\n auto v4 = json_types[\"number\"][\"floating-point\"].template get<float>();\n auto v5 = json_types[\"number\"][\"floating-point\"].template get<int>();\n auto v6 = json_types[\"string\"].template get<std::string>();\n auto v7 = json_types[\"array\"].template get<std::vector<short>>();\n auto v8 = json_types.template get<std::unordered_map<std::string, json>>();\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n Output:
1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting pointers\n auto p1 = value.template get<const json::number_integer_t*>();\n auto p2 = value.template get<json::number_integer_t*>();\n auto p3 = value.template get<json::number_integer_t* const>();\n auto p4 = value.template get<const json::number_integer_t* const>();\n auto p5 = value.template get<json::number_float_t*>();\n\n // print the pointees\n std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\\n';\n std::cout << std::boolalpha << (p5 == nullptr) << '\\n';\n}\n Output:
17 17 17 17\ntrue\n"},{"location":"api/basic_json/get/#version-history","title":"Version history","text":"basic_json in version 3.2.0.static allocator_type get_allocator();\n Returns the allocator associated with the container.
"},{"location":"api/basic_json/get_allocator/#return-value","title":"Return value","text":"associated allocator
"},{"location":"api/basic_json/get_allocator/#examples","title":"Examples","text":"ExampleThe example shows how get_allocator() is used to created json values.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n auto alloc = json::get_allocator();\n using traits_t = std::allocator_traits<decltype(alloc)>;\n\n json* j = traits_t::allocate(alloc, 1);\n traits_t::construct(alloc, j, \"Hello, world!\");\n\n std::cout << *j << std::endl;\n\n traits_t::destroy(alloc, j);\n traits_t::deallocate(alloc, j, 1);\n}\n Output:
\"Hello, world!\"\n"},{"location":"api/basic_json/get_allocator/#version-history","title":"Version history","text":"binary_t& get_binary();\n\nconst binary_t& get_binary() const;\n Returns a reference to the stored binary value.
"},{"location":"api/basic_json/get_binary/#return-value","title":"Return value","text":"Reference to binary value.
"},{"location":"api/basic_json/get_binary/#exception-safety","title":"Exception safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/get_binary/#exceptions","title":"Exceptions","text":"Throws type_error.302 if the value is not binary
Constant.
"},{"location":"api/basic_json/get_binary/#examples","title":"Examples","text":"ExampleThe following code shows how to query a binary value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary vector\n std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};\n\n // create a binary JSON value with subtype 42\n json j = json::binary(vec, 42);\n\n // output type and subtype\n std::cout << \"type: \" << j.type_name() << \", subtype: \" << j.get_binary().subtype() << std::endl;\n}\n Output:
type: binary, subtype: 42\n"},{"location":"api/basic_json/get_binary/#version-history","title":"Version history","text":"template<typename PointerType>\nPointerType get_ptr() noexcept;\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n Implicit pointer access to the internally stored JSON value. No copies are made.
"},{"location":"api/basic_json/get_ptr/#template-parameters","title":"Template parameters","text":"PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get_ptr/#return-value","title":"Return value","text":"pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/get_ptr/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/get_ptr/#notes","title":"Notes","text":"Undefined behavior
The pointer becomes invalid if the underlying JSON object changes.
Consider the following example code where the pointer ptr changes after the array is resized. As a result, reading or writing to ptr after the array change would be undefined behavior. The address of the first array element changes, because the underlying std::vector is resized after adding a fifth element.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j = {1, 2, 3, 4};\n auto* ptr = j[0].get_ptr<std::int64_t*>();\n std::cout << \"value at \" << ptr << \" is \" << *ptr << std::endl;\n\n j.push_back(5);\n\n ptr = j[0].get_ptr<std::int64_t*>();\n std::cout << \"value at \" << ptr << \" is \" << *ptr << std::endl;\n}\n Output:
value at 0x6000012fc1c8 is 1\nvalue at 0x6000029fc088 is 1\n"},{"location":"api/basic_json/get_ptr/#examples","title":"Examples","text":"Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting pointers\n auto p1 = value.get_ptr<const json::number_integer_t*>();\n auto p2 = value.get_ptr<json::number_integer_t*>();\n auto p3 = value.get_ptr<json::number_integer_t* const>();\n auto p4 = value.get_ptr<const json::number_integer_t* const>();\n auto p5 = value.get_ptr<json::number_float_t*>();\n\n // print the pointees\n std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\\n';\n std::cout << std::boolalpha << (p5 == nullptr) << '\\n';\n}\n Output:
17 17 17 17\ntrue\n"},{"location":"api/basic_json/get_ptr/#see-also","title":"See also","text":"template<typename ReferenceType>\nReferenceType get_ref();\n\ntemplate<typename ReferenceType>\nconst ReferenceType get_ref() const;\n Implicit reference access to the internally stored JSON value. No copies are made.
"},{"location":"api/basic_json/get_ref/#template-parameters","title":"Template parameters","text":"ReferenceType reference type; must be a reference to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Enforced by a static assertion."},{"location":"api/basic_json/get_ref/#return-value","title":"Return value","text":"reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise
Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/get_ref/#exceptions","title":"Exceptions","text":"Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: \"incompatible ReferenceType for get_ref, actual type is binary\".
Constant.
"},{"location":"api/basic_json/get_ref/#notes","title":"Notes","text":"Undefined behavior
The reference becomes invalid if the underlying JSON object changes.
"},{"location":"api/basic_json/get_ref/#examples","title":"Examples","text":"ExampleThe example shows several calls to get_ref().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting references\n auto r1 = value.get_ref<const json::number_integer_t&>();\n auto r2 = value.get_ref<json::number_integer_t&>();\n\n // print the values\n std::cout << r1 << ' ' << r2 << '\\n';\n\n // incompatible type throws exception\n try\n {\n auto r3 = value.get_ref<json::number_float_t&>();\n }\n catch (const json::type_error& ex)\n {\n std::cout << ex.what() << '\\n';\n }\n}\n Output:
17 17\n[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\n"},{"location":"api/basic_json/get_ref/#see-also","title":"See also","text":"template<typename ValueType>\nValueType& get_to(ValueType& v) const noexcept(\n noexcept(JSONSerializer<ValueType>::from_json(\n std::declval<const basic_json_t&>(), v)));\n Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing
ValueType v;\nJSONSerializer<ValueType>::from_json(*this, v);\n This overload is chosen if:
ValueType is not basic_json,json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&)ValueType the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"the input parameter, allowing chaining calls
"},{"location":"api/basic_json/get_to/#exceptions","title":"Exceptions","text":"Depends on what json_serializer<ValueType> from_json() method throws
The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n bool v1;\n int v2;\n short v3;\n float v4;\n int v5;\n std::string v6;\n std::vector<short> v7;\n std::unordered_map<std::string, json> v8;\n\n // use explicit conversions\n json_types[\"boolean\"].get_to(v1);\n json_types[\"number\"][\"integer\"].get_to(v2);\n json_types[\"number\"][\"integer\"].get_to(v3);\n json_types[\"number\"][\"floating-point\"].get_to(v4);\n json_types[\"number\"][\"floating-point\"].get_to(v5);\n json_types[\"string\"].get_to(v6);\n json_types[\"array\"].get_to(v7);\n json_types.get_to(v8);\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n Output:
1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n"},{"location":"api/basic_json/get_to/#version-history","title":"Version history","text":"enum class input_format_t {\n json,\n cbor,\n msgpack,\n ubjson,\n bson,\n bjdata\n};\n This enumeration is used in the sax_parse function to choose the input format to parse:
The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // CBOR byte string\n std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse CBOR\n bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
binary(val=[...])\n\nresult: true\n"},{"location":"api/basic_json/input_format_t/#version-history","title":"Version history","text":"// (1)\niterator insert(const_iterator pos, const basic_json& val);\niterator insert(const_iterator pos, basic_json&& val);\n\n// (2)\niterator insert(const_iterator pos, size_type cnt, const basic_json& val);\n\n// (3)\niterator insert(const_iterator pos, const_iterator first, const_iterator last);\n\n// (4)\niterator insert(const_iterator pos, initializer_list_t ilist);\n\n// (5)\nvoid insert(const_iterator first, const_iterator last);\n val into array before iterator pos.cnt copies of val into array before iterator pos.[first, last) into array before iterator pos.ilist into array before iterator pos.[first, last) into object.For all cases where an element is added to an 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. Also, any iterator or reference after the insertion point will point to the same index which is now a different value.
For ordered_json, also adding an element to an object can yield a reallocation which again invalidates all iterators and all references. Also, any iterator or reference after the insertion point will point to the same index which is now a different value.
pos (in) iterator before which the content will be inserted; may be the end() iterator val (in) value to insert cnt (in) number of copies of val to insert first (in) begin of the range of elements to insert last (in) end of the range of elements to insert ilist (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"val.pos if cnt==0pos if first==lastpos if ilist is emptyStrong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/insert/#exceptions","title":"Exceptions","text":"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"invalid_iterator.211 if first or last are iterators into container for which insert is called; example: \"passed iterators may not belong to container\"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"type_error.309 if called on JSON values other than objects; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"pos and end of the container.cnt plus linear in the distance between pos and end of the container.std::distance(first, last) plus linear in the distance between pos and end of the container.ilist.size() plus linear in the distance between pos and end of the container.O(N*log(size() + N)), where N is the number of elements to insert.The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 10 before number 3\n auto new_pos = v.insert(v.begin() + 2, 10);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
10\n[1,2,10,3,4]\n Example (2): insert copies of element into array The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 7 copies of number 7 before number 3\n auto new_pos = v.insert(v.begin() + 2, 7, 7);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
7\n[1,2,7,7,7,7,7,7,7,3,4]\n Example (3): insert range of elements into array The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // create a JSON array to copy values from\n json v2 = {\"one\", \"two\", \"three\", \"four\"};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), v2.begin(), v2.end());\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
\"one\"\n[1,2,3,4,\"one\",\"two\",\"three\",\"four\"]\n Example (4): insert elements from initializer list into array The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), {7, 8, 9});\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
7\n[1,2,3,4,7,8,9]\n Example (5): insert range of elements into object The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create two JSON objects\n json j1 = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n json j2 = {{\"eleven\", \"elf\"}, {\"seventeen\", \"siebzehn\"}};\n\n // output objects\n std::cout << j1 << '\\n';\n std::cout << j2 << '\\n';\n\n // insert range from j2 to j1\n j1.insert(j2.begin(), j2.end());\n\n // output result of insert call\n std::cout << j1 << '\\n';\n}\n Output:
{\"one\":\"eins\",\"two\":\"zwei\"}\n{\"eleven\":\"elf\",\"seventeen\":\"siebzehn\"}\n{\"eleven\":\"elf\",\"one\":\"eins\",\"seventeen\":\"siebzehn\",\"two\":\"zwei\"}\n"},{"location":"api/basic_json/insert/#version-history","title":"Version history","text":"class invalid_iterator : public exception;\n This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx (see list of iterator errors).
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_invalid_iterator fill:#CCCCFF"},{"location":"api/basic_json/invalid_iterator/#member-functions","title":"Member functions","text":"The following code shows how a invalid_iterator exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling iterator::key() on non-object iterator\n json j = \"string\";\n json::iterator it = j.begin();\n auto k = it.key();\n }\n catch (const json::invalid_iterator& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n"},{"location":"api/basic_json/invalid_iterator/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errortype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsconstexpr bool is_array() const noexcept;\n This function returns true if and only if the JSON value is an array.
true if type is an array, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_array/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_array/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_array() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_array()\n std::cout << std::boolalpha;\n std::cout << j_null.is_array() << '\\n';\n std::cout << j_boolean.is_array() << '\\n';\n std::cout << j_number_integer.is_array() << '\\n';\n std::cout << j_number_unsigned_integer.is_array() << '\\n';\n std::cout << j_number_float.is_array() << '\\n';\n std::cout << j_object.is_array() << '\\n';\n std::cout << j_array.is_array() << '\\n';\n std::cout << j_string.is_array() << '\\n';\n std::cout << j_binary.is_array() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\n"},{"location":"api/basic_json/is_array/#version-history","title":"Version history","text":"constexpr bool is_binary() const noexcept;\n This function returns true if and only if the JSON value is binary array.
true if type is binary, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_binary/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_binary/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_binary() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_binary()\n std::cout << std::boolalpha;\n std::cout << j_null.is_binary() << '\\n';\n std::cout << j_boolean.is_binary() << '\\n';\n std::cout << j_number_integer.is_binary() << '\\n';\n std::cout << j_number_unsigned_integer.is_binary() << '\\n';\n std::cout << j_number_float.is_binary() << '\\n';\n std::cout << j_object.is_binary() << '\\n';\n std::cout << j_array.is_binary() << '\\n';\n std::cout << j_string.is_binary() << '\\n';\n std::cout << j_binary.is_binary() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\n"},{"location":"api/basic_json/is_binary/#version-history","title":"Version history","text":"constexpr bool is_boolean() const noexcept;\n This function returns true if and only if the JSON value is true or false.
true if type is boolean, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_boolean/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_boolean/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_boolean() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_boolean()\n std::cout << std::boolalpha;\n std::cout << j_null.is_boolean() << '\\n';\n std::cout << j_boolean.is_boolean() << '\\n';\n std::cout << j_number_integer.is_boolean() << '\\n';\n std::cout << j_number_unsigned_integer.is_boolean() << '\\n';\n std::cout << j_number_float.is_boolean() << '\\n';\n std::cout << j_object.is_boolean() << '\\n';\n std::cout << j_array.is_boolean() << '\\n';\n std::cout << j_string.is_boolean() << '\\n';\n std::cout << j_binary.is_boolean() << '\\n';\n}\n Output:
false\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_boolean/#version-history","title":"Version history","text":"constexpr bool is_discarded() const noexcept;\n This function returns true for a JSON value if either:
parser_callback_t), orallow_exceptions set to false; see parse for more information.true if type is discarded, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_discarded/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_discarded/#notes","title":"Notes","text":"Comparisons
Discarded values are never compared equal with operator==. That is, checking whether a JSON value j is discarded will only work via:
j.is_discarded()\n because
j == json::value_t::discarded\n will always be false.
Removal during parsing with callback functions
When a value is discarded by a callback function (see parser_callback_t) during parsing, then it is removed when it is part of a structured value. For instance, if the second value of an array is discarded, instead of [null, discarded, false], the array [null, false] is returned. Only if the top-level value is discarded, the return value of the parse call is discarded.
This function will always be false for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases.
The following code exemplifies is_discarded() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_discarded()\n std::cout << std::boolalpha;\n std::cout << j_null.is_discarded() << '\\n';\n std::cout << j_boolean.is_discarded() << '\\n';\n std::cout << j_number_integer.is_discarded() << '\\n';\n std::cout << j_number_unsigned_integer.is_discarded() << '\\n';\n std::cout << j_number_float.is_discarded() << '\\n';\n std::cout << j_object.is_discarded() << '\\n';\n std::cout << j_array.is_discarded() << '\\n';\n std::cout << j_string.is_discarded() << '\\n';\n std::cout << j_binary.is_discarded() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_discarded/#version-history","title":"Version history","text":"constexpr bool is_null() const noexcept;\n This function returns true if and only if the JSON value is null.
true if type is null, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_null/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_null/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_null() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_null()\n std::cout << std::boolalpha;\n std::cout << j_null.is_null() << '\\n';\n std::cout << j_boolean.is_null() << '\\n';\n std::cout << j_number_integer.is_null() << '\\n';\n std::cout << j_number_unsigned_integer.is_null() << '\\n';\n std::cout << j_number_float.is_null() << '\\n';\n std::cout << j_object.is_null() << '\\n';\n std::cout << j_array.is_null() << '\\n';\n std::cout << j_string.is_null() << '\\n';\n std::cout << j_binary.is_null() << '\\n';\n}\n Output:
true\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_null/#version-history","title":"Version history","text":"constexpr bool is_number() const noexcept;\n This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.
true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number/#possible-implementation","title":"Possible implementation","text":"constexpr bool is_number() const noexcept\n{\n return is_number_integer() || is_number_float();\n}\n"},{"location":"api/basic_json/is_number/#examples","title":"Examples","text":"Example The following code exemplifies is_number() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number() << '\\n';\n std::cout << j_boolean.is_number() << '\\n';\n std::cout << j_number_integer.is_number() << '\\n';\n std::cout << j_number_unsigned_integer.is_number() << '\\n';\n std::cout << j_number_float.is_number() << '\\n';\n std::cout << j_object.is_number() << '\\n';\n std::cout << j_array.is_number() << '\\n';\n std::cout << j_string.is_number() << '\\n';\n std::cout << j_binary.is_number() << '\\n';\n}\n Output:
false\nfalse\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number/#see-also","title":"See also","text":"true for unsigned integers in 2.0.0.constexpr bool is_number_float() const noexcept;\n This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.
true if type is a floating-point number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number_float/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number_float/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_number_float() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_float()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_float() << '\\n';\n std::cout << j_boolean.is_number_float() << '\\n';\n std::cout << j_number_integer.is_number_float() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_float() << '\\n';\n std::cout << j_number_float.is_number_float() << '\\n';\n std::cout << j_object.is_number_float() << '\\n';\n std::cout << j_array.is_number_float() << '\\n';\n std::cout << j_string.is_number_float() << '\\n';\n std::cout << j_binary.is_number_float() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number_float/#see-also","title":"See also","text":"constexpr bool is_number_integer() const noexcept;\n This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.
true if type is an integer or unsigned integer number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number_integer/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number_integer/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_number_integer() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_integer()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_integer() << '\\n';\n std::cout << j_boolean.is_number_integer() << '\\n';\n std::cout << j_number_integer.is_number_integer() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_integer() << '\\n';\n std::cout << j_number_float.is_number_integer() << '\\n';\n std::cout << j_object.is_number_integer() << '\\n';\n std::cout << j_array.is_number_integer() << '\\n';\n std::cout << j_string.is_number_integer() << '\\n';\n std::cout << j_binary.is_number_integer() << '\\n';\n}\n Output:
false\nfalse\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number_integer/#see-also","title":"See also","text":"true for unsigned integers in 2.0.0.constexpr bool is_number_unsigned() const noexcept;\n This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.
true if type is an unsigned integer number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number_unsigned/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number_unsigned/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_number_unsigned() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_unsigned()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_unsigned() << '\\n';\n std::cout << j_boolean.is_number_unsigned() << '\\n';\n std::cout << j_number_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_float.is_number_unsigned() << '\\n';\n std::cout << j_object.is_number_unsigned() << '\\n';\n std::cout << j_array.is_number_unsigned() << '\\n';\n std::cout << j_string.is_number_unsigned() << '\\n';\n std::cout << j_binary.is_number_unsigned() << '\\n';\n}\n Output:
false\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number_unsigned/#see-also","title":"See also","text":"constexpr bool is_object() const noexcept;\n This function returns true if and only if the JSON value is an object.
true if type is an object, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_object/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_object/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_object() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_object()\n std::cout << std::boolalpha;\n std::cout << j_null.is_object() << '\\n';\n std::cout << j_boolean.is_object() << '\\n';\n std::cout << j_number_integer.is_object() << '\\n';\n std::cout << j_number_unsigned_integer.is_object() << '\\n';\n std::cout << j_number_float.is_object() << '\\n';\n std::cout << j_object.is_object() << '\\n';\n std::cout << j_array.is_object() << '\\n';\n std::cout << j_string.is_object() << '\\n';\n std::cout << j_binary.is_object() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_object/#version-history","title":"Version history","text":"constexpr bool is_primitive() const noexcept;\n This function returns true if and only if the JSON type is primitive (string, number, boolean, null, binary).
true if type is primitive (string, number, boolean, null, or binary), false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_primitive/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_primitive/#possible-implementation","title":"Possible implementation","text":"constexpr bool is_primitive() const noexcept\n{\n return is_null() || is_string() || is_boolean() || is_number() || is_binary();\n}\n"},{"location":"api/basic_json/is_primitive/#notes","title":"Notes","text":"The term primitive stems from RFC 8259:
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.
The following code exemplifies is_primitive() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_primitive()\n std::cout << std::boolalpha;\n std::cout << j_null.is_primitive() << '\\n';\n std::cout << j_boolean.is_primitive() << '\\n';\n std::cout << j_number_integer.is_primitive() << '\\n';\n std::cout << j_number_unsigned_integer.is_primitive() << '\\n';\n std::cout << j_number_float.is_primitive() << '\\n';\n std::cout << j_object.is_primitive() << '\\n';\n std::cout << j_array.is_primitive() << '\\n';\n std::cout << j_string.is_primitive() << '\\n';\n std::cout << j_binary.is_primitive() << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\nfalse\nfalse\ntrue\ntrue\n"},{"location":"api/basic_json/is_primitive/#see-also","title":"See also","text":"nulltrue for binary types in version 3.8.0.constexpr bool is_string() const noexcept;\n This function returns true if and only if the JSON value is a string.
true if type is a string, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_string/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_string/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_string() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_string()\n std::cout << std::boolalpha;\n std::cout << j_null.is_string() << '\\n';\n std::cout << j_boolean.is_string() << '\\n';\n std::cout << j_number_integer.is_string() << '\\n';\n std::cout << j_number_unsigned_integer.is_string() << '\\n';\n std::cout << j_number_float.is_string() << '\\n';\n std::cout << j_object.is_string() << '\\n';\n std::cout << j_array.is_string() << '\\n';\n std::cout << j_string.is_string() << '\\n';\n std::cout << j_binary.is_string() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\n"},{"location":"api/basic_json/is_string/#version-history","title":"Version history","text":"constexpr bool is_structured() const noexcept;\n This function returns true if and only if the JSON type is structured (array or object).
true if type is structured (array or object), false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_structured/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_structured/#possible-implementation","title":"Possible implementation","text":"constexpr bool is_structured() const noexcept\n{\n return is_array() || is_object();\n}\n"},{"location":"api/basic_json/is_structured/#notes","title":"Notes","text":"The term structured stems from RFC 8259:
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
Note that though strings are containers in C++, they are treated as primitive values in JSON.
"},{"location":"api/basic_json/is_structured/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_structured() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_structured()\n std::cout << std::boolalpha;\n std::cout << j_null.is_structured() << '\\n';\n std::cout << j_boolean.is_structured() << '\\n';\n std::cout << j_number_integer.is_structured() << '\\n';\n std::cout << j_number_unsigned_integer.is_structured() << '\\n';\n std::cout << j_number_float.is_structured() << '\\n';\n std::cout << j_object.is_structured() << '\\n';\n std::cout << j_array.is_structured() << '\\n';\n std::cout << j_string.is_structured() << '\\n';\n std::cout << j_binary.is_structured() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\ntrue\ntrue\nfalse\nfalse\n"},{"location":"api/basic_json/is_structured/#see-also","title":"See also","text":"iteration_proxy<iterator> items() noexcept;\niteration_proxy<const_iterator> items() const noexcept;\n This function allows accessing iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.
For loop without items() function:
for (auto it = j_object.begin(); it != j_object.end(); ++it)\n{\n std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n}\n Range-based for loop without items() function:
for (auto it : j_object)\n{\n // \"it\" is of type json::reference and has no key() member\n std::cout << \"value: \" << it << '\\n';\n}\n Range-based for loop with items() function:
for (auto& el : j_object.items())\n{\n std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n The items() function also allows using structured bindings (C++17):
for (auto& [key, val] : j_object.items())\n{\n std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n"},{"location":"api/basic_json/items/#return-value","title":"Return value","text":"iteration proxy object wrapping the current value with an interface to use in range-based for loops
"},{"location":"api/basic_json/items/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/items/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/items/#notes","title":"Notes","text":"When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string.
Lifetime issues
Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See #2040 for more information.
The following code shows an example for items().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // example for an object\n for (auto& x : j_object.items())\n {\n std::cout << \"key: \" << x.key() << \", value: \" << x.value() << '\\n';\n }\n\n // example for an array\n for (auto& x : j_array.items())\n {\n std::cout << \"key: \" << x.key() << \", value: \" << x.value() << '\\n';\n }\n}\n Output:
key: one, value: 1\nkey: two, value: 2\nkey: 0, value: 1\nkey: 1, value: 2\nkey: 2, value: 4\nkey: 3, value: 8\nkey: 4, value: 16\n"},{"location":"api/basic_json/items/#version-history","title":"Version history","text":"iterator_wrapper in version 3.0.0.items and deprecated iterator_wrapper in version 3.1.0.Deprecation
This function replaces the static function iterator_wrapper which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function iterator_wrapper will be removed in version 4.0.0. Please replace all occurrences of iterator_wrapper(j) with j.items().
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
using json_base_class_t = detail::json_base_class<CustomBaseClass>;\n The base class used to inject custom functionality into each instance of basic_json. Examples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.
CustomBaseClass the base class to be added to basic_json"},{"location":"api/basic_json/json_base_class_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_base_class_t/#default-type","title":"Default type","text":"The default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.
The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.
The following code shows how to inject custom data and methods for each node.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nclass visitor_adaptor_with_metadata\n{\n public:\n template <class Fnc>\n void visit(const Fnc& fnc) const;\n\n int metadata = 42;\n private:\n template <class Ptr, class Fnc>\n void do_visit(const Ptr& ptr, const Fnc& fnc) const;\n};\n\nusing json = nlohmann::basic_json <\n std::map,\n std::vector,\n std::string,\n bool,\n std::int64_t,\n std::uint64_t,\n double,\n std::allocator,\n nlohmann::adl_serializer,\n std::vector<std::uint8_t>,\n visitor_adaptor_with_metadata\n >;\n\ntemplate <class Fnc>\nvoid visitor_adaptor_with_metadata::visit(const Fnc& fnc) const\n{\n do_visit(json::json_pointer{}, fnc);\n}\n\ntemplate <class Ptr, class Fnc>\nvoid visitor_adaptor_with_metadata::do_visit(const Ptr& ptr, const Fnc& fnc) const\n{\n using value_t = nlohmann::detail::value_t;\n const json& j = *static_cast<const json*>(this);\n switch (j.type())\n {\n case value_t::object:\n fnc(ptr, j);\n for (const auto& entry : j.items())\n {\n entry.value().do_visit(ptr / entry.key(), fnc);\n }\n break;\n case value_t::array:\n fnc(ptr, j);\n for (std::size_t i = 0; i < j.size(); ++i)\n {\n j.at(i).do_visit(ptr / std::to_string(i), fnc);\n }\n break;\n case value_t::null:\n case value_t::string:\n case value_t::boolean:\n case value_t::number_integer:\n case value_t::number_unsigned:\n case value_t::number_float:\n case value_t::binary:\n fnc(ptr, j);\n break;\n case value_t::discarded:\n default:\n break;\n }\n}\n\nint main()\n{\n // create a json object\n json j;\n j[\"null\"];\n j[\"object\"][\"uint\"] = 1U;\n j[\"object\"].metadata = 21;\n\n // visit and output\n j.visit(\n [&](const json::json_pointer & p,\n const json & j)\n {\n std::cout << (p.empty() ? std::string{\"/\"} : p.to_string())\n << \" - metadata = \" << j.metadata << \" -> \" << j.dump() << '\\n';\n });\n}\n Output:
/ - metadata = 42 -> {\"null\":null,\"object\":{\"uint\":1}}\n/null - metadata = 42 -> null\n/object - metadata = 21 -> {\"uint\":1}\n/object/uint - metadata = 42 -> 1\n"},{"location":"api/basic_json/json_base_class_t/#version-history","title":"Version history","text":"template<typename T, typename SFINAE>\nusing json_serializer = JSONSerializer<T, SFINAE>;\n"},{"location":"api/basic_json/json_serializer/#template-parameters","title":"Template parameters","text":"T type to convert; will be used in the to_json/from_json functions SFINAE type to add compile type checks via SFINAE; usually void"},{"location":"api/basic_json/json_serializer/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_serializer/#default-type","title":"Default type","text":"The default values for json_serializer is adl_serializer.
The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n"},{"location":"api/basic_json/json_serializer/#version-history","title":"Version history","text":"size_type max_size() const noexcept;\n Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the JSON value.
The return value depends on the different types and is defined as follows:
Value type return value null0 (same as size()) boolean 1 (same as size()) string 1 (same as size()) number 1 (same as size()) binary 1 (same as size()) object result of function object_t::max_size() array result of function array_t::max_size()"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/max_size/#complexity","title":"Complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.
This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of string elements the JSON value can store which is 1.
The following code calls max_size() on the different value types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call max_size()\n std::cout << j_null.max_size() << '\\n';\n std::cout << j_boolean.max_size() << '\\n';\n std::cout << j_number_integer.max_size() << '\\n';\n std::cout << j_number_float.max_size() << '\\n';\n std::cout << j_object.max_size() << '\\n';\n std::cout << j_array.max_size() << '\\n';\n std::cout << j_string.max_size() << '\\n';\n}\n Output:
0\n1\n1\n1\n115292150460684697\n576460752303423487\n1\n Note the output is platform-dependent.
"},{"location":"api/basic_json/max_size/#version-history","title":"Version history","text":"1 for binary types in version 3.8.0.void merge_patch(const basic_json& apply_patch);\n The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):
define MergePatch(Target, Patch):\n if Patch is an Object:\n if Target is not an Object:\n Target = {} // Ignore the contents and set it to an empty Object\n for each Name/Value pair in Patch:\n if Value is null:\n if Name exists in Target:\n remove the Name/Value pair from Target\n else:\n Target[Name] = MergePatch(Target[Name], Value)\n return Target\n else:\n return Patch\n Thereby, Target is the current object; that is, the patch is applied to the current value.
apply_patch (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"Linear in the lengths of apply_patch.
The following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n Output:
{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n"},{"location":"api/basic_json/merge_patch/#see-also","title":"See also","text":"static basic_json meta();\n This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.
"},{"location":"api/basic_json/meta/#return-value","title":"Return value","text":"JSON object holding version information
key descriptioncompiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown. url The URL of the project as string. version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/meta/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/meta/#examples","title":"Examples","text":"ExampleThe following code shows an example output of the meta() function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // call meta()\n std::cout << std::setw(4) << json::meta() << '\\n';\n}\n Output:
{\n \"compiler\": {\n \"c++\": \"201103\",\n \"family\": \"gcc\",\n \"version\": \"12.3.0\"\n },\n \"copyright\": \"(C) 2013-2022 Niels Lohmann\",\n \"name\": \"JSON for Modern C++\",\n \"platform\": \"apple\",\n \"url\": \"https://github.com/nlohmann/json\",\n \"version\": {\n \"major\": 3,\n \"minor\": 11,\n \"patch\": 3,\n \"string\": \"3.11.3\"\n }\n}\n Note the output is platform-dependent.
"},{"location":"api/basic_json/meta/#see-also","title":"See also","text":"using number_float_t = NumberFloatType;\n The type used to store JSON numbers (floating-point).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store floating-point numbers in C++, a type is defined by the template parameter NumberFloatType which chooses the type to use.
With the default values for NumberFloatType (double), the default value for number_float_t is double.
01.2 will be serialized to 1.2. During deserialization, leading zeros yield an error.null.RFC 8259 states:
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.
This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.
Floating-point number values are stored directly inside a basic_json type.
The following code shows that number_float_t is by default, a typedef to double.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<double, json::number_float_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/number_float_t/#version-history","title":"Version history","text":"using number_integer_t = NumberIntegerType;\n The type used to store JSON numbers (integers).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.
With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.
"},{"location":"api/basic_json/number_integer_t/#storage","title":"Storage","text":"Integer number values are stored directly inside a basic_json type.
The following code shows that number_integer_t is by default, a typedef to std::int64_t.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::int64_t, json::number_integer_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/number_integer_t/#version-history","title":"Version history","text":"using number_unsigned_t = NumberUnsignedType;\n The type used to store JSON numbers (unsigned).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.
With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range \\f[-2^{53}+1, 2^{53}-1]\\f are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.
Integer number values are stored directly inside a basic_json type.
The following code shows that number_unsigned_t is by default, a typedef to std::uint64_t.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::uint64_t, json::number_unsigned_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/number_unsigned_t/#version-history","title":"Version history","text":"static basic_json object(initializer_list_t init = {});\n Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.
init (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"JSON object value
"},{"location":"api/basic_json/object/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/object/#exceptions","title":"Exceptions","text":"Throws type_error.301 if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list init. See example below.
Linear in the size of init.
This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t).
The following code shows an example for the object function.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON objects\n json j_no_init_list = json::object();\n json j_empty_init_list = json::object({});\n json j_list_of_pairs = json::object({ {\"one\", 1}, {\"two\", 2} });\n\n // serialize the JSON objects\n std::cout << j_no_init_list << '\\n';\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_list_of_pairs << '\\n';\n\n // example for an exception\n try\n {\n // can only create an object from a list of pairs\n json j_invalid_object = json::object({{ \"one\", 1, 2 }});\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
{}\n{}\n{\"one\":1,\"two\":2}\n[json.exception.type_error.301] cannot create object from initializer list\n"},{"location":"api/basic_json/object/#see-also","title":"See also","text":"basic_json(initializer_list_t) - create a JSON value from an initializer listarray - create a JSON array value from an initializer listusing object_comparator_t = typename object_t::key_compare;\n// or\nusing object_comparator_t = default_object_comparator_t;\n The comparator used by object_t. Defined as typename object_t::key_compare if available, and default_object_comparator_t otherwise.
The example below demonstrates the used object comparator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha\n << \"json::object_comparator_t(\\\"one\\\", \\\"two\\\") = \" << json::object_comparator_t{}(\"one\", \"two\") << \"\\n\"\n << \"json::object_comparator_t(\\\"three\\\", \\\"four\\\") = \" << json::object_comparator_t{}(\"three\", \"four\") << std::endl;\n}\n Output:
json::object_comparator_t(\"one\", \"two\") = true\njson::object_comparator_t(\"three\", \"four\") = false\n"},{"location":"api/basic_json/object_comparator_t/#version-history","title":"Version history","text":"typename object_t::key_compare or default_object_comparator_t in version 3.11.0.using object_t = ObjectType<StringType,\n basic_json,\n default_object_comparator_t,\n AllocatorType<std::pair<const StringType, basic_json>>>;\n The type used to store JSON objects.
RFC 8259 describes JSON objects as follows:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
To store objects in C++, a type is defined by the template parameters described below.
"},{"location":"api/basic_json/object_t/#template-parameters","title":"Template parameters","text":"ObjectType the container to store objects (e.g., std::map or std::unordered_map) StringType the type of the keys or names (e.g., std::string). The comparison function std::less<StringType> is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/object_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/object_t/#default-type","title":"Default type","text":"With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:
// until C++14\nstd::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<std::string>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n\n// since C++14\nstd::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n See default_object_comparator_t for more information.
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
{\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.dump) in this order. For instance, {\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be stored and serialized as {\"a\": 2, \"b\": 1}.{\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be treated as equal.RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.
Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.
The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.
The following code shows that object_t is by default, a typedef to std::map<json::string_t, json>.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::map<json::string_t, json>, json::object_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/object_t/#version-history","title":"Version history","text":"// (1)\nreference operator+=(basic_json&& val);\nreference operator+=(const basic_json& val);\n\n// (2)\nreference operator+=(const typename object_t::value_type& val);\n\n// (3)\nreference operator+=(initializer_list_t init);\n Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.
Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.
This function allows using operator+= with an initializer list. In case
init contains only two elements, andinit is a string,init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).
For all cases where an element is added to an 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.
For ordered_json, also adding an element to an object can yield a reallocation which again invalidates all iterators and all references.
val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"*this
All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use operator+=() with number\"
size())).init.(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n Output:
[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n object.push_back(json::object_t::value_type(\"three\", 3));\n object += json::object_t::value_type(\"four\", 4);\n null += json::object_t::value_type(\"A\", \"a\");\n null += json::object_t::value_type(\"B\", \"b\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values:\n object.push_back({\"three\", 3}); // object is extended\n object += {\"four\", 4}; // object is extended\n null.push_back({\"five\", 5}); // null is converted to array\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // would throw:\n //object.push_back({1, 2, 3});\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n"},{"location":"api/basic_json/operator%2B%3D/#see-also","title":"See also","text":"basic_json& operator=(basic_json other) noexcept (\n std::is_nothrow_move_constructible<value_t>::value &&\n std::is_nothrow_move_assignable<value_t>::value &&\n std::is_nothrow_move_constructible<json_value>::value &&\n std::is_nothrow_move_assignable<json_value>::value\n);\n Copy assignment operator. Copies a JSON value via the \"copy and swap\" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function.
other (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator%3D/#examples","title":"Examples","text":"ExampleThe code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json a = 23;\n json b = 42;\n\n // copy-assign a to b\n b = a;\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n Output:
23\n23\n"},{"location":"api/basic_json/operator%3D/#version-history","title":"Version history","text":"// (1)\nreference operator[](size_type idx);\nconst_reference operator[](size_type idx) const;\n\n// (2)\nreference operator[](typename object_t::key_type key);\nconst_reference operator[](const typename object_t::key_type& key) const;\n\n// (3)\ntemplate<typename KeyType>\nreference operator[](KeyType&& key);\ntemplate<typename KeyType>\nconst_reference operator[](KeyType&& key) const;\n\n// (4)\nreference operator[](const json_pointer& ptr);\nconst_reference operator[](const json_pointer& ptr) const;\n idx.key. The non-const qualified overload takes the key by value.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr.KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#iterator-invalidation","title":"Iterator invalidation","text":"For the non-const versions 1. and 4., when passing an array index that does not exist, it is created and filled with a null value before a reference to it is returned. For this, a reallocation can happen, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
For ordered_json, also passing an object key to the non-const versions 2., 3., and 4., a reallocation can happen which again invalidates all iterators and all references.
idx (in) index of the element to access key (in) object key of the element to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"idxkeykeyptrStrong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/operator%5B%5D/#exceptions","title":"Exceptions","text":"type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense.type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense.parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'.parse_error.109 if an array index in the passed JSON pointer ptr is not a number.out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version.out_of_range.404 if the JSON pointer ptr can not be resolved.idx is in the range of the array. Otherwise, linear in idx - size().Undefined behavior and runtime assertions
idx does not exist, the behavior is undefined.key does not exist, the behavior is undefined and is guarded by a runtime assertion!The non-const version may add values: If idx is beyond the range of the array (i.e., idx >= size()), then the array is silently filled up with null values to make idx a valid reference to the last stored element. In case the value was null before, it is converted to an array.
If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.
See 2.
null values are created in arrays and objects if necessary.
In particular:
null value before a reference to it is returned.null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.- is treated as a synonym for the index past the end.The example below shows how array elements can be read and written using [] operator. Note the addition of null values.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json array = {1, 2, 3, 4, 5};\n\n // output element at index 3 (fourth element)\n std::cout << array[3] << '\\n';\n\n // change last element to 6\n array[array.size() - 1] = 6;\n\n // output changed array\n std::cout << array << '\\n';\n\n // write beyond array limit\n array[10] = 11;\n\n // output changed array\n std::cout << array << '\\n';\n}\n Output:
4\n[1,2,3,4,6]\n[1,2,3,4,6,null,null,null,null,null,11]\n Example: (1) access specified array element (const) The example below shows how array elements can be read using the [] operator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n}\n Output:
\"third\"\n Example: (2) access specified object element The example below shows how object elements can be read and written using the [] operator.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"] << \"\\n\\n\";\n\n // change element with key \"three\"\n object[\"three\"] = 3;\n\n // output changed array\n std::cout << std::setw(4) << object << \"\\n\\n\";\n\n // mention nonexisting key\n object[\"four\"];\n\n // write to nonexisting key\n object[\"five\"][\"really\"][\"nested\"] = true;\n\n // output changed object\n std::cout << std::setw(4) << object << '\\n';\n}\n Output:
2\n\n{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n\n{\n \"five\": {\n \"really\": {\n \"nested\": true\n }\n },\n \"four\": null,\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n Example: (2) access specified object element (const) The example below shows how object elements can be read using the [] operator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n const json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"] << '\\n';\n}\n Output:
2\n Example: (3) access specified object element using string_view The example below shows how object elements can be read using the [] operator.
#include <iostream>\n#include <iomanip>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"sv] << \"\\n\\n\";\n\n // change element with key \"three\"\n object[\"three\"sv] = 3;\n\n // output changed array\n std::cout << std::setw(4) << object << \"\\n\\n\";\n\n // mention nonexisting key\n object[\"four\"sv];\n\n // write to nonexisting key\n object[\"five\"sv][\"really\"sv][\"nested\"sv] = true;\n\n // output changed object\n std::cout << std::setw(4) << object << '\\n';\n}\n Output:
2\n\n{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n\n{\n \"five\": {\n \"really\": {\n \"nested\": true\n }\n },\n \"four\": null,\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n Example: (3) access specified object element using string_view (const) The example below shows how object elements can be read using the [] operator.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n const json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"sv] << '\\n';\n}\n Output:
2\n Example: (4) access specified element via JSON Pointer The example below shows how values can be read and written using JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j[\"/number\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j[\"/string\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j[\"/array\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j[\"/array/1\"_json_pointer] << '\\n';\n\n // writing access\n\n // change the string\n j[\"/string\"_json_pointer] = \"bar\";\n // output the changed string\n std::cout << j[\"string\"] << '\\n';\n\n // \"change\" a nonexisting object entry\n j[\"/boolean\"_json_pointer] = true;\n // output the changed object\n std::cout << j << '\\n';\n\n // change an array element\n j[\"/array/1\"_json_pointer] = 21;\n // \"change\" an array element with nonexisting index\n j[\"/array/4\"_json_pointer] = 44;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n\n // \"change\" the array element past the end\n j[\"/array/-\"_json_pointer] = 55;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n}\n Output:
1\n\"foo\"\n[1,2]\n2\n\"bar\"\n{\"array\":[1,2],\"boolean\":true,\"number\":1,\"string\":\"bar\"}\n[1,21,null,null,44]\n[1,21,null,null,44,55]\n Example: (4) access specified element via JSON Pointer (const) The example below shows how values can be read using JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n const json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j[\"/number\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j[\"/string\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j[\"/array\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j[\"/array/1\"_json_pointer] << '\\n';\n}\n Output:
1\n\"foo\"\n[1,2]\n2\n"},{"location":"api/basic_json/operator%5B%5D/#see-also","title":"See also","text":"at for access by reference with range checkingvalue for access with default valueT* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0.template<typename ValueType>\nJSON_EXPLICIT operator ValueType() const;\n Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.
ValueType the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"copy of the JSON value, converted to ValueType
Depends on what json_serializer<ValueType> from_json() method throws
Linear in the size of the JSON value.
"},{"location":"api/basic_json/operator_ValueType/#notes","title":"Notes","text":"Definition of JSON_EXPLICIT
By default JSON_EXPLICIT is defined to the empty string, so the signature is:
template<typename ValueType>\noperator ValueType() const;\n If JSON_USE_IMPLICIT_CONVERSIONS is set to 0, JSON_EXPLICIT is defined to explicit:
template<typename ValueType>\nexplicit operator ValueType() const;\n That is, implicit conversions can be switched off by defining JSON_USE_IMPLICIT_CONVERSIONS to 0.
Future behavior change
Implicit conversions will be switched off by default in the next major release of the library. That is, JSON_EXPLICIT will be set to explicit by default.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use implicit conversions\n bool v1 = json_types[\"boolean\"];\n int v2 = json_types[\"number\"][\"integer\"];\n short v3 = json_types[\"number\"][\"integer\"];\n float v4 = json_types[\"number\"][\"floating-point\"];\n int v5 = json_types[\"number\"][\"floating-point\"];\n std::string v6 = json_types[\"string\"];\n std::vector<short> v7 = json_types[\"array\"];\n std::unordered_map<std::string, json> v8 = json_types;\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n\n // example for an exception\n try\n {\n bool v1 = json_types[\"string\"];\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n[json.exception.type_error.302] type must be boolean, but is string\n"},{"location":"api/basic_json/operator_ValueType/#version-history","title":"Version history","text":"JSON_EXPLICIT/JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.// until C++20\nbool operator==(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator==(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator==(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n\n// since C++20\nclass basic_json {\n bool operator==(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n bool operator==(ScalarType rhs) const noexcept; // (2)\n};\n Compares two JSON values for equality according to the following rules:
operator==.Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are equal
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_eq/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_eq/#notes","title":"Notes","text":"Comparing special values
NaN values are unordered within the domain of numbers. The following comparisons all yield false:NaN with itself.NaN with another NaN.NaN and any other number.null values are all equal.Comparing floating-point numbers
Floating-point numbers inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default. To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance
template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\ninline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n{\n return std::abs(a - b) <= epsilon;\n}\n Or you can self-defined operator equal function like this:
bool my_equal(const_reference lhs, const_reference rhs)\n{\n const auto lhs_type lhs.type();\n const auto rhs_type rhs.type();\n if (lhs_type == rhs_type)\n {\n switch(lhs_type)\n // self_defined case\n case value_t::number_float:\n return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();\n // other cases remain the same with the original\n ...\n }\n...\n}\n Comparing different basic_json specializations
Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects
{\n \"version\": 1,\n \"type\": \"integer\"\n}\n and
{\n \"type\": \"integer\",\n \"version\": 1\n}\n depends on whether nlohmann::json or nlohmann::ordered_json is used:
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n nlohmann::json uj1 = {{\"version\", 1}, {\"type\", \"integer\"}};\n nlohmann::json uj2 = {{\"type\", \"integer\"}, {\"version\", 1}};\n\n nlohmann::ordered_json oj1 = {{\"version\", 1}, {\"type\", \"integer\"}};\n nlohmann::ordered_json oj2 = {{\"type\", \"integer\"}, {\"version\", 1}};\n\n std::cout << std::boolalpha << (uj1 == uj2) << '\\n' << (oj1 == oj2) << std::endl;\n}\n Output:
true\nfalse\n"},{"location":"api/basic_json/operator_eq/#examples","title":"Examples","text":"Example The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.000000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 == array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 == object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 == number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 == string_2) << '\\n';\n}\n Output:
[1,2,3] == [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} == {\"A\":\"a\",\"B\":\"b\"} true\n17 == 17.0 true\n\"foo\" == \"bar\" false\n Example The example demonstrates comparing several JSON types against the null pointer (JSON null).
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array = {1, 2, 3};\n json object = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json number = 17;\n json string = \"foo\";\n json null;\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array << \" == nullptr \" << (array == nullptr) << '\\n';\n std::cout << object << \" == nullptr \" << (object == nullptr) << '\\n';\n std::cout << number << \" == nullptr \" << (number == nullptr) << '\\n';\n std::cout << string << \" == nullptr \" << (string == nullptr) << '\\n';\n std::cout << null << \" == nullptr \" << (null == nullptr) << '\\n';\n}\n Output:
[1,2,3] == nullptr false\n{\"A\":\"a\",\"B\":\"b\"} == nullptr false\n17 == nullptr false\n\"foo\" == nullptr false\nnull == nullptr true\n"},{"location":"api/basic_json/operator_eq/#version-history","title":"Version history","text":"// until C++20\nbool operator>=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator>=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator>=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs < rhs) (see operator<).Compares whether a JSON value is greater than or equal to a scalar or a scalar is greater than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"whether lhs is less than or equal to rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_ge/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_ge/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" >= \" << array_2 << \" \" << (array_1 >= array_2) << '\\n';\n std::cout << object_1 << \" >= \" << object_2 << \" \" << (object_1 >= object_2) << '\\n';\n std::cout << number_1 << \" >= \" << number_2 << \" \" << (number_1 >= number_2) << '\\n';\n std::cout << string_1 << \" >= \" << string_2 << \" \" << (string_1 >= string_2) << '\\n';\n}\n Output:
[1,2,3] >= [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} >= {\"A\":\"a\",\"B\":\"b\"} true\n17 >= 17.0000000000001 false\n\"foo\" >= \"bar\" true\n"},{"location":"api/basic_json/operator_ge/#see-also","title":"See also","text":"// until C++20\nbool operator>(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator>(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator>(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs <= rhs) (see operator<=).Compares whether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"whether lhs is greater than rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_gt/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_gt/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" > \" << array_2 << \" \" << (array_1 > array_2) << '\\n';\n std::cout << object_1 << \" > \" << object_2 << \" \" << (object_1 > object_2) << '\\n';\n std::cout << number_1 << \" > \" << number_2 << \" \" << (number_1 > number_2) << '\\n';\n std::cout << string_1 << \" > \" << string_2 << \" \" << (string_1 > string_2) << '\\n';\n}\n Output:
[1,2,3] > [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} > {\"A\":\"a\",\"B\":\"b\"} false\n17 > 17.0000000000001 false\n\"foo\" > \"bar\" true\n"},{"location":"api/basic_json/operator_gt/#see-also","title":"See also","text":"// until C++20\nbool operator<=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator<=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator<=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(rhs < lhs) (see operator<).Compares whether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"whether lhs is less than or equal to rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_le/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_le/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" <= \" << array_2 << \" \" << (array_1 <= array_2) << '\\n';\n std::cout << object_1 << \" <= \" << object_2 << \" \" << (object_1 <= object_2) << '\\n';\n std::cout << number_1 << \" <= \" << number_2 << \" \" << (number_1 <= number_2) << '\\n';\n std::cout << string_1 << \" <= \" << string_2 << \" \" << (string_1 <= string_2) << '\\n';\n}\n Output:
[1,2,3] <= [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} <= {\"A\":\"a\",\"B\":\"b\"} true\n17 <= 17.0000000000001 true\n\"foo\" <= \"bar\" false\n"},{"location":"api/basic_json/operator_le/#see-also","title":"See also","text":"// until C++20\nbool operator<(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator<(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator<(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:
false.operator<.lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:Compares whether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"whether lhs is less than rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_lt/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_lt/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 < array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 < object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 < number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 < string_2) << '\\n';\n}\n Output:
[1,2,3] == [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} == {\"A\":\"a\",\"B\":\"b\"} false\n17 == 17.0000000000001 true\n\"foo\" == \"bar\" false\n"},{"location":"api/basic_json/operator_lt/#see-also","title":"See also","text":"// until C++20\nbool operator!=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator!=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator!=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n\n// since C++20\nclass basic_json {\n bool operator!=(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n bool operator!=(ScalarType rhs) const noexcept; // (2)\n};\n Compares two JSON values for inequality according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are not equal
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_ne/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_ne/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.000000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" != \" << array_2 << \" \" << (array_1 != array_2) << '\\n';\n std::cout << object_1 << \" != \" << object_2 << \" \" << (object_1 != object_2) << '\\n';\n std::cout << number_1 << \" != \" << number_2 << \" \" << (number_1 != number_2) << '\\n';\n std::cout << string_1 << \" != \" << string_2 << \" \" << (string_1 != string_2) << '\\n';\n}\n Output:
[1,2,3] != [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} != {\"A\":\"a\",\"B\":\"b\"} false\n17 != 17.0 false\n\"foo\" != \"bar\" true\n Example The example demonstrates comparing several JSON types against the null pointer (JSON null).
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array = {1, 2, 3};\n json object = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json number = 17;\n json string = \"foo\";\n json null;\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array << \" != nullptr \" << (array != nullptr) << '\\n';\n std::cout << object << \" != nullptr \" << (object != nullptr) << '\\n';\n std::cout << number << \" != nullptr \" << (number != nullptr) << '\\n';\n std::cout << string << \" != nullptr \" << (string != nullptr) << '\\n';\n std::cout << null << \" != nullptr \" << (null != nullptr) << '\\n';\n}\n Output:
[1,2,3] != nullptr true\n{\"A\":\"a\",\"B\":\"b\"} != nullptr true\n17 != nullptr true\n\"foo\" != nullptr true\nnull != nullptr false\n"},{"location":"api/basic_json/operator_ne/#version-history","title":"Version history","text":"// since C++20\nclass basic_json {\n std::partial_ordering operator<=>(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n std::partial_ordering operator<=>(const ScalarType rhs) const noexcept; // (2)\n};\n 3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:
std::partial_ordering::unordered if either value is discarded.operator<=>.operator<=>. For instance, comparing an integer and a floating-point value will 3-way compare the first value converted to floating-point with the second value.value_t).3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way comparing both JSON values (see 1).
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"rhs (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"the std::partial_ordering of the 3-way comparison of *this and rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_spaceship/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_spaceship/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered:NaN with itself.NaN with another NaN.NaN and any other number.The example demonstrates comparing several JSON values.
#include <compare>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nconst char* to_string(const std::partial_ordering& po)\n{\n if (std::is_lt(po))\n {\n return \"less\";\n }\n else if (std::is_gt(po))\n {\n return \"greater\";\n }\n else if (std::is_eq(po))\n {\n return \"equivalent\";\n }\n return \"unordered\";\n}\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number = 17;\n json string = \"foo\";\n json discarded = json(json::value_t::discarded);\n\n // output values and comparisons\n std::cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string(array_1 <=> array_2) << '\\n'; // *NOPAD*\n std::cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string(object_1 <=> object_2) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << number << \" := \" << to_string(string <=> number) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << discarded << \" := \" << to_string(string <=> discarded) << '\\n'; // *NOPAD*\n}\n Output:
[1,2,3] <=> [1,2,4] := less\n{\"A\":\"a\",\"B\":\"b\"} <=> {\"A\":\"a\",\"B\":\"b\"} := equivalent\n\"foo\" <=> 17 := greater\n\"foo\" <=> <discarded> := unordered\n Example: (2) comparing JSON values and scalars The example demonstrates comparing several JSON values and scalars.
#include <compare>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nconst char* to_string(const std::partial_ordering& po)\n{\n if (std::is_lt(po))\n {\n return \"less\";\n }\n else if (std::is_gt(po))\n {\n return \"greater\";\n }\n else if (std::is_eq(po))\n {\n return \"equivalent\";\n }\n return \"unordered\";\n}\n\nint main()\n{\n using float_limits = std::numeric_limits<json::number_float_t>;\n constexpr auto nan = float_limits::quiet_NaN();\n\n // create several JSON values\n json boolean = false;\n json number = 17;\n json string = \"17\";\n\n // output values and comparisons\n std::cout << std::boolalpha << std::fixed;\n std::cout << boolean << \" <=> \" << true << \" := \" << to_string(boolean <=> true) << '\\n'; // *NOPAD*\n std::cout << number << \" <=> \" << 17.0 << \" := \" << to_string(number <=> 17.0) << '\\n'; // *NOPAD*\n std::cout << number << \" <=> \" << nan << \" := \" << to_string(number <=> nan) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << 17 << \" := \" << to_string(string <=> 17) << '\\n'; // *NOPAD*\n}\n Output:
false <=> true := less\n17 <=> 17.000000 := equivalent\n17 <=> nan := unordered\n\"17\" <=> 17 := greater\n"},{"location":"api/basic_json/operator_spaceship/#see-also","title":"See also","text":"constexpr operator value_t() const noexcept;\n Return the type of the JSON value as a value from the value_t enumeration.
the type of the JSON value
Value type return valuenull value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/operator_value_t/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/operator_value_t/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/operator_value_t/#examples","title":"Examples","text":"ExampleThe following code exemplifies operator value_t() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call operator value_t()\n json::value_t t_null = j_null;\n json::value_t t_boolean = j_boolean;\n json::value_t t_number_integer = j_number_integer;\n json::value_t t_number_unsigned = j_number_unsigned;\n json::value_t t_number_float = j_number_float;\n json::value_t t_object = j_object;\n json::value_t t_array = j_array;\n json::value_t t_string = j_string;\n\n // print types\n std::cout << std::boolalpha;\n std::cout << (t_null == json::value_t::null) << '\\n';\n std::cout << (t_boolean == json::value_t::boolean) << '\\n';\n std::cout << (t_number_integer == json::value_t::number_integer) << '\\n';\n std::cout << (t_number_unsigned == json::value_t::number_unsigned) << '\\n';\n std::cout << (t_number_float == json::value_t::number_float) << '\\n';\n std::cout << (t_object == json::value_t::object) << '\\n';\n std::cout << (t_array == json::value_t::array) << '\\n';\n std::cout << (t_string == json::value_t::string) << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n"},{"location":"api/basic_json/operator_value_t/#version-history","title":"Version history","text":"class other_error : public exception;\n This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx (see list of other errors).
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_other_error fill:#CCCCFF"},{"location":"api/basic_json/other_error/#member-functions","title":"Member functions","text":"The following code shows how a other_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n try\n {\n // executing a failing JSON Patch operation\n json value = R\"({\n \"best_biscuit\": {\n \"name\": \"Oreo\"\n }\n })\"_json;\n json patch = R\"([{\n \"op\": \"test\",\n \"path\": \"/best_biscuit/name\",\n \"value\": \"Choco Leibniz\"\n }])\"_json;\n value.patch(patch);\n }\n catch (const json::other_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n"},{"location":"api/basic_json/other_error/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeclass out_of_range : public exception;\n This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx (see list of out-of-range errors).
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_out_of_range fill:#CCCCFF"},{"location":"api/basic_json/out_of_range/#member-functions","title":"Member functions","text":"The following code shows how a out_of_range exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for an invalid index\n json j = {1, 2, 3, 4};\n j.at(4) = 10;\n }\n catch (const json::out_of_range& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n"},{"location":"api/basic_json/out_of_range/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeother_error for exceptions indicating other library errors// (1)\ntemplate<typename InputType>\nstatic basic_json parse(InputType&& i,\n const parser_callback_t cb = nullptr,\n const bool allow_exceptions = true,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json parse(IteratorType first, IteratorType last,\n const parser_callback_t cb = nullptr,\n const bool allow_exceptions = true,\n const bool ignore_comments = false);\n Deserialize from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
InputType A compatible input, for instance:
std::istream objectFILE pointer (throws if null)std::stringobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type, for instance.
std::string::iterator or std::vector<std::uint8_t>::iteratorptr and ptr + leni (in) Input to parse from. cb (in) a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/parse/#exceptions","title":"Exceptions","text":"parse_error.101 in case of an unexpected token, or empty input like a null FILE* or char* pointer.parse_error.102 if to_unicode fails or surrogate error.parse_error.103 if to_unicode fails.Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb or reading from (1) the input i or (2) the iterator range [first, last] has a super-linear complexity.
A UTF-8 byte order mark is silently ignored.
"},{"location":"api/basic_json/parse/#examples","title":"Examples","text":"Parsing from a character arrayThe example below demonstrates the parse() function reading from an array.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n char text[] = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n Parsing from a string The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n Parsing from an input stream The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // fill a stream with JSON text\n std::stringstream ss;\n ss << text;\n\n // parse and serialize JSON\n json j_complete = json::parse(ss);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // fill a stream with JSON text\n ss.clear();\n ss << text;\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(ss, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n Parsing from a contiguous container The example below demonstrates the parse() function reading from a contiguous container.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given as std::vector\n std::vector<std::uint8_t> text = {'[', '1', ',', '2', ',', '3', ']', '\\0'};\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
[\n 1,\n 2,\n 3\n]\n Parsing from a non null-terminated string The example below demonstrates the parse() function reading from a string that is not null-terminated.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given as string that is not null-terminated\n const char* ptr = \"[1,2,3]another value\";\n\n // parse and serialize JSON\n json j_complete = json::parse(ptr, ptr + 7);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
[\n 1,\n 2,\n 3\n]\n Parsing from an iterator pair The example below demonstrates the parse() function reading from an iterator pair.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given an input with other values\n std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'};\n\n // parse and serialize JSON\n json j_complete = json::parse(input.begin(), input.begin() + 7);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
[\n 1,\n 2,\n 3\n]\n Effect of allow_exceptions parameter The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // an invalid JSON text\n std::string text = R\"(\n {\n \"key\": \"value without closing quotes\n }\n )\";\n\n // parse with exceptions\n try\n {\n json j = json::parse(text);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n // parse without exceptions\n json j = json::parse(text, nullptr, false);\n\n if (j.is_discarded())\n {\n std::cout << \"the input is invalid JSON\" << std::endl;\n }\n else\n {\n std::cout << \"the input is valid JSON: \" << j << std::endl;\n }\n}\n Output:
[json.exception.parse_error.101] parse error at line 4, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n; last read: '\"value without closing quotes<U+000A>'\nthe input is invalid JSON\n"},{"location":"api/basic_json/parse/#see-also","title":"See also","text":"ignore_comments added in version 3.9.0.FILE* null pointers to exception in version 3.11.4.Deprecation
Overload (2) replaces calls to parse with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like parse({ptr, ptr+len}, ...); with parse(ptr, ptr+len, ...);.
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
class parse_error : public exception;\n This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, BSON, CBOR, MessagePack, UBJSON, as well as when using JSON Patch.
Member byte holds the byte index of the last read character in the input file (see note below).
Exceptions have ids 1xx (see list of parse errors).
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_parse_error fill:#CCCCFF"},{"location":"api/basic_json/parse_error/#member-functions","title":"Member functions","text":"For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector for binary formats.
"},{"location":"api/basic_json/parse_error/#examples","title":"Examples","text":"ExampleThe following code shows how a parse_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // parsing input with a syntax error\n json::parse(\"[1,2,3,]\");\n }\n catch (const json::parse_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << '\\n'\n << \"byte position of error: \" << e.byte << std::endl;\n }\n}\n Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nexception id: 101\nbyte position of error: 8\n"},{"location":"api/basic_json/parse_error/#see-also","title":"See also","text":"invalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsenum class parse_event_t : std::uint8_t {\n object_start,\n object_end,\n array_start,\n array_end,\n key,\n value\n};\n The parser callback distinguishes the following events:
object_start: the parser read { and started to process a JSON objectkey: the parser read a key of a value in an objectobject_end: the parser read } and finished processing a JSON objectarray_start: the parser read [ and started to process a JSON arrayarray_end: the parser read ] and finished processing a JSON arrayvalue: the parser finished reading a JSON valuetemplate<typename BasicJsonType>\nusing parser_callback_t =\n std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Discarding a value (i.e., returning false) has different effects depending on the context in which function was called:
null. This case happens if the top-level element is skipped.depth (in) the depth of the recursion during parsing event (in) an event of type parse_event_t indicating the context in the callback function has been called parsed (in, out) the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.
The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n"},{"location":"api/basic_json/parser_callback_t/#version-history","title":"Version history","text":"basic_json patch(const basic_json& json_patch) const;\n JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
"},{"location":"api/basic_json/patch/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch/#return-value","title":"Return value","text":"patched document
"},{"location":"api/basic_json/patch/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/patch/#exceptions","title":"Exceptions","text":"parse_error.104 if the JSON patch does not consist of an array of objects.parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".out_of_range.401 if an array index is out of range.out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: \"key baz not found\".out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")out_of_range.501 if \"test\" operation was unsuccessful.Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.
"},{"location":"api/basic_json/patch/#notes","title":"Notes","text":"The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value.
"},{"location":"api/basic_json/patch/#examples","title":"Examples","text":"ExampleThe following code shows how a JSON patch is applied to a value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // apply the patch\n json patched_doc = doc.patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << doc << \"\\n\\n\"\n << std::setw(4) << patched_doc << std::endl;\n}\n Output:
{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"api/basic_json/patch/#see-also","title":"See also","text":"void patch_inplace(const basic_json& json_patch) const;\n JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. This function applies a JSON patch in place and returns void.
"},{"location":"api/basic_json/patch_inplace/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch_inplace/#exception-safety","title":"Exception safety","text":"No guarantees, value may be corrupted by an unsuccessful patch operation.
"},{"location":"api/basic_json/patch_inplace/#exceptions","title":"Exceptions","text":"parse_error.104 if the JSON patch does not consist of an array of objects.parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".out_of_range.401 if an array index is out of range.out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: \"key baz not found\".out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")out_of_range.501 if \"test\" operation was unsuccessful.Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.
"},{"location":"api/basic_json/patch_inplace/#notes","title":"Notes","text":"Unlike patch, patch_inplace applies the operation \"in place\" and no copy of the JSON value is created. That makes it faster for large documents by avoiding the copy. However, the JSON value might be corrupted if the function throws an exception.
The following code shows how a JSON patch is applied to a value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // output original document\n std::cout << \"Before\\n\" << std::setw(4) << doc << std::endl;\n\n // apply the patch\n doc.patch_inplace(patch);\n\n // output patched document\n std::cout << \"\\nAfter\\n\" << std::setw(4) << doc << std::endl;\n}\n Output:
Before\n{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\nAfter\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"api/basic_json/patch_inplace/#see-also","title":"See also","text":"// (1)\nvoid push_back(basic_json&& val);\nvoid push_back(const basic_json& val);\n\n// (2)\nvoid push_back(const typename object_t::value_type& val);\n\n// (3)\nvoid push_back(initializer_list_t init);\n Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.
Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.
This function allows using push_back with an initializer list. In case
init contains only two elements, andinit is a string,init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).
For all cases where an element is added to an 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.
For ordered_json, also adding an element to an object can yield a reallocation which again invalidates all iterators and all references.
val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use push_back() with number\"
size())).init.(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n Output:
[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n object.push_back(json::object_t::value_type(\"three\", 3));\n object += json::object_t::value_type(\"four\", 4);\n null += json::object_t::value_type(\"A\", \"a\");\n null += json::object_t::value_type(\"B\", \"b\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values:\n object.push_back({\"three\", 3}); // object is extended\n object += {\"four\", 4}; // object is extended\n null.push_back({\"five\", 5}); // null is converted to array\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // would throw:\n //object.push_back({1, 2, 3});\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n"},{"location":"api/basic_json/push_back/#see-also","title":"See also","text":"reverse_iterator rbegin() noexcept;\nconst_reverse_iterator rbegin() const noexcept;\n Returns an iterator to the reverse-beginning; that is, the last element.
"},{"location":"api/basic_json/rbegin/#return-value","title":"Return value","text":"reverse iterator to the first element
"},{"location":"api/basic_json/rbegin/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/rbegin/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/rbegin/#examples","title":"Examples","text":"ExampleThe following code shows an example for rbegin().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-beginning\n json::reverse_iterator it = array.rbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n Output:
5\n"},{"location":"api/basic_json/rbegin/#version-history","title":"Version history","text":"reverse_iterator rend() noexcept;\nconst_reverse_iterator rend() const noexcept;\n Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.
"},{"location":"api/basic_json/rend/#return-value","title":"Return value","text":"reverse iterator to the element following the last element
"},{"location":"api/basic_json/rend/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/rend/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/rend/#examples","title":"Examples","text":"ExampleThe following code shows an example for eend().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-end\n json::reverse_iterator it = array.rend();\n\n // increment the iterator to point to the first element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n Output:
1\n"},{"location":"api/basic_json/rend/#version-history","title":"Version history","text":"// (1)\ntemplate <typename InputType, typename SAX>\nstatic bool sax_parse(InputType&& i,\n SAX* sax,\n input_format_t format = input_format_t::json,\n const bool strict = true,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<class IteratorType, class SAX>\nstatic bool sax_parse(IteratorType first, IteratorType last,\n SAX* sax,\n input_format_t format = input_format_t::json,\n const bool strict = true,\n const bool ignore_comments = false);\n Read from input and generate SAX events
Read from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
The SAX event lister must follow the interface of json_sax.
InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType Description SAX Description"},{"location":"api/basic_json/sax_parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. sax (in) SAX event listener format (in) the format to parse (JSON, CBOR, MessagePack, or UBJSON) (optional, input_format_t::json by default), see input_format_t for more information strict (in) whether the input has to be consumed completely (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/sax_parse/#return-value","title":"Return value","text":"return value of the last processed SAX event
"},{"location":"api/basic_json/sax_parse/#exception-safety","title":"Exception safety","text":""},{"location":"api/basic_json/sax_parse/#complexity","title":"Complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.
A UTF-8 byte order mark is silently ignored.
"},{"location":"api/basic_json/sax_parse/#examples","title":"Examples","text":"ExampleThe example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/basic_json/sax_parse/#version-history","title":"Version history","text":"ignore_comments added in version 3.9.0.Deprecation
Overload (2) replaces calls to sax_parse with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like sax_parse({ptr, ptr+len}); with sax_parse(ptr, ptr+len);.
size_type size() const noexcept;\n Returns the number of elements in a JSON value.
"},{"location":"api/basic_json/size/#return-value","title":"Return value","text":"The return value depends on the different types and is defined as follows:
Value type return value null0 boolean 1 string 1 number 1 binary 1 object result of function object_t::size() array result of function array_t::size()"},{"location":"api/basic_json/size/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/size/#complexity","title":"Complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.
This function does not return the length of a string stored as JSON value -- it returns the number of elements in the JSON value which is 1 in the case of a string.
The following code calls size() on the different value types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call size()\n std::cout << j_null.size() << '\\n';\n std::cout << j_boolean.size() << '\\n';\n std::cout << j_number_integer.size() << '\\n';\n std::cout << j_number_float.size() << '\\n';\n std::cout << j_object.size() << '\\n';\n std::cout << j_object_empty.size() << '\\n';\n std::cout << j_array.size() << '\\n';\n std::cout << j_array_empty.size() << '\\n';\n std::cout << j_string.size() << '\\n';\n}\n Output:
0\n1\n1\n1\n2\n0\n5\n0\n1\n"},{"location":"api/basic_json/size/#version-history","title":"Version history","text":"1 for binary types in version 3.8.0.namespace std {\n struct hash<nlohmann::basic_json>;\n}\n Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.
The example shows how to calculate hash values for different JSON values.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n std::cout << \"hash(null) = \" << std::hash<json> {}(json(nullptr)) << '\\n'\n << \"hash(false) = \" << std::hash<json> {}(json(false)) << '\\n'\n << \"hash(0) = \" << std::hash<json> {}(json(0)) << '\\n'\n << \"hash(0U) = \" << std::hash<json> {}(json(0U)) << '\\n'\n << \"hash(\\\"\\\") = \" << std::hash<json> {}(json(\"\")) << '\\n'\n << \"hash({}) = \" << std::hash<json> {}(json::object()) << '\\n'\n << \"hash([]) = \" << std::hash<json> {}(json::array()) << '\\n'\n << \"hash({\\\"hello\\\": \\\"world\\\"}) = \" << std::hash<json> {}(\"{\\\"hello\\\": \\\"world\\\"}\"_json)\n << std::endl;\n}\n Output:
hash(null) = 2654435769\nhash(false) = 2654436030\nhash(0) = 2654436095\nhash(0U) = 2654436156\nhash(\"\") = 6142509191626859748\nhash({}) = 2654435832\nhash([]) = 2654435899\nhash({\"hello\": \"world\"}) = 4469488738203676328\n Note the output is platform-dependent.
"},{"location":"api/basic_json/std_hash/#version-history","title":"Version history","text":"namespace std {\n void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2);\n}\n Exchanges the values of two JSON objects.
"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2)\n{\n j1.swap(j2);\n}\n"},{"location":"api/basic_json/std_swap/#examples","title":"Examples","text":"Example The following code shows how two values are swapped with std::swap.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j1 = {{\"one\", 1}, {\"two\", 2}};\n json j2 = {1, 2, 4, 8, 16};\n\n std::cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n';\n\n // swap values\n std::swap(j1, j2);\n\n std::cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std::endl;\n}\n Output:
j1 = {\"one\":1,\"two\":2} | j2 = [1,2,4,8,16]\nj1 = [1,2,4,8,16] | j2 = {\"one\":1,\"two\":2}\n"},{"location":"api/basic_json/std_swap/#see-also","title":"See also","text":"using string_t = StringType;\n The type used to store JSON strings.
RFC 8259 describes JSON strings as follows:
A string is a sequence of zero or more Unicode characters.
To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.
"},{"location":"api/basic_json/string_t/#template-parameters","title":"Template parameters","text":"StringType the container to store strings (e.g., std::string). Note this container is used for keys/names in objects, see object_t."},{"location":"api/basic_json/string_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/string_t/#default-type","title":"Default type","text":"With the default values for StringType (std::string), the default value for string_t is std::string.
Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.
RFC 8259 states:
Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal.
This implementation is interoperable as it does compare strings code unit by code unit.
"},{"location":"api/basic_json/string_t/#storage","title":"Storage","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.
The following code shows that string_t is by default, a typedef to std::string.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::string, json::string_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/string_t/#version-history","title":"Version history","text":"// (1)\nvoid swap(reference other) noexcept;\n\n// (2)\nvoid swap(reference left, reference right) noexcept;\n\n// (3)\nvoid swap(array_t& other);\n\n// (4)\nvoid swap(object_t& other);\n\n// (5)\nvoid swap(string_t& other);\n\n// (6)\nvoid swap(binary_t& other);\n\n// (7)\nvoid swap(typename binary_t::container_type& other);\n other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. left with those of right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Implemented as a friend function callable via ADL.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike version (6), no binary subtype is involved.other (in, out) value to exchange the contents with left (in, out) value to exchange the contents with right (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"type_error.310 if called on JSON values other than arrays; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than objects; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than strings; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"Constant.
"},{"location":"api/basic_json/swap/#examples","title":"Examples","text":"Example: Swap JSON value (1, 2)The example below shows how JSON values can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create two JSON values\n json j1 = {1, 2, 3, 4, 5};\n json j2 = {{\"pi\", 3.141592653589793}, {\"e\", 2.718281828459045}};\n\n // swap the values\n j1.swap(j2);\n\n // output the values\n std::cout << \"j1 = \" << j1 << '\\n';\n std::cout << \"j2 = \" << j2 << '\\n';\n}\n Output:
j1 = {\"e\":2.718281828459045,\"pi\":3.141592653589793}\nj2 = [1,2,3,4,5]\n Example: Swap array (3) The example below shows how arrays can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = {{\"array\", {1, 2, 3, 4}}};\n\n // create an array_t\n json::array_t array = {\"Snap\", \"Crackle\", \"Pop\"};\n\n // swap the array stored in the JSON value\n value[\"array\"].swap(array);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"array = \" << array << '\\n';\n}\n Output:
value = {\"array\":[\"Snap\",\"Crackle\",\"Pop\"]}\narray = [1,2,3,4]\n Example: Swap object (4) The example below shows how objects can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { {\"translation\", {{\"one\", \"eins\"}, {\"two\", \"zwei\"}}} };\n\n // create an object_t\n json::object_t object = {{\"cow\", \"Kuh\"}, {\"dog\", \"Hund\"}};\n\n // swap the object stored in the JSON value\n value[\"translation\"].swap(object);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"object = \" << object << '\\n';\n}\n Output:
value = {\"translation\":{\"cow\":\"Kuh\",\"dog\":\"Hund\"}}\nobject = {\"one\":\"eins\",\"two\":\"zwei\"}\n Example: Swap string (5) The example below shows how strings can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { \"the good\", \"the bad\", \"the ugly\" };\n\n // create string_t\n json::string_t string = \"the fast\";\n\n // swap the object stored in the JSON value\n value[1].swap(string);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"string = \" << string << '\\n';\n}\n Output:
value = [\"the good\",\"the fast\",\"the ugly\"]\nstring = the bad\n Example: Swap string (6) The example below shows how binary values can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary value\n json value = json::binary({1, 2, 3});\n\n // create a binary_t\n json::binary_t binary = {{4, 5, 6}};\n\n // swap the object stored in the JSON value\n value.swap(binary);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"binary = \" << json(binary) << '\\n';\n}\n Output:
value = {\"bytes\":[4,5,6],\"subtype\":null}\nbinary = {\"bytes\":[1,2,3],\"subtype\":null}\n"},{"location":"api/basic_json/swap/#see-also","title":"See also","text":"// (1)\nstatic std::vector<std::uint8_t> to_bjdata(const basic_json& j,\n const bool use_size = false,\n const bool use_type = false);\n\n// (2)\nstatic void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,\n const bool use_size = false, const bool use_type = false);\nstatic void to_bjdata(const basic_json& j, detail::output_adapter<char> o,\n const bool use_size = false, const bool use_type = false);\n Serializes a given JSON value j to a byte vector using the BJData (Binary JData) serialization format. BJData aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_bjdata/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in BJData format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print BJData's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to BJData\n std::vector<std::uint8_t> v = json::to_bjdata(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to BJData using default representation\n std::vector<std::uint8_t> v_array = json::to_bjdata(array);\n // serialize it to BJData using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);\n // serialize it to BJData using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"api/basic_json/to_bjdata/#version-history","title":"Version history","text":"// (1)\nstatic std::vector<std::uint8_t> to_bson(const basic_json& j);\n\n// (2)\nstatic void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_bson(const basic_json& j, detail::output_adapter<char> o);\n BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document).
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_bson/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in BSON format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector<std::uint8_t> v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 \n"},{"location":"api/basic_json/to_bson/#version-history","title":"Version history","text":"// (1)\nstatic std::vector<std::uint8_t> to_cbor(const basic_json& j);\n\n// (2)\nstatic void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_cbor(const basic_json& j, detail::output_adapter<char> o);\n Serializes a given JSON value j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_cbor/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in CBOR format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to CBOR\n std::vector<std::uint8_t> v = json::to_cbor(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"api/basic_json/to_cbor/#version-history","title":"Version history","text":"// (1)\nstatic std::vector<std::uint8_t> to_msgpack(const basic_json& j);\n\n// (2)\nstatic void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_msgpack(const basic_json& j, detail::output_adapter<char> o);\n Serializes a given JSON value j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_msgpack/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in MessagePack format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"api/basic_json/to_msgpack/#version-history","title":"Version history","text":"template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j);\n This function implements a user-defined to_string for JSON objects.
"},{"location":"api/basic_json/to_string/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/basic_json/to_string/#return-value","title":"Return value","text":"string containing the serialization of the JSON value
"},{"location":"api/basic_json/to_string/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/to_string/#exceptions","title":"Exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded
Linear.
"},{"location":"api/basic_json/to_string/#possible-implementation","title":"Possible implementation","text":"template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j)\n{\n return j.dump();\n}\n"},{"location":"api/basic_json/to_string/#examples","title":"Examples","text":"Example The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing std::to_string;\n\nint main()\n{\n // create values\n json j = {{\"one\", 1}, {\"two\", 2}};\n int i = 42;\n\n // use ADL to select best to_string function\n auto j_str = to_string(j); // calling nlohmann::to_string\n auto i_str = to_string(i); // calling std::to_string\n\n // serialize without indentation\n std::cout << j_str << \"\\n\\n\"\n << i_str << std::endl;\n}\n Output:
{\"one\":1,\"two\":2}\n\n42\n"},{"location":"api/basic_json/to_string/#see-also","title":"See also","text":"Added in version 3.7.0.
"},{"location":"api/basic_json/to_ubjson/","title":"nlohmann::basic_json::to_ubjson","text":"// (1)\nstatic std::vector<std::uint8_t> to_ubjson(const basic_json& j,\n const bool use_size = false,\n const bool use_type = false);\n\n// (2)\nstatic void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,\n const bool use_size = false, const bool use_type = false);\nstatic void to_ubjson(const basic_json& j, detail::output_adapter<char> o,\n const bool use_size = false, const bool use_type = false);\n Serializes a given JSON value j to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_ubjson/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in UBJSON format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print UBJSON's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to UBJSON\n std::vector<std::uint8_t> v = json::to_ubjson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to UBJSON using default representation\n std::vector<std::uint8_t> v_array = json::to_ubjson(array);\n // serialize it to UBJSON using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);\n // serialize it to UBJSON using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"api/basic_json/to_ubjson/#version-history","title":"Version history","text":"constexpr value_t type() const noexcept;\n Return the type of the JSON value as a value from the value_t enumeration.
the type of the JSON value
Value type return valuenull value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/type/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/type/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/type/#examples","title":"Examples","text":"ExampleThe following code exemplifies type() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type()\n std::cout << std::boolalpha;\n std::cout << (j_null.type() == json::value_t::null) << '\\n';\n std::cout << (j_boolean.type() == json::value_t::boolean) << '\\n';\n std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\\n';\n std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\\n';\n std::cout << (j_number_float.type() == json::value_t::number_float) << '\\n';\n std::cout << (j_object.type() == json::value_t::object) << '\\n';\n std::cout << (j_array.type() == json::value_t::array) << '\\n';\n std::cout << (j_string.type() == json::value_t::string) << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n"},{"location":"api/basic_json/type/#version-history","title":"Version history","text":"class type_error : public exception;\n This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx (see list of type errors).
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_type_error fill:#CCCCFF"},{"location":"api/basic_json/type_error/#member-functions","title":"Member functions","text":"The following code shows how a type_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling push_back() on a string value\n json j = \"string\";\n j.push_back(\"another string\");\n }\n catch (const json::type_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n"},{"location":"api/basic_json/type_error/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorsout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsconst char* type_name() const noexcept;\n Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type.
"},{"location":"api/basic_json/type_name/#return-value","title":"Return value","text":"a string representation of the type (value_t):
null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\""},{"location":"api/basic_json/type_name/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/type_name/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/type_name/#examples","title":"Examples","text":"ExampleThe following code exemplifies type_name() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type_name()\n std::cout << j_null << \" is a \" << j_null.type_name() << '\\n';\n std::cout << j_boolean << \" is a \" << j_boolean.type_name() << '\\n';\n std::cout << j_number_integer << \" is a \" << j_number_integer.type_name() << '\\n';\n std::cout << j_number_unsigned << \" is a \" << j_number_unsigned.type_name() << '\\n';\n std::cout << j_number_float << \" is a \" << j_number_float.type_name() << '\\n';\n std::cout << j_object << \" is an \" << j_object.type_name() << '\\n';\n std::cout << j_array << \" is an \" << j_array.type_name() << '\\n';\n std::cout << j_string << \" is a \" << j_string.type_name() << '\\n';\n}\n Output:
null is a null\ntrue is a boolean\n-17 is a number\n42 is a number\n23.42 is a number\n{\"one\":1,\"two\":2} is an object\n[1,2,4,8,16] is an array\n\"Hello, world\" is a string\n"},{"location":"api/basic_json/type_name/#version-history","title":"Version history","text":"const char* and added noexcept in version 3.0.0.basic_json unflatten() const;\n The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints:
the original JSON from a flattened version
"},{"location":"api/basic_json/unflatten/#exception-safety","title":"Exception safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/unflatten/#exceptions","title":"Exceptions","text":"The function can throw the following exceptions:
type_error.314 if value is not an objecttype_error.315 if object values are not primitiveLinear in the size the JSON value.
"},{"location":"api/basic_json/unflatten/#notes","title":"Notes","text":"Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j, the following is always true: j == j.flatten().unflatten().
The following code shows how a flattened JSON object is unflattened into the original nested JSON object.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value\n json j_flattened =\n {\n {\"/answer/everything\", 42},\n {\"/happy\", true},\n {\"/list/0\", 1},\n {\"/list/1\", 0},\n {\"/list/2\", 2},\n {\"/name\", \"Niels\"},\n {\"/nothing\", nullptr},\n {\"/object/currency\", \"USD\"},\n {\"/object/value\", 42.99},\n {\"/pi\", 3.141}\n };\n\n // call unflatten()\n std::cout << std::setw(4) << j_flattened.unflatten() << '\\n';\n}\n Output:
{\n \"answer\": {\n \"everything\": 42\n },\n \"happy\": true,\n \"list\": [\n 1,\n 0,\n 2\n ],\n \"name\": \"Niels\",\n \"nothing\": null,\n \"object\": {\n \"currency\": \"USD\",\n \"value\": 42.99\n },\n \"pi\": 3.141\n}\n"},{"location":"api/basic_json/unflatten/#see-also","title":"See also","text":"// (1)\nvoid update(const_reference j, bool merge_objects = false);\n\n// (2)\nvoid update(const_iterator first, const_iterator last, bool merge_objects = false);\n j.[first, last)When merge_objects is false (default), existing keys are overwritten. When merge_objects is true, recursively merges objects with common keys.
The function is motivated by Python's dict.update function.
"},{"location":"api/basic_json/update/#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.
j (in) JSON object to read values from merge_objects (in) when true, existing keys are not overwritten, but contents of objects are merged recursively (default: false) first (in) begin of the range of elements to insert last (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"The example shows how update() is used.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create two JSON objects\n json o1 = R\"( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} )\"_json;\n json o2 = R\"( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} )\"_json;\n json o3 = o1;\n\n // add all keys from o2 to o1 (updating \"color\", replacing \"names\")\n o1.update(o2);\n\n // add all keys from o2 to o1 (updating \"color\", merging \"names\")\n o3.update(o2, true);\n\n // output updated object o1 and o3\n std::cout << std::setw(2) << o1 << '\\n';\n std::cout << std::setw(2) << o3 << '\\n';\n}\n Output:
{\n \"color\": \"blue\",\n \"names\": {\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n{\n \"color\": \"blue\",\n \"names\": {\n \"de\": \"Flugzeug\",\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n Example The example shows how update() is used.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create two JSON objects\n json o1 = R\"( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} )\"_json;\n json o2 = R\"( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} )\"_json;\n json o3 = o1;\n\n // add all keys from o2 to o1 (updating \"color\", replacing \"names\")\n o1.update(o2.begin(), o2.end());\n\n // add all keys from o2 to o1 (updating \"color\", merging \"names\")\n o3.update(o2.begin(), o2.end(), true);\n\n // output updated object o1 and o3\n std::cout << std::setw(2) << o1 << '\\n';\n std::cout << std::setw(2) << o3 << '\\n';\n}\n Output:
{\n \"color\": \"blue\",\n \"names\": {\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n{\n \"color\": \"blue\",\n \"names\": {\n \"de\": \"Flugzeug\",\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n Example One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects:
{\n \"color\": \"red\",\n \"active\": true,\n \"name\": {\"de\": \"Maus\", \"en\": \"mouse\"}\n}\n The user may override the default settings selectively:
{\n \"color\": \"blue\",\n \"name\": {\"es\": \"rat\u00f3n\"},\n}\n Then update manages the merging of default settings and user settings:
auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings);\n Now effective_settings contains the default settings, but those keys set by the user are overwritten:
{\n \"color\": \"blue\",\n \"active\": true,\n \"name\": {\"es\": \"rat\u00f3n\"}\n}\n Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true:
auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings, true);\n {\n \"color\": \"blue\",\n \"active\": true,\n \"name\": {\"de\": \"Maus\", \"en\": \"mouse\", \"es\": \"rat\u00f3n\"}\n}\n"},{"location":"api/basic_json/update/#version-history","title":"Version history","text":"merge_objects parameter in 3.10.5.// (1)\ntemplate<class ValueType>\nValueType value(const typename object_t::key_type& key,\n ValueType&& default_value) const;\n\n// (2)\ntemplate<class ValueType, class KeyType>\nValueType value(KeyType&& key,\n ValueType&& default_value) const;\n\n// (3)\ntemplate<class ValueType>\nValueType value(const json_pointer& ptr,\n const ValueType& default_value) const;\n Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.
The function is basically equivalent to executing
try {\n return at(key);\n} catch(out_of_range) {\n return default_value;\n}\n 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.
Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists.
The function is basically equivalent to executing
try {\n return at(ptr);\n} catch(out_of_range) {\n return default_value;\n}\n Differences to at and operator[]
at, this function does not throw if the given key/ptr was not found.operator[], this function does not implicitly add an element to the position defined by key/ptr key. This function is furthermore also applicable to const objects.KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17). ValueType type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"key (in) key of the element to access default_value (in) the value to return if key/ptr found no value ptr (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"key or default_value if key is not foundkey or default_value if key is not foundptr or default_value if no value for ptr is foundStrong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/value/#exceptions","title":"Exceptions","text":"type_error.302 if default_value does not match the type of the value at keytype_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.type_error.302 if default_value does not match the type of the value at ptrtype_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.The example below shows how object elements can be queried with a default value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"integer\", 0);\n double v_floating = j.value(\"floating\", 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"nonexisting\", \"oops\");\n bool v_boolean = j.value(\"nonexisting\", false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n Output:
1 42.23 oops false\n Example: (2) access specified object element using string_view with default value The example below shows how object elements can be queried with a default value.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"integer\"sv, 0);\n double v_floating = j.value(\"floating\"sv, 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"nonexisting\"sv, \"oops\");\n bool v_boolean = j.value(\"nonexisting\"sv, false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n Output:
1 42.23 oops false\n Example: (3) access specified object element via JSON Pointer with default value The example below shows how object elements can be queried with a default value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"/integer\"_json_pointer, 0);\n double v_floating = j.value(\"/floating\"_json_pointer, 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"/nonexisting\"_json_pointer, \"oops\");\n bool v_boolean = j.value(\"/nonexisting\"_json_pointer, false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n Output:
1 42.23 oops false\n"},{"location":"api/basic_json/value/#see-also","title":"See also","text":"at for access by reference with range checkingoperator[] for unchecked access by referencedefault_value type from const ValueType& to ValueType&& in version 3.11.0.ValueType the first template parameter in version 3.11.2.enum class value_t : std::uint8_t {\n null,\n object,\n array,\n string,\n boolean,\n number_integer,\n number_unsigned,\n number_float,\n binary,\n discarded\n};\n This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions is_null, is_object, is_array, is_string, is_boolean, is_number (with is_number_integer, is_number_unsigned, and is_number_float), is_discarded, is_binary, is_primitive, and is_structured rely on it.
Ordering
The order of types is as follows:
nullbooleannumber_integer, number_unsigned, number_floatobjectarraystringbinarydiscarded is unordered.
Types of numbers
There are three enumerators for numbers (number_integer, number_unsigned, and number_float) to distinguish between different types of numbers:
number_unsigned_t for unsigned integersnumber_integer_t for signed integersnumber_float_t for floating-point numbers or to approximate integers which do not fit into the limits of their respective typeComparison operators
operator< and operator<=> (since C++20) are overloaded and compare according to the ordering described above. Until C++20 all other relational and equality operators yield results according to the integer value of each enumerator. Since C++20 some compilers consider the rewritten candidates generated from operator<=> during overload resolution, while others do not. For predictable and portable behavior use:
operator< or operator<=> when wanting to compare according to the order described aboveoperator== or operator!= when wanting to compare according to each enumerators integer valueThe following code how type() queries the value_t for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type()\n std::cout << std::boolalpha;\n std::cout << (j_null.type() == json::value_t::null) << '\\n';\n std::cout << (j_boolean.type() == json::value_t::boolean) << '\\n';\n std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\\n';\n std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\\n';\n std::cout << (j_number_float.type() == json::value_t::number_float) << '\\n';\n std::cout << (j_object.type() == json::value_t::object) << '\\n';\n std::cout << (j_array.type() == json::value_t::array) << '\\n';\n std::cout << (j_string.type() == json::value_t::string) << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n"},{"location":"api/basic_json/value_t/#version-history","title":"Version history","text":"~basic_json() noexcept;\n Destroys the JSON value and frees all allocated memory.
"},{"location":"api/basic_json/~basic_json/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/~basic_json/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/~basic_json/#version-history","title":"Version history","text":"template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n This type extends the template parameter BinaryType provided to basic_json with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type.
BinaryType container to store bytes (std::vector<std::uint8_t> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":"BinaryType)std::uint64_t)std::uint64_t in 3.10.0.// (1)\nbyte_container_with_subtype();\n\n// (2)\nbyte_container_with_subtype(const container_type& container);\nbyte_container_with_subtype(container_type&& container);\n\n// (3)\nbyte_container_with_subtype(const container_type& container, subtype_type subtype);\nbyte_container_with_subtype(container_type&& container, subtype_type subtype);\n container (in) binary container subtype (in) subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","title":"Examples","text":"Example The example below demonstrates how byte containers can be created.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n // (1) create empty container\n auto c1 = byte_container_with_subtype();\n\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // (2) create container\n auto c2 = byte_container_with_subtype(bytes);\n\n // (3) create container with subtype\n auto c3 = byte_container_with_subtype(bytes, 42);\n\n std::cout << json(c1) << \"\\n\" << json(c2) << \"\\n\" << json(c3) << std::endl;\n}\n Output:
{\"bytes\":[],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":42}\n"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/clear_subtype/","title":"nlohmann::byte_container_with_subtype::clear_subtype","text":"void clear_subtype() noexcept;\n Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for instance MessagePack will prefer the bin family over the ext family.
"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how clear_subtype can remove subtypes.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container with subtype\n auto c1 = byte_container_with_subtype(bytes, 42);\n\n std::cout << \"before calling clear_subtype(): \" << json(c1) << '\\n';\n\n c1.clear_subtype();\n\n std::cout << \"after calling clear_subtype(): \" << json(c1) << '\\n';\n}\n Output:
before calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":42}\nafter calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":null}\n"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/has_subtype/","title":"nlohmann::byte_container_with_subtype::has_subtype","text":"constexpr bool has_subtype() const noexcept;\n Returns whether the value has a subtype.
"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","title":"Return value","text":"whether the value has a subtype
"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how has_subtype can check whether a subtype was set.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container\n auto c1 = byte_container_with_subtype(bytes);\n\n // create container with subtype\n auto c2 = byte_container_with_subtype(bytes, 42);\n\n std::cout << std::boolalpha << \"c1.has_subtype() = \" << c1.has_subtype()\n << \"\\nc2.has_subtype() = \" << c2.has_subtype() << std::endl;\n}\n Output:
c1.has_subtype() = false\nc2.has_subtype() = true\n"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/set_subtype/","title":"nlohmann::byte_container_with_subtype::set_subtype","text":"void set_subtype(subtype_type subtype) noexcept;\n Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.
"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","title":"Parameters","text":"subtype (in) subtype to set"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how a subtype can be set with set_subtype.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container without subtype\n auto c = byte_container_with_subtype(bytes);\n\n std::cout << \"before calling set_subtype(42): \" << json(c) << '\\n';\n\n // set the subtype\n c.set_subtype(42);\n\n std::cout << \"after calling set_subtype(42): \" << json(c) << '\\n';\n}\n Output:
before calling set_subtype(42): {\"bytes\":[202,254,186,190],\"subtype\":null}\nafter calling set_subtype(42): {\"bytes\":[202,254,186,190],\"subtype\":42}\n"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/subtype/","title":"nlohmann::byte_container_with_subtype::subtype","text":"constexpr subtype_type subtype() const noexcept;\n Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return subtype_type(-1) as a sentinel value.
the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how the subtype can be retrieved with subtype. Note how subtype_type(-1) is returned for container c1.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container\n auto c1 = byte_container_with_subtype(bytes);\n\n // create container with subtype\n auto c2 = byte_container_with_subtype(bytes, 42);\n\n std::cout << \"c1.subtype() = \" << c1.subtype()\n << \"\\nc2.subtype() = \" << c2.subtype() << std::endl;\n\n // in case no subtype is set, return special value\n assert(c1.subtype() == static_cast<byte_container_with_subtype::subtype_type>(-1));\n}\n Output:
c1.subtype() = 18446744073709551615\nc2.subtype() = 42\n"},{"location":"api/byte_container_with_subtype/subtype/#version-history","title":"Version history","text":"subtype_type(-1) as documented in version 3.10.0.template<typename RefStringType>\nclass json_pointer;\n A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.
RefStringType the string type used for the reference tokens making up the JSON pointer Deprecation
For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.
basic_json to string type in version 3.11.0.const string_t& back() const;\n Return last reference token.
"},{"location":"api/json_pointer/back/#return-value","title":"Return value","text":"Last reference token.
"},{"location":"api/json_pointer/back/#exceptions","title":"Exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.
"},{"location":"api/json_pointer/back/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/json_pointer/back/#examples","title":"Examples","text":"ExampleThe example shows the usage of back.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo\");\n json::json_pointer ptr2(\"/foo/0\");\n\n // call empty()\n std::cout << \"last reference token of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.back() << \"\\\"\\n\"\n << \"last reference token of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.back() << \"\\\"\" << std::endl;\n}\n Output:
last reference token of \"/foo\" is \"foo\"\nlast reference token of \"/foo/0\" is \"0\"\n"},{"location":"api/json_pointer/back/#version-history","title":"Version history","text":"string_t in version 3.11.0.bool empty() const noexcept;\n Return whether pointer points to the root document.
"},{"location":"api/json_pointer/empty/#return-value","title":"Return value","text":"true iff the JSON pointer points to the root document.
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/json_pointer/empty/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/json_pointer/empty/#examples","title":"Examples","text":"ExampleThe example shows the result of empty for different JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n\n // call empty()\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\": \" << ptr0.empty() << '\\n'\n << \"\\\"\" << ptr1 << \"\\\": \" << ptr1.empty() << '\\n'\n << \"\\\"\" << ptr2 << \"\\\": \" << ptr2.empty() << '\\n'\n << \"\\\"\" << ptr3 << \"\\\": \" << ptr3.empty() << std::endl;\n}\n Output:
\"\": true\n\"\": true\n\"/foo\": false\n\"/foo/0\": false\n"},{"location":"api/json_pointer/empty/#version-history","title":"Version history","text":"Added in version 3.6.0.
"},{"location":"api/json_pointer/json_pointer/","title":"nlohmann::json_pointer::json_pointer","text":"explicit json_pointer(const string_t& s = \"\");\n Create a JSON pointer according to the syntax described in Section 3 of RFC6901.
"},{"location":"api/json_pointer/json_pointer/#parameters","title":"Parameters","text":"s (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value"},{"location":"api/json_pointer/json_pointer/#exceptions","title":"Exceptions","text":"s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.The example shows the construction several valid JSON pointers as well as the exceptional behavior.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // correct JSON pointers\n json::json_pointer p1;\n json::json_pointer p2(\"\");\n json::json_pointer p3(\"/\");\n json::json_pointer p4(\"//\");\n json::json_pointer p5(\"/foo/bar\");\n json::json_pointer p6(\"/foo/bar/-\");\n json::json_pointer p7(\"/foo/~0\");\n json::json_pointer p8(\"/foo/~1\");\n\n // error: JSON pointer does not begin with a slash\n try\n {\n json::json_pointer p9(\"foo\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // error: JSON pointer uses escape symbol ~ not followed by 0 or 1\n try\n {\n json::json_pointer p10(\"/foo/~\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // error: JSON pointer uses escape symbol ~ not followed by 0 or 1\n try\n {\n json::json_pointer p11(\"/foo/~3\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n"},{"location":"api/json_pointer/json_pointer/#version-history","title":"Version history","text":"s to string_t in version 3.11.0.// until C++20\ntemplate<typename RefStringTypeLhs, typename RefStringTypeRhs>\nbool operator==(\n const json_pointer<RefStringTypeLhs>& lhs,\n const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)\n\ntemplate<typename RefStringTypeLhs, typename StringType>\nbool operator==(\n const json_pointer<RefStringTypeLhs>& lhs,\n const StringType& rhs); // (2)\n\ntemplate<typename RefStringTypeRhs, typename StringType>\nbool operator==(\n const StringType& lhs,\n const json_pointer<RefStringTypeRhs>& rhs); // (2)\n\n// since C++20\nclass json_pointer {\n template<typename RefStringTypeRhs>\n bool operator==(\n const json_pointer<RefStringTypeRhs>& rhs) const noexcept; // (1)\n\n bool operator==(const string_t& rhs) const; // (2)\n};\n Compares two JSON pointers for equality by comparing their reference tokens.
Compares a JSON pointer and a string or a string and a JSON pointer for equality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.
RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are equal
s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.
Deprecation
Overload 2 is deprecated and will be removed in a future major version release.
"},{"location":"api/json_pointer/operator_eq/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointersThe example demonstrates comparing JSON pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // compare JSON pointers\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << ptr0 << \"\\\": \" << (ptr0 == ptr0) << '\\n'\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << ptr1 << \"\\\": \" << (ptr0 == ptr1) << '\\n'\n << \"\\\"\" << ptr1 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (ptr1 == ptr2) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (ptr2 == ptr2) << std::endl;\n}\n Output:
\"\" == \"\": true\n\"\" == \"\": true\n\"\" == \"/foo\": false\n\"/foo\" == \"/foo\": true\n Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.
#include <exception>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // different strings\n std::string str0(\"\");\n std::string str1(\"/foo\");\n std::string str2(\"bar\");\n\n // compare JSON pointers and strings\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << str0 << \"\\\": \" << (ptr0 == str0) << '\\n'\n << \"\\\"\" << str0 << \"\\\" == \\\"\" << ptr1 << \"\\\": \" << (str0 == ptr1) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" == \\\"\" << str1 << \"\\\": \" << (ptr2 == str1) << std::endl;\n\n try\n {\n std::cout << \"\\\"\" << str2 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (str2 == ptr2) << std::endl;\n }\n catch (const json::parse_error& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n}\n Output:
\"\" == \"\": true\n\"\" == \"\": true\n\"/foo\" == \"/foo\": true\n\"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'\n"},{"location":"api/json_pointer/operator_eq/#version-history","title":"Version history","text":"// until C++20\ntemplate<typename RefStringTypeLhs, typename RefStringTypeRhs>\nbool operator!=(\n const json_pointer<RefStringTypeLhs>& lhs,\n const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)\n\ntemplate<typename RefStringTypeLhs, typename StringType>\nbool operator!=(\n const json_pointer<RefStringTypeLhs>& lhs,\n const StringType& rhs); // (2)\n\ntemplate<typename RefStringTypeRhs, typename StringType>\nbool operator!=(\n const StringType& lhs,\n const json_pointer<RefStringTypeRhs>& rhs); // (2)\n Compares two JSON pointers for inequality by comparing their reference tokens.
Compares a JSON pointer and a string or a string and a JSON pointer for inequality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.
RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are not equal
s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator==.
Deprecation
Overload 2 is deprecated and will be removed in a future major version release.
"},{"location":"api/json_pointer/operator_ne/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointersThe example demonstrates comparing JSON pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // compare JSON pointers\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << ptr0 << \"\\\": \" << (ptr0 != ptr0) << '\\n'\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << ptr1 << \"\\\": \" << (ptr0 != ptr1) << '\\n'\n << \"\\\"\" << ptr1 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (ptr1 != ptr2) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (ptr2 != ptr2) << std::endl;\n}\n Output:
\"\" != \"\": false\n\"\" != \"\": false\n\"\" != \"/foo\": true\n\"/foo\" != \"/foo\": false\n Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // different strings\n std::string str0(\"\");\n std::string str1(\"/foo\");\n std::string str2(\"bar\");\n\n // compare JSON pointers and strings\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << str0 << \"\\\": \" << (ptr0 != str0) << '\\n'\n << \"\\\"\" << str0 << \"\\\" != \\\"\" << ptr1 << \"\\\": \" << (str0 != ptr1) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" != \\\"\" << str1 << \"\\\": \" << (ptr2 != str1) << std::endl;\n\n try\n {\n std::cout << \"\\\"\" << str2 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (str2 != ptr2) << std::endl;\n }\n catch (const json::parse_error& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n}\n Output:
\"\" != \"\": false\n\"\" != \"\": false\n\"/foo\" != \"/foo\": false\n\"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'\n"},{"location":"api/json_pointer/operator_ne/#version-history","title":"Version history","text":"// (1)\njson_pointer operator/(const json_pointer& lhs, const json_pointer& rhs);\n\n// (2)\njson_pointer operator/(const json_pointer& lhs, string_t token);\n\n// (3)\njson_pointer operator/(const json_pointer& lhs, std::size_t array_idx);\n lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slash/#return-value","title":"Return value","text":"rhs appended to lhstoken appended to lhsarray_idx appended to lhslhs and rhs.lhs.lhs.The example shows the usage of operator/.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON pointer\n json::json_pointer ptr(\"/foo\");\n\n // append a JSON Pointer\n std::cout << \"\\\"\" << ptr / json::json_pointer(\"/bar/baz\") << \"\\\"\\n\";\n\n // append a string\n std::cout << \"\\\"\" << ptr / \"fob\" << \"\\\"\\n\";\n\n // append an array index\n std::cout << \"\\\"\" << ptr / 42 << \"\\\"\" << std::endl;\n}\n Output:
\"/foo/bar/baz\"\n\"/foo/fob\"\n\"/foo/42\"\n"},{"location":"api/json_pointer/operator_slash/#version-history","title":"Version history","text":"token to string_t in version 3.11.0.// (1)\njson_pointer& operator/=(const json_pointer& ptr);\n\n// (2)\njson_pointer& operator/=(string_t token);\n\n// (3)\njson_pointer& operator/=(std::size_t array_idx)\n ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"ptr appendedtoken appended without escaping tokenarray_idx appendedptr.The example shows the usage of operator/=.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON pointer\n json::json_pointer ptr(\"/foo\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append a JSON Pointer\n ptr /= json::json_pointer(\"/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append a string\n ptr /= \"fob\";\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append an array index\n ptr /= 42;\n std::cout << \"\\\"\" << ptr << \"\\\"\" << std::endl;\n}\n Output:
\"/foo\"\n\"/foo/bar/baz\"\n\"/foo/bar/baz/fob\"\n\"/foo/bar/baz/fob/42\"\n"},{"location":"api/json_pointer/operator_slasheq/#version-history","title":"Version history","text":"token to string_t in version 3.11.0.operator string_t() const\n Return a string representation of the JSON pointer.
"},{"location":"api/json_pointer/operator_string_t/#return-value","title":"Return value","text":"A string representation of the JSON pointer
"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","title":"Possible implementation","text":"operator string_t() const\n{\n return to_string();\n}\n"},{"location":"api/json_pointer/operator_string_t/#notes","title":"Notes","text":"Deprecation
This function is deprecated in favor of to_string and will be removed in a future major version release.
The example shows how JSON Pointers can be implicitly converted to strings.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo/0\");\n json::json_pointer ptr2(\"/a~1b\");\n\n // implicit conversion to string\n std::string s;\n s += ptr1;\n s += \"\\n\";\n s += ptr2;\n\n std::cout << s << std::endl;\n}\n Output:
/foo/0\n/a~1b\n"},{"location":"api/json_pointer/operator_string_t/#version-history","title":"Version history","text":"string_t and deprecated in version 3.11.0.json_pointer parent_pointer() const;\n Returns the parent of this JSON pointer.
"},{"location":"api/json_pointer/parent_pointer/#return-value","title":"Return value","text":"Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.
"},{"location":"api/json_pointer/parent_pointer/#complexity","title":"Complexity","text":"Linear in the length of the JSON pointer.
"},{"location":"api/json_pointer/parent_pointer/#examples","title":"Examples","text":"ExampleThe example shows the result of parent_pointer for different JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n\n // call parent_pointer()\n std::cout << std::boolalpha\n << \"parent of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.parent_pointer() << \"\\\"\\n\"\n << \"parent of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.parent_pointer() << \"\\\"\\n\"\n << \"parent of \\\"\" << ptr3 << \"\\\" is \\\"\" << ptr3.parent_pointer() << \"\\\"\" << std::endl;\n}\n Output:
parent of \"\" is \"\"\nparent of \"/foo\" is \"\"\nparent of \"/foo/0\" is \"/foo\"\n"},{"location":"api/json_pointer/parent_pointer/#version-history","title":"Version history","text":"Added in version 3.6.0.
"},{"location":"api/json_pointer/pop_back/","title":"nlohmann::json_pointer::pop_back","text":"void pop_back();\n Remove last reference token.
"},{"location":"api/json_pointer/pop_back/#exceptions","title":"Exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.
"},{"location":"api/json_pointer/pop_back/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/json_pointer/pop_back/#examples","title":"Examples","text":"ExampleThe example shows the usage of pop_back.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr(\"/foo/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call pop_back()\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}\n Output:
\"/foo/bar/baz\"\n\"/foo/bar\"\n\"/foo\"\n\"\"\n"},{"location":"api/json_pointer/pop_back/#version-history","title":"Version history","text":"Added in version 3.6.0.
"},{"location":"api/json_pointer/push_back/","title":"nlohmann::json_pointer::push_back","text":"void push_back(const string_t& token);\n\nvoid push_back(string_t&& token);\n Append an unescaped token at the end of the reference pointer.
"},{"location":"api/json_pointer/push_back/#parameters","title":"Parameters","text":"token (in) token to add"},{"location":"api/json_pointer/push_back/#complexity","title":"Complexity","text":"Amortized constant.
"},{"location":"api/json_pointer/push_back/#examples","title":"Examples","text":"ExampleThe example shows the result of push_back for different JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr;\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call push_back()\n ptr.push_back(\"foo\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.push_back(\"0\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.push_back(\"bar\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}\n Output:
\"\"\n\"/foo\"\n\"/foo/0\"\n\"/foo/0/bar\"\n"},{"location":"api/json_pointer/push_back/#version-history","title":"Version history","text":"token to string_t in version 3.11.0.using string_t = RefStringType;\n The string type used for the reference tokens making up the JSON pointer.
See basic_json::string_t for more information.
The example shows the type string_t and its relation to basic_json::string_t.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::json_pointer::string_t s = \"This is a string.\";\n\n std::cout << s << std::endl;\n\n std::cout << std::boolalpha << std::is_same<json::json_pointer::string_t, json::string_t>::value << std::endl;\n}\n Output:
This is a string.\ntrue\n"},{"location":"api/json_pointer/string_t/#version-history","title":"Version history","text":"string_t to_string() const;\n Return a string representation of the JSON pointer.
"},{"location":"api/json_pointer/to_string/#return-value","title":"Return value","text":"A string representation of the JSON pointer
"},{"location":"api/json_pointer/to_string/#notes","title":"Notes","text":"For each JSON pointer ptr, it holds:
ptr == json_pointer(ptr.to_string());\n"},{"location":"api/json_pointer/to_string/#examples","title":"Examples","text":"Example The example shows the result of to_string.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n json::json_pointer ptr4(\"/\");\n json::json_pointer ptr5(\"/a~1b\");\n json::json_pointer ptr6(\"/c%d\");\n json::json_pointer ptr7(\"/e^f\");\n json::json_pointer ptr8(\"/g|h\");\n json::json_pointer ptr9(\"/i\\\\j\");\n json::json_pointer ptr10(\"/k\\\"l\");\n json::json_pointer ptr11(\"/ \");\n json::json_pointer ptr12(\"/m~0n\");\n\n std::cout << \"\\\"\" << ptr1.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr2.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr3.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr4.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr5.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr6.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr7.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr8.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr9.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr10.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr11.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr12.to_string() << \"\\\"\" << std::endl;\n}\n Output:
\"\"\n\"/foo\"\n\"/foo/0\"\n\"/\"\n\"/a~1b\"\n\"/c%d\"\n\"/e^f\"\n\"/g|h\"\n\"/i\\j\"\n\"/k\"l\"\n\"/ \"\n\"/m~0n\"\n"},{"location":"api/json_pointer/to_string/#version-history","title":"Version history","text":"string_t in version 3.11.0.template<typename BasicJsonType>\nstruct json_sax;\n This class describes the SAX interface used by sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input.
"},{"location":"api/json_sax/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/json_sax/#member-types","title":"Member types","text":"BasicJsonType's type for numbers (integer)BasicJsonType's type for numbers (unsigned)BasicJsonType's type for numbers (floating-point)BasicJsonType's type for stringsBasicJsonType's type for binary arraysbinary_t, binary) added in version 3.8.0.virtual bool binary(binary_t& val) = 0;\n A binary value was read.
"},{"location":"api/json_sax/binary/#parameters","title":"Parameters","text":"val (in) binary value"},{"location":"api/json_sax/binary/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/binary/#notes","title":"Notes","text":"It is safe to move the passed binary value.
"},{"location":"api/json_sax/binary/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // CBOR byte string\n std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse CBOR\n bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
binary(val=[...])\n\nresult: true\n"},{"location":"api/json_sax/binary/#version-history","title":"Version history","text":"virtual bool boolean(bool val) = 0;\n A boolean value was read.
"},{"location":"api/json_sax/boolean/#parameters","title":"Parameters","text":"val (in) boolean value"},{"location":"api/json_sax/boolean/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/boolean/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/boolean/#version-history","title":"Version history","text":"virtual bool end_array() = 0;\n The end of an array was read.
"},{"location":"api/json_sax/end_array/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/end_array/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/end_array/#version-history","title":"Version history","text":"virtual bool end_object() = 0;\n The end of an object was read.
"},{"location":"api/json_sax/end_object/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/end_object/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/end_object/#version-history","title":"Version history","text":"virtual bool key(string_t& val) = 0;\n An object key was read.
"},{"location":"api/json_sax/key/#parameters","title":"Parameters","text":"val (in) object key"},{"location":"api/json_sax/key/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/key/#notes","title":"Notes","text":"It is safe to move the passed object key value.
"},{"location":"api/json_sax/key/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/key/#version-history","title":"Version history","text":"virtual bool null() = 0;\n A null value was read.
"},{"location":"api/json_sax/null/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/null/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/null/#version-history","title":"Version history","text":"virtual bool number_float(number_float_t val, const string_t& s) = 0;\n A floating-point number was read.
"},{"location":"api/json_sax/number_float/#parameters","title":"Parameters","text":"val (in) floating-point value s (in) string representation of the original input"},{"location":"api/json_sax/number_float/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/number_float/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/number_float/#version-history","title":"Version history","text":"virtual bool number_integer(number_integer_t val) = 0;\n An integer number was read.
"},{"location":"api/json_sax/number_integer/#parameters","title":"Parameters","text":"val (in) integer value"},{"location":"api/json_sax/number_integer/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/number_integer/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/number_integer/#version-history","title":"Version history","text":"virtual bool number_unsigned(number_unsigned_t val) = 0;\n An unsigned integer number was read.
"},{"location":"api/json_sax/number_unsigned/#parameters","title":"Parameters","text":"val (in) unsigned integer value"},{"location":"api/json_sax/number_unsigned/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/number_unsigned/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/number_unsigned/#version-history","title":"Version history","text":"virtual bool parse_error(std::size_t position,\n const std::string& last_token,\n const detail::exception& ex) = 0;\n A parse error occurred.
"},{"location":"api/json_sax/parse_error/#parameters","title":"Parameters","text":"position (in) the position in the input where the error occurs last_token (in) the last read token ex (in) an exception object describing the error"},{"location":"api/json_sax/parse_error/#return-value","title":"Return value","text":"Whether parsing should proceed (must return false).
The example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/parse_error/#version-history","title":"Version history","text":"virtual bool start_array(std::size_t elements) = 0;\n The beginning of an array was read.
"},{"location":"api/json_sax/start_array/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_array/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/start_array/#notes","title":"Notes","text":"Binary formats may report the number of elements.
"},{"location":"api/json_sax/start_array/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/start_array/#version-history","title":"Version history","text":"virtual bool start_object(std::size_t elements) = 0;\n The beginning of an object was read.
"},{"location":"api/json_sax/start_object/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_object/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/start_object/#notes","title":"Notes","text":"Binary formats may report the number of elements.
"},{"location":"api/json_sax/start_object/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/start_object/#version-history","title":"Version history","text":"virtual bool string(string_t& val) = 0;\n A string value was read.
"},{"location":"api/json_sax/string/#parameters","title":"Parameters","text":"val (in) string value"},{"location":"api/json_sax/string/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/string/#notes","title":"Notes","text":"It is safe to move the passed string value.
"},{"location":"api/json_sax/string/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/string/#version-history","title":"Version history","text":"Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page.
std::filesystem supportstd::ranges supportnlohmann namespaceClass/struct:
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZENLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULTNLOHMANN_DEFINE_TYPE_INTRUSIVENLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZENLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULTNLOHMANN_DEFINE_TYPE_NON_INTRUSIVENLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) - serialization/deserialization of types with access to private variables
#define JSON_ASSERT(x) /* value */\n This macro controls which code is executed for runtime assertions of the library.
"},{"location":"api/macros/json_assert/#parameters","title":"Parameters","text":"x (in) expression of scalar type"},{"location":"api/macros/json_assert/#default-definition","title":"Default definition","text":"The default value is assert(x).
#define JSON_ASSERT(x) assert(x)\n Therefore, assertions can be switched off by defining NDEBUG.
const object). See page runtime assertions for more information.std::abort may leave the library in an undefined state.The following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n Example 2: user-defined behavior The assertion reporting can be changed by defining JSON_ASSERT(x) differently.
#include <cstdio>\n#include <cstdlib>\n#define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();}\n\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n Output:
assertion error in operator[]\n"},{"location":"api/macros/json_assert/#version-history","title":"Version history","text":"#define JSON_DIAGNOSTICS /* value */\n This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).
When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.
"},{"location":"api/macros/json_diagnostics/#default-definition","title":"Default definition","text":"The default value is 0 (extended diagnostics are switched off).
#define JSON_DIAGNOSTICS 0\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_diagnostics/#notes","title":"Notes","text":"ABI compatibility
As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names.
This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior.
Where possible, it is still recommended that all code define this the same way for maximum interoperability.
CMake option
Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which defines JSON_DIAGNOSTICS accordingly.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] type must be number, but is string\n This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.
#include <iostream>\n\n# define JSON_DIAGNOSTICS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.
#define JSON_DISABLE_ENUM_SERIALIZATION /* value */\n When defined to 1, default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details).
Parsing or serializing an enum will result in a compiler error.
This works for both unscoped and scoped enums.
"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","title":"Default definition","text":"The default value is 0.
#define JSON_DISABLE_ENUM_SERIALIZATION 0\n"},{"location":"api/macros/json_disable_enum_serialization/#notes","title":"Notes","text":"CMake option
Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization (OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.
The code below forces the library not to create default serialization/deserialization functions from_json and to_json, meaning the code below does not compile.
#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nint main()\n{\n // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not\n const json j = Choice::first; \n\n // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not\n Choice ch = j.template get<Choice>();\n}\n Example 2: Serialize enum macro The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses NLOHMANN_JSON_SERIALIZE_ENUM to parse and serialize the enum.
#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Choice,\n{\n { Choice::first, \"first\" },\n { Choice::second, \"second\" },\n})\n\nint main()\n{\n // uses user-defined to_json function defined by macro\n const json j = Choice::first; \n\n // uses user-defined from_json function defined by macro\n Choice ch = j.template get<Choice>();\n}\n Example 3: User-defined serialization/deserialization functions The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses user-defined functions to parse and serialize the enum.
#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nvoid from_json(const json& j, Choice& ch)\n{\n auto value = j.template get<std::string>();\n if (value == \"first\")\n {\n ch = Choice::first;\n }\n else if (value == \"second\")\n {\n ch = Choice::second;\n }\n}\n\nvoid to_json(json& j, const Choice& ch)\n{\n auto value = j.template get<std::string>();\n if (value == \"first\")\n {\n ch = Choice::first;\n }\n else if (value == \"second\")\n {\n ch = Choice::second;\n }\n}\n\nint main()\n{\n // uses user-defined to_json function\n const json j = Choice::first; \n\n // uses user-defined from_json function\n Choice ch = j.template get<Choice>();\n}\n"},{"location":"api/macros/json_disable_enum_serialization/#see-also","title":"See also","text":"NLOHMANN_JSON_SERIALIZE_ENUM#define JSON_HAS_CPP_11\n#define JSON_HAS_CPP_14\n#define JSON_HAS_CPP_17\n#define JSON_HAS_CPP_20\n The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.
The default value is detected based on preprocessor macros such as __cplusplus, _HAS_CXX17, or _MSVC_LANG.
JSON_HAS_CPP_11 is always defined.The code below forces the library to use the C++14 standard:
#define JSON_HAS_CPP_14 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_cpp_11/#version-history","title":"Version history","text":"#define JSON_HAS_FILESYSTEM /* value */\n#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */\n When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.
The default value is detected based on the preprocessor macros __cpp_lib_filesystem, __cpp_lib_experimental_filesystem, __has_include(<filesystem>), or __has_include(<experimental/filesystem>).
stdc++fs to be linked to for filesystem support.The code below forces the library to use the header <experimental/filesystem>.
#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_filesystem/#version-history","title":"Version history","text":"#define JSON_HAS_RANGES /* value */\n This macro indicates whether the standard library has any support for ranges. Implies support for concepts. Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macro __cpp_lib_ranges.
When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_has_ranges/#examples","title":"Examples","text":"ExampleThe code below forces the library to enable support for ranges:
#define JSON_HAS_RANGES 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_ranges/#version-history","title":"Version history","text":"#define JSON_HAS_STATIC_RTTI /* value */\n This macro indicates whether the standard library has any support for RTTI (run time type information). Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI.
When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_has_static_rtti/#examples","title":"Examples","text":"ExampleThe code below forces the library to enable support for libraries with RTTI dependence:
#define JSON_HAS_STATIC_RTTI 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_static_rtti/#version-history","title":"Version history","text":"#define JSON_HAS_THREE_WAY_COMPARISON /* value */\n This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison.
When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_has_three_way_comparison/#examples","title":"Examples","text":"ExampleThe code below forces the library to use 3-way comparison:
#define JSON_HAS_THREE_WAY_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_three_way_comparison/#version-history","title":"Version history","text":"#define JSON_NO_IO\n When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> are not included and parse functions relying on these headers are excluded. This is relevant for environments where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).
By default, JSON_NO_IO is not defined.
#undef JSON_NO_IO\n"},{"location":"api/macros/json_no_io/#examples","title":"Examples","text":"Example The code below forces the library not to use the headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream>.
#define JSON_NO_IO 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_no_io/#version-history","title":"Version history","text":"#define JSON_NOEXCEPTION\n Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION. When defining JSON_NOEXCEPTION, try is replaced by if (true), catch is replaced by if (false), and throw is replaced by std::abort().
The same effect is achieved by setting the compiler flag -fno-exceptions.
By default, the macro is not defined.
#undef JSON_NOEXCEPTION\n"},{"location":"api/macros/json_noexception/#notes","title":"Notes","text":"The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
The code below switches off exceptions in the library.
#define JSON_NOEXCEPTION 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_noexception/#see-also","title":"See also","text":"Added in version 2.1.0.
"},{"location":"api/macros/json_skip_library_version_check/","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"#define JSON_SKIP_LIBRARY_VERSION_CHECK\n When defined, the library will not create a compiler warning when a different version of the library was already included.
"},{"location":"api/macros/json_skip_library_version_check/#default-definition","title":"Default definition","text":"By default, the macro is not defined.
#undef JSON_SKIP_LIBRARY_VERSION_CHECK\n"},{"location":"api/macros/json_skip_library_version_check/#notes","title":"Notes","text":"ABI compatibility
Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.
"},{"location":"api/macros/json_skip_library_version_check/#examples","title":"Examples","text":"Example
The following warning will be shown in case a different version of the library was already included:
Already included a different version of the library!\n"},{"location":"api/macros/json_skip_library_version_check/#version-history","title":"Version history","text":"Added in version 3.11.0.
"},{"location":"api/macros/json_skip_unsupported_compiler_check/","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","title":"Default definition","text":"By default, the macro is not defined.
#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","title":"Examples","text":"Example The code below switches off the check whether the compiler is supported.
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","title":"Version history","text":"Added in version 3.2.0.
"},{"location":"api/macros/json_throw_user/","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER","text":"// (1)\n#define JSON_CATCH_USER(exception) /* value */\n// (2)\n#define JSON_THROW_USER(exception) /* value */\n// (3)\n#define JSON_TRY_USER /* value */\n Controls how exceptions are handled by the library.
catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.try calls inside the library. It has no arguments and is always followed by a scope.exception (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"By default, the macros map to their respective C++ keywords:
#define JSON_CATCH_USER(exception) catch(exception)\n#define JSON_THROW_USER(exception) throw exception\n#define JSON_TRY_USER try\n When exceptions are switched off, the try block is executed unconditionally, and throwing exceptions is replaced by calling std::abort to make reaching the throw branch abort the process.
#define JSON_THROW_USER(exception) std::abort()\n#define JSON_TRY_USER if (true)\n#define JSON_CATCH_USER(exception) if (false)\n"},{"location":"api/macros/json_throw_user/#examples","title":"Examples","text":"Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>\n\n#define JSON_TRY_USER if(true)\n#define JSON_CATCH_USER(exception) if(false)\n#define JSON_THROW_USER(exception) \\\n {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\\n << \" (function \" << __FUNCTION__ << \") - \" \\\n << (exception).what() << std::endl; \\\n std::abort();}\n\n#include <nlohmann/json.hpp>\n"},{"location":"api/macros/json_throw_user/#see-also","title":"See also","text":"#define JSON_USE_GLOBAL_UDLS /* value */\n When defined to 1, the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals.
The default value is 1.
#define JSON_USE_GLOBAL_UDLS 1\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_use_global_udls/#notes","title":"Notes","text":"Future behavior change
The user-defined string literals will be removed from the global namespace in the next major release of the library.
To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details.
CMake option
The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs (ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.
The code below shows the default behavior using the _json UDL.
#include <nlohmann/json.hpp>\n\n#include <iostream>\n\nint main()\n{\n auto j = \"42\"_json;\n\n std::cout << j << std::endl;\n}\n Output:
42\n Example 2: Namespaced UDLs The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0.
#define JSON_USE_GLOBAL_UDLS 0\n#include <nlohmann/json.hpp>\n\n#include <iostream>\n\nint main()\n{\n // auto j = \"42\"_json; // This line would fail to compile,\n // because the UDLs are not in the global namespace\n\n // Bring the UDLs into scope\n using namespace nlohmann::json_literals;\n\n auto j = \"42\"_json;\n\n std::cout << j << std::endl;\n}\n Output:
42\n"},{"location":"api/macros/json_use_global_udls/#see-also","title":"See also","text":"operator\"\"_jsonoperator\"\"_json_pointer#define JSON_USE_IMPLICIT_CONVERSIONS /* value */\n When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType.
By default, implicit conversions are enabled.
#define JSON_USE_IMPLICIT_CONVERSIONS 1\n"},{"location":"api/macros/json_use_implicit_conversions/#notes","title":"Notes","text":"Future behavior change
Implicit conversions will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
CMake option
Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions (ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.
This is an example for an implicit conversion:
json j = \"Hello, world!\";\nstd::string s = j;\n When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0, the code above does no longer compile. Instead, it must be written like this:
json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n"},{"location":"api/macros/json_use_implicit_conversions/#see-also","title":"See also","text":"#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */\n This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default).
When enabled, comparisons involving at least one discarded JSON value yield results as follows:
Operator Result== false != true < false <= true >= true > false Otherwise, comparisons involving at least one discarded JSON value always yield false.
The default value is 0.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","title":"Notes","text":"Inconsistent behavior in C++20 and beyond
When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.
<=>) will always give the correct result (std::partial_ordering::unordered) regardless of the value of JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON.Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in inconsistent and unpredictable behavior.
See operator<=> for more information on 3-way comparison.
Deprecation
The legacy comparison behavior is deprecated and may be removed in a future major version release.
New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.
CMake option
Legacy comparison can also be controlled with the CMake option JSON_LegacyDiscardedValueComparison (OFF by default) which defines JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON accordingly.
The code below switches on the legacy discarded value comparison behavior in the library.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","title":"Version history","text":"#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(type, base_type, member...) // (1)\n#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(type, base_type, member...) // (2)\n\n#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(type, base_type, member...) // (3)\n#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, base_type, member...) // (4)\n These macros can be used to simplify the serialization/deserialization of derived types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object.
NLOHMANN_DEFINE_TYPE_INTRUSIVE, they can access private members.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, they cannot access private members.The first parameter is the name of the derived class/struct, the second parameter is the name of the base class/struct and all remaining parameters name the members. The base type must be already serializable/deserializable.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in) name of the type (class, struct) to serialize/deserialize base_type (in) name of the base type (class, struct) type is derived from member (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_derived_type/#default-definition","title":"Default definition","text":"Macros 1 and 2 add two friend functions to the class which take care of the serialization and deserialization:
friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&);\n Macros 3 and 4 add two functions to the namespace which take care of the serialization and deserialization:
void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&);\n In both cases they call the to_json/from_json functions of the base type before serializing/deserializing the members of the derived type:
class A { /* ... */ };\nclass B : public A { /* ... */ };\n\nvoid to_json(nlohmann::json& j, const B& b) {\n nlohmann::to_json(j, static_cast<const A&>(b));\n // ...\n}\n\nvoid from_json(const nlohmann::json& j, B& b) {\n nlohmann::from_json(j, static_cast<A&>(b));\n // ...\n}\n"},{"location":"api/macros/nlohmann_define_derived_type/#notes","title":"Notes","text":"Prerequisites
Implementation limits
Example of NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE usage:
class A {\n double Aa;\n double Ab;\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(A, Aa, Ab)\n};\n\nclass B : public A {\n int Ba;\n int Bb;\n NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(B, A, Ba, Bb)\n};\n"},{"location":"api/macros/nlohmann_define_derived_type/#see-also","title":"See also","text":"#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1)\n#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)\n#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)\n These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","title":"Default definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization:
friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&); // except (3)\n See examples below for the concrete generated code.
"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","title":"Notes","text":"Prerequisites
type must be default constructible (except (3)). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.NLOHMANN_DEFINE_TYPE_INTRUSIVE is used inside the class.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT can be used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n\n friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n {\n nlohmann_json_t.name = nlohmann_json_j.at(\"name\");\n nlohmann_json_t.address = nlohmann_json_j.at(\"address\");\n nlohmann_json_t.age = nlohmann_json_j.at(\"age\");\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT is used inside the class.-1 is used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n\n friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n {\n person nlohmann_json_default_obj;\n nlohmann_json_t.name = nlohmann_json_j.value(\"name\", nlohmann_json_default_obj.name);\n nlohmann_json_t.address = nlohmann_json_j.value(\"address\", nlohmann_json_default_obj.address);\n nlohmann_json_t.age = nlohmann_json_j.value(\"age\", nlohmann_json_default_obj.age);\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Note how a default-initialized person object is used in the from_json to fill missing values.
Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n // No default constructor\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n Notes:
ns::person is non-default-constructible. This allows this macro to be used instead of NLOHMANN_DEFINE_TYPE_INTRUSIVE and NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE.NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE is used inside the class.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n // No default constructor\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","title":"See also","text":"#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1)\n#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)\n#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)\n These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined outside the class/struct to create code for, but inside its namespace. Unlike NLOHMANN_DEFINE_TYPE_INTRUSIVE, it cannot access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the (public) member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","title":"Default definition","text":"The macros add two functions to the namespace which take care of the serialization and deserialization:
void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&); // except (3)\n See examples below for the concrete generated code.
"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","title":"Notes","text":"Prerequisites
type must be default constructible (except (3). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE is used outside the class, but inside its namespace ns.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT can be used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n\nvoid from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n{\n nlohmann_json_t.name = nlohmann_json_j.at(\"name\");\n nlohmann_json_t.address = nlohmann_json_j.at(\"address\");\n nlohmann_json_t.age = nlohmann_json_j.at(\"age\");\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns.-1 is used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n\nvoid from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n{\n person nlohmann_json_default_obj;\n nlohmann_json_t.name = nlohmann_json_j.value(\"name\", nlohmann_json_default_obj.name);\n nlohmann_json_t.address = nlohmann_json_j.value(\"address\", nlohmann_json_default_obj.address);\n nlohmann_json_t.age = nlohmann_json_j.value(\"age\", nlohmann_json_default_obj.age);\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Note how a default-initialized person object is used in the from_json to fill missing values.
Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n Notes:
ns::person is non-default-constructible. This allows this macro to be used instead of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE and NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE is used outside the class, but inside its namespace ns.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","title":"See also","text":"#define NLOHMANN_JSON_NAMESPACE /* value */\n This macro evaluates to the full name of the nlohmann namespace.
The default value consists of the root namespace (nlohmann) and an inline ABI namespace. See nlohmann Namespace for details.
When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.
"},{"location":"api/macros/nlohmann_json_namespace/#examples","title":"Examples","text":"ExampleThe example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann\nusing json = NLOHMANN_JSON_NAMESPACE::json;\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n Output:
nlohmann::json_abi_v3_11_3\n"},{"location":"api/macros/nlohmann_json_namespace/#see-also","title":"See also","text":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_ENDNLOHMANN_JSON_NAMESPACE_NO_VERSION#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1)\n#define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2)\n These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details.
The default definitions open and close the nlohmann namespace. The precise definition of [NLOHMANN_JSON_NAMESPACE_BEGIN] varies as described here.
Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN:
namespace nlohmann\n{\ninline namespace json_abi_v3_11_2\n{\n Default definition of NLOHMANN_JSON_NAMESPACE_END:
} // namespace json_abi_v3_11_2\n} // namespace nlohmann\n When these macros are not defined, the library will define them to their default definitions.
"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","title":"Examples","text":"ExampleThe example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN/NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page.
#include <iostream>\n#include <optional>\n#include <nlohmann/json.hpp>\n\n// partial specialization (see https://json.nlohmann.me/features/arbitrary_types/)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<std::optional<T>>\n{\n static void to_json(json& j, const std::optional<T>& opt)\n {\n if (opt == std::nullopt)\n {\n j = nullptr;\n }\n else\n {\n j = *opt;\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n\nint main()\n{\n std::optional<int> o1 = 1;\n std::optional<int> o2 = std::nullopt;\n\n NLOHMANN_JSON_NAMESPACE::json j;\n j.push_back(o1);\n j.push_back(o2);\n std::cout << j << std::endl;\n}\n Output:
[1,null]\n"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","title":"See also","text":"nlohmann NamespaceNLOHMANN_JSON_NAMESPACE_NO_VERSION#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */\n If defined to 1, the version component is omitted from the inline namespace. See nlohmann Namespace for details.
The default value is 0.
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","title":"Examples","text":"ExampleThe example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace.
#include <iostream>\n\n#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1\n#include <nlohmann/json.hpp>\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n Output:
nlohmann::json_abi\n"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","title":"See also","text":"nlohmann NamespaceNLOHMANN_JSON_NAMESPACENLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)\n By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.
type (in) name of the enum to serialize/deserialize conversion (in) a pair of an enumerator and a JSON serialization; arbitrary pairs can be given as a comma-separated list"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","title":"Default definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization:
template<typename BasicJsonType>\ninline void to_json(BasicJsonType& j, const type& e);\ntemplate<typename BasicJsonType>\ninline void from_json(const BasicJsonType& j, type& e);\n"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","title":"Notes","text":"Prerequisites
The macro must be used inside the namespace of the enum.
Important notes
template get<ENUM_TYPE>(), undefined JSON values will default to the first specified conversion. Select this default pair carefully. See example 1 below.The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum TaskState\n{\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID = -1\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(TaskState,\n{\n { TS_INVALID, nullptr },\n { TS_STOPPED, \"stopped\" },\n { TS_RUNNING, \"running\" },\n { TS_COMPLETED, \"completed\" }\n})\n\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" }\n})\n} // namespace ns\n\nint main()\n{\n // serialization\n json j_stopped = ns::TS_STOPPED;\n json j_red = ns::Color::red;\n std::cout << \"ns::TS_STOPPED -> \" << j_stopped\n << \", ns::Color::red -> \" << j_red << std::endl;\n\n // deserialization\n json j_running = \"running\";\n json j_blue = \"blue\";\n auto running = j_running.template get<ns::TaskState>();\n auto blue = j_blue.template get<ns::Color>();\n std::cout << j_running << \" -> \" << running\n << \", \" << j_blue << \" -> \" << static_cast<int>(blue) << std::endl;\n\n // deserializing undefined JSON value to enum\n // (where the first map entry above is the default)\n json j_pi = 3.14;\n auto invalid = j_pi.template get<ns::TaskState>();\n auto unknown = j_pi.template get<ns::Color>();\n std::cout << j_pi << \" -> \" << invalid << \", \"\n << j_pi << \" -> \" << static_cast<int>(unknown) << std::endl;\n}\n Output:
ns::TS_STOPPED -> \"stopped\", ns::Color::red -> \"red\"\n\"running\" -> 1, \"blue\" -> 2\n3.14 -> -1, 3.14 -> 3\n Example 2: Multiple conversions for one enumerator The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\", because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" },\n { Color::red, \"rot\" } // a second conversion for Color::red\n})\n}\n\nint main()\n{\n // serialization\n json j_red = ns::Color::red;\n std::cout << static_cast<int>(ns::Color::red) << \" -> \" << j_red << std::endl;\n\n // deserialization\n json j_rot = \"rot\";\n auto rot = j_rot.template get<ns::Color>();\n auto red = j_red.template get<ns::Color>();\n std::cout << j_rot << \" -> \" << static_cast<int>(rot) << std::endl;\n std::cout << j_red << \" -> \" << static_cast<int>(red) << std::endl;\n}\n Output:
0 -> \"red\"\n\"rot\" -> 0\n\"red\" -> 0\n"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","title":"See also","text":"JSON_DISABLE_ENUM_SERIALIZATIONAdded in version 3.4.0.
"},{"location":"api/macros/nlohmann_json_version_major/","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"#define NLOHMANN_JSON_VERSION_MAJOR /* value */\n#define NLOHMANN_JSON_VERSION_MINOR /* value */\n#define NLOHMANN_JSON_VERSION_PATCH /* value */\n These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.
"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","title":"Default definition","text":"The macros are defined according to the current library version.
"},{"location":"api/macros/nlohmann_json_version_major/#examples","title":"Examples","text":"ExampleThe example below shows how NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH are defined by the library.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << \"JSON for Modern C++ version \"\n << NLOHMANN_JSON_VERSION_MAJOR << \".\"\n << NLOHMANN_JSON_VERSION_MINOR << \".\"\n << NLOHMANN_JSON_VERSION_PATCH << std::endl;\n}\n Output:
JSON for Modern C++ version 3.11.3\n"},{"location":"api/macros/nlohmann_json_version_major/#see-also","title":"See also","text":"Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:
namespace ns {\n // a simple struct to model a person\n struct person {\n std::string name;\n std::string address;\n int age;\n };\n} // namespace ns\n\nns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// convert to JSON: copy each value into the JSON object\njson j;\nj[\"name\"] = p.name;\nj[\"address\"] = p.address;\nj[\"age\"] = p.age;\n\n// ...\n\n// convert from JSON: copy each value from the JSON object\nns::person p {\n j[\"name\"].template get<std::string>(),\n j[\"address\"].template get<std::string>(),\n j[\"age\"].template get<int>()\n};\n It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
// create a person\nns::person p {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// conversion: person -> json\njson j = p;\n\nstd::cout << j << std::endl;\n// {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n\n// conversion: json -> person\nauto p2 = j.template get<ns::person>();\n\n// that's it\nassert(p == p2);\n"},{"location":"features/arbitrary_types/#basic-usage","title":"Basic usage","text":"To make this work with one of your types, you only need to provide two functions:
using json = nlohmann::json;\n\nnamespace ns {\n void to_json(json& j, const person& p) {\n j = json{ {\"name\", p.name}, {\"address\", p.address}, {\"age\", p.age} };\n }\n\n void from_json(const json& j, person& p) {\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n }\n} // namespace ns\n That's all! When calling the json constructor with your type, your custom to_json method will be automatically called. Likewise, when calling template get<your_type>() or get_to(your_type&), the from_json method will be called.
Some important things:
ns, where person is defined).template get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)from_json, use function at() to access the object values rather than operator[]. In case a key does not exist, at throws an exception that you can handle, whereas operator[] exhibits undefined behavior.std::vector: the library already implements these.If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate.
There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object:
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in from_json() due to a missing value in the JSON object.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type.NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in from_json() due to a missing value in the JSON object.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type.In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here.
Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.The to_json/from_json functions for the person struct above can be created with:
namespace ns {\n NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n}\n Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed:
namespace ns {\n class address {\n private:\n std::string street;\n int housenumber;\n int postcode;\n\n public:\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)\n };\n}\n"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
The library uses JSON Serializers to convert types to json. The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).
It is implemented like this (simplified):
template <typename T>\nstruct adl_serializer {\n static void to_json(json& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n static void from_json(const json& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...
To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:
// partial specialization (full specialization works too)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<boost::optional<T>> {\n static void to_json(json& j, const boost::optional<T>& opt) {\n if (opt == boost::none) {\n j = nullptr;\n } else {\n j = *opt; // this will call adl_serializer<T>::to_json which will\n // find the free function to_json in T's namespace!\n }\n }\n\n static void from_json(const json& j, boost::optional<T>& opt) {\n if (j.is_null()) {\n opt = boost::none;\n } else {\n opt = j.template get<T>(); // same as above, but with\n // adl_serializer<T>::from_json\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n ABI compatibility
Use NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END instead of namespace nlohmann { } in code which may be linked with different versions of this library.
get() for non-default constructible/non-copyable types?","text":"There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:
struct move_only_type {\n move_only_type() = delete;\n move_only_type(int ii): i(ii) {}\n move_only_type(const move_only_type&) = delete;\n move_only_type(move_only_type&&) = default;\n\n int i;\n};\n\nnamespace nlohmann {\n template <>\n struct adl_serializer<move_only_type> {\n // note: the return type is no longer 'void', and the method only takes\n // one argument\n static move_only_type from_json(const json& j) {\n return {j.template get<int>()};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert move_only_type to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, move_only_type t) {\n j = t.i;\n }\n };\n}\n"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"Yes. You might want to take a look at unit-udt.cpp in the test suite, to see a few examples.
If you write your own serializer, you'll need to do a few things:
basic_json alias than nlohmann::json (the last template parameter of basic_json is the JSONSerializer)basic_json alias (or a template parameter) in all your to_json/from_json methodsnlohmann::to_json and nlohmann::from_json when you need ADLHere is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
// You should use void as a second template argument\n// if you don't need compile-time checks on T\ntemplate<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>\nstruct less_than_32_serializer {\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, T value) {\n // we want to use ADL, and call the correct to_json overload\n using nlohmann::to_json; // this method is called by adl_serializer,\n // this is where the magic happens\n to_json(j, value);\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing here\n using nlohmann::from_json;\n from_json(j, value);\n }\n};\n Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
template <typename T, void>\nstruct bad_serializer\n{\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, const T& value) {\n // this calls BasicJsonType::json_serializer<T>::to_json(j, value);\n // if BasicJsonType::json_serializer == bad_serializer ... oops!\n j = value;\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // this calls BasicJsonType::json_serializer<T>::from_json(j, value);\n // if BasicJsonType::json_serializer == bad_serializer ... oops!\n value = j.template template get<T>(); // oops!\n }\n};\n"},{"location":"features/assertions/","title":"Runtime Assertions","text":"The code contains numerous debug assertions to ensure class invariants are valid or to detect undefined behavior. Whereas the former class invariants are nothing to be concerned of, the latter checks for undefined behavior are to detect bugs in client code.
"},{"location":"features/assertions/#switch-off-runtime-assertions","title":"Switch off runtime assertions","text":"Runtime assertions can be switched off by defining the preprocessor macro NDEBUG (see the documentation of assert) which is the default for release builds.
The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header.
Function operator[] implements unchecked access for objects. Whereas a missing key is added in case of non-const objects, accessing a const object with a missing key is undefined behavior (think of a dereferenced null pointer) and yields a runtime assertion.
If you are not sure whether an element in an object exists, use checked access with the at function or call the contains function before.
See also the documentation on element access.
Example 1: Missing object keyThe following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.
Example 2: Uninitialized iterator rangeThe following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::iterator it1, it2;\n json j(it1, it2);\n}\n Output:
Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.
Example 3: Uninitialized iteratorThe following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::iterator it;\n ++it;\n}\n Output:
Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n"},{"location":"features/assertions/#changes","title":"Changes","text":""},{"location":"features/assertions/#reading-from-a-null-file-or-char-pointer","title":"Reading from a null FILE or char pointer","text":"Reading from a null FILE or char pointer in C++ is undefined behavior. Until version 3.11.4, this library asserted that the pointer was not nullptr using a runtime assertion. If assertions were disabled, this would result in undefined behavior. Since version 3.11.4, this library checks for nullptr and throws a parse_error.101 to prevent the undefined behavior.
The following code will trigger an assertion at runtime:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::FILE* f = std::fopen(\"nonexistent_file.json\", \"r\");\n try {\n json j = json::parse(f);\n } catch (std::exception& e) {\n std::cerr << e.what() << std::endl;\n }\n}\n Output:
[json.exception.parse_error.101] parse error: attempting to parse an empty input; check that your input string or stream contains the expected JSON\n"},{"location":"features/binary_values/","title":"Binary Values","text":"The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored.
JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.
"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"classDiagram\n\nclass binary_t [\"json::binary_t\"] {\n +void set_subtype(std::uint64_t subtype)\n +void clear_subtype()\n +std::uint64_t subtype() const\n +bool has_subtype() const\n}\n\nclass vector [\"std::vector<uint8_t>\"]\n\nvector <|-- binary_t By default, binary values are stored as std::vector<std::uint8_t>. This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t:
auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE});\nauto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n There are several convenience functions to check and set the subtype:
binary.has_subtype(); // returns false\nbinary_with_subtype.has_subtype(); // returns true\n\nbinary_with_subtype.clear_subtype();\nbinary_with_subtype.has_subtype(); // returns true\n\nbinary_with_subtype.set_subtype(42);\nbinary.set_subtype(23);\n\nbinary.subtype(); // returns 23\n As json::binary_t is subclassing std::vector<std::uint8_t>, all member functions are available:
binary.size(); // returns 4\nbinary[1]; // returns 0xFE\n JSON values can be constructed from json::binary_t:
json j = binary;\n Binary values are primitive values just like numbers or strings:
j.is_binary(); // returns true\nj.is_primitive(); // returns true\n Given a binary JSON value, the binary_t can be accessed by reference as via get_binary():
j.get_binary().has_subtype(); // returns true\nj.get_binary().size(); // returns 4\n For convenience, binary JSON values can be constructed via json::binary:
auto j2 = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 23);\nauto j3 = json::binary({0xCA, 0xFE, 0xBA, 0xBE});\n\nj2 == j; // returns true\nj3.get_binary().has_subtype(); // returns false\nj3.get_binary().subtype(); // returns std::uint64_t(-1) as j3 has no subtype\n"},{"location":"features/binary_values/#serialization","title":"Serialization","text":"Binary values are serialized differently according to the formats.
"},{"location":"features/binary_values/#json","title":"JSON","text":"JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: bytes holds an array of integers, and subtype is an integer or null.
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// serialize to standard output\nstd::cout << j.dump(2) << std::endl;\n Output:
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n No roundtrip for binary values
The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes.
"},{"location":"features/binary_values/#bjdata","title":"BJData","text":"BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
ExampleCode:
// create a binary value of subtype 42 (will be ignored in BJData)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BJData\nauto v = json::to_bjdata(j); \n v is a std::vector<std::uint8t> with the following 20 elements:
0x7B // '{'\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '['\n 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')\n 0x5D // ']'\n0x7D // '}'\n The following code uses the type and size optimization for UBJSON:
// convert to UBJSON using the size and type optimization\nauto v = json::to_bjdata(j, true, true);\n The resulting vector has 22 elements; the optimization is not effective for examples with few values:
0x7B // '{'\n 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '[' array\n 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers\n 0x23 0x69 0x04 // '#' i 4 number of array elements\n 0xCA 0xFE 0xBA 0xBE // content\n Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:
{\n \"binary\": [202, 254, 186, 190]\n}\n"},{"location":"features/binary_values/#bson","title":"BSON","text":"BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used.
ExampleCode:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BSON\nauto v = json::to_bson(j); \n v is a std::vector<std::uint8t> with the following 22 elements:
0x16 0x00 0x00 0x00 // number of bytes in the document\n 0x05 // binary value\n 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte\n 0x04 0x00 0x00 0x00 // number of bytes\n 0x2a // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n0x00 // end of the document\n Note that the serialization preserves the subtype, and deserializing v would yield the following value:
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n"},{"location":"features/binary_values/#cbor","title":"CBOR","text":"CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
ExampleCode:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to CBOR\nauto v = json::to_cbor(j); \n v is a std::vector<std::uint8t> with the following 15 elements:
0xA1 // map(1)\n 0x66 // text(6)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0xD8 0x2A // tag(42)\n 0x44 // bytes(4)\n 0xCA 0xFE 0xBA 0xBE // content\n Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless json::cbor_tag_handler_t::ignore or json::cbor_tag_handler_t::store is passed to json::from_cbor.
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": null\n }\n}\n"},{"location":"features/binary_values/#messagepack","title":"MessagePack","text":"MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
ExampleCode:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to MessagePack\nauto v = json::to_msgpack(j); \n v is a std::vector<std::uint8t> with the following 14 elements:
0x81 // fixmap1\n 0xA6 // fixstr6\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0xD6 // fixext4\n 0x2A // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n Note that the serialization preserves the subtype, and deserializing v would yield the following value:
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n"},{"location":"features/binary_values/#ubjson","title":"UBJSON","text":"UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
ExampleCode:
// create a binary value of subtype 42 (will be ignored in UBJSON)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to UBJSON\nauto v = json::to_ubjson(j); \n v is a std::vector<std::uint8t> with the following 20 elements:
0x7B // '{'\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '['\n 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')\n 0x5D // ']'\n0x7D // '}'\n The following code uses the type and size optimization for UBJSON:
// convert to UBJSON using the size and type optimization\nauto v = json::to_ubjson(j, true, true);\n The resulting vector has 23 elements; the optimization is not effective for examples with few values:
0x7B // '{'\n 0x24 // '$' type of the object elements\n 0x5B // '[' array\n 0x23 0x69 0x01 // '#' i 1 number of object elements\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers\n 0x23 0x69 0x04 // '#' i 4 number of array elements\n 0xCA 0xFE 0xBA 0xBE // content\n Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:
{\n \"binary\": [202, 254, 186, 190]\n}\n"},{"location":"features/comments/","title":"Comments","text":"This library does not support comments by default. It does so for three reasons:
// or /* */ are allowed in JavaScript, but JSON is not JavaScript.This was not an oversight: Douglas Crockford wrote on this in May 2012:
I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
It is dangerous for interoperability if some libraries would add comment support while others don't. Please check The Harmful Consequences of the Robustness Principle on this.
However, you can pass set parameter ignore_comments to true in the parse function to ignore // or /* */ comments. Comments will then be treated as whitespace.
Example
Consider the following JSON with comments.
{\n // update in 2006: removed Pluto\n \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n}\n When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true, the comments are ignored during parsing:
#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::string s = R\"(\n {\n // update in 2006: removed Pluto\n \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n }\n )\";\n\n try\n {\n json j = json::parse(s);\n }\n catch (json::exception &e)\n {\n std::cout << e.what() << std::endl;\n }\n\n json j = json::parse(s,\n /* callback */ nullptr,\n /* allow exceptions */ true,\n /* ignore_comments */ true);\n std::cout << j.dump(2) << '\\n';\n}\n Output:
[json.exception.parse_error.101] parse error at line 3, column 9:\nsyntax error while parsing object key - invalid literal;\nlast read: '<U+000A> {<U+000A> /'; expected string literal\n {\n \"planets\": [\n \"Mercury\",\n \"Venus\",\n \"Earth\",\n \"Mars\",\n \"Jupiter\",\n \"Uranus\",\n \"Neptune\"\n ]\n}\n"},{"location":"features/enum_conversion/","title":"Specializing enum conversion","text":"By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:
// example enum type declaration\nenum TaskState {\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID=-1,\n};\n\n// map TaskState values to JSON as strings\nNLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {\n {TS_INVALID, nullptr},\n {TS_STOPPED, \"stopped\"},\n {TS_RUNNING, \"running\"},\n {TS_COMPLETED, \"completed\"},\n})\n The NLOHMANN_JSON_SERIALIZE_ENUM() macro declares a set of to_json() / from_json() functions for type TaskState while avoiding repetition and boilerplate serialization code.
// enum to JSON as string\njson j = TS_STOPPED;\nassert(j == \"stopped\");\n\n// json string to enum\njson j3 = \"running\";\nassert(j3.template get<TaskState>() == TS_RUNNING);\n\n// undefined json value to enum (where the first map entry above is the default)\njson jPi = 3.14;\nassert(jPi.template get<TaskState>() == TS_INVALID );\n"},{"location":"features/enum_conversion/#notes","title":"Notes","text":"Just as in Arbitrary Type Conversions above,
NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization.Other Important points:
template get<ENUM_TYPE>(), undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.JSON_DISABLE_ENUM_SERIALIZATION.A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values.
As for other containers, begin() returns an iterator to the first value and end() returns an iterator to the value following the last value. The latter iterator is a placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, begin() will return end().
When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.
// create JSON object {\"one\": 1, \"two\": 2, \"three\": 3}\njson j;\nj[\"one\"] = 1;\nj[\"two\"] = 2;\nj[\"three\"] = 3;\n\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n Output:
1\n3\n2\n The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".
"},{"location":"features/iterators/#access-object-key-during-iteration","title":"Access object key during iteration","text":"The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown.
// create JSON object {\"one\": 1, \"two\": 2, \"three\": 3}\njson j;\nj[\"one\"] = 1;\nj[\"two\"] = 2;\nj[\"three\"] = 3;\n\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << it.key() << \" : \" << it.value() << std::endl;\n}\n Output:
one : 1\nthree : 3\ntwo : 2\n"},{"location":"features/iterators/#range-based-for-loops","title":"Range-based for loops","text":"C++11 allows using range-based for loops to iterate over a container.
for (auto it : j_object)\n{\n // \"it\" is of type json::reference and has no key() member\n std::cout << \"value: \" << it << '\\n';\n}\n For this reason, the items() function allows accessing iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.
for (auto& el : j_object.items())\n{\n std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n The items() function also allows using structured bindings (C++17):
for (auto& [key, val] : j_object.items())\n{\n std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n Note
When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string.
Warning
Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See #2040 for more information.
rbegin() and rend() return iterators in the reverse sequence.
json j = {1, 2, 3, 4};\n\nfor (auto it = j.rbegin(); it != j.rend(); ++it)\n{\n std::cout << *it << std::endl;\n}\n Output:
4\n3\n2\n1\n"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe the underlying string or binary array is empty.
json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n Output:
\"Hello, world\"\n"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators clear all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
The following code shows how a JSON patch is applied to a value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // apply the patch\n json patched_doc = doc.patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << doc << \"\\n\\n\"\n << std::setw(4) << patched_doc << std::endl;\n}\n Output:
{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"features/json_patch/#diff","title":"Diff","text":"The library can also calculate a JSON patch (i.e., a diff) given two JSON values.
Invariant
For two JSON values source and target, the following code yields always true:
source.patch(diff(source, target)) == target;\n Example The following code shows how a JSON patch is created as a diff for two JSON values.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the source document\n json source = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the target document\n json target = R\"(\n {\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n }\n )\"_json;\n\n // create the patch\n json patch = json::diff(source, target);\n\n // roundtrip\n json patched_source = source.patch(patch);\n\n // output patch and roundtrip result\n std::cout << std::setw(4) << patch << \"\\n\\n\"\n << std::setw(4) << patched_source << std::endl;\n}\n Output:
[\n {\n \"op\": \"replace\",\n \"path\": \"/baz\",\n \"value\": \"boo\"\n },\n {\n \"op\": \"remove\",\n \"path\": \"/foo\"\n },\n {\n \"op\": \"add\",\n \"path\": \"/hello\",\n \"value\": [\n \"world\"\n ]\n }\n]\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"features/json_pointer/","title":"JSON Pointer","text":""},{"location":"features/json_pointer/#introduction","title":"Introduction","text":"The library supports JSON Pointer (RFC 6901) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document.
Consider the following JSON document
{\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n}\n Then every value inside the JSON document can be identified as follows:
JSON Pointer JSON value ``{\"array\":[\"A\",\"B\",\"C\"],\"nested\":{\"one\":1,\"two\":2,\"three\":[true,false]}} /array [\"A\",\"B\",\"C\"] /array/0 A /array/1 B /array/2 C /nested {\"one\":1,\"two\":2,\"three\":[true,false]} /nested/one 1 /nested/two 2 /nested/three [true,false] /nested/three/0 true /nested/three/1 false Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\". See RFC 6901 for more information.
JSON Pointers can be created from a string:
json::json_pointer p = \"/nested/one\";\n Furthermore, a user-defined string literal can be used to achieve the same result:
auto p = \"/nested/one\"_json_pointer;\n The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.
"},{"location":"features/json_pointer/#value-access","title":"Value access","text":"JSON Pointers can be used in the at, operator[], and value functions just like object keys or array indices.
// the JSON value from above\nauto j = json::parse(R\"({\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n})\");\n\n// access values\nauto val = j[\"\"_json_pointer]; // {\"array\":[\"A\",\"B\",\"C\"],...}\nauto val1 = j[\"/nested/one\"_json_pointer]; // 1\nauto val2 = j.at(json::json_pointer(\"/nested/three/1\")); // false\nauto val3 = j.value(json::json_pointer(\"/nested/four\"), 0); // 0\n"},{"location":"features/json_pointer/#flatten-unflatten","title":"Flatten / unflatten","text":"The library implements a function flatten to convert any JSON document into a JSON object where each key is a JSON Pointer and each value is a primitive JSON value (i.e., a string, boolean, number, or null).
// the JSON value from above\nauto j = json::parse(R\"({\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n})\");\n\n// create flattened value\nauto j_flat = j.flatten();\n The resulting value j_flat is:
{\n \"/array/0\": \"A\",\n \"/array/1\": \"B\",\n \"/array/2\": \"C\",\n \"/nested/one\": 1,\n \"/nested/two\": 2,\n \"/nested/three/0\": true,\n \"/nested/three/1\": false\n}\n The reverse function, unflatten recreates the original value.
auto j_original = j_flat.unflatten();\n"},{"location":"features/json_pointer/#see-also","title":"See also","text":"json_pointerflattenunflattenSome aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.
JSON_ASSERT(x)","text":"This macro controls which code is executed for runtime assertions of the library.
See full documentation of JSON_ASSERT(x).
JSON_CATCH_USER(exception)","text":"This macro overrides catch calls inside the library.
See full documentation of JSON_CATCH_USER(exception).
JSON_DIAGNOSTICS","text":"This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).
When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.
The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which sets JSON_DIAGNOSTICS accordingly.
See full documentation of JSON_DIAGNOSTICS.
JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20","text":"The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.
See full documentation of JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, and JSON_HAS_CPP_20.
JSON_HAS_FILESYSTEM, JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.
See full documentation of JSON_HAS_FILESYSTEM and JSON_HAS_EXPERIMENTAL_FILESYSTEM.
JSON_NOEXCEPTION","text":"Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION.
See full documentation of JSON_NOEXCEPTION.
JSON_DISABLE_ENUM_SERIALIZATION","text":"When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM.
See full documentation of JSON_DISABLE_ENUM_SERIALIZATION.
JSON_NO_IO","text":"When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).
See full documentation of JSON_NO_IO.
JSON_SKIP_LIBRARY_VERSION_CHECK","text":"When defined, the library will not create a compiler warning when a different version of the library was already included.
See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK.
JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK.
JSON_THROW_USER(exception)","text":"This macro overrides throw calls inside the library. The argument is the exception to be thrown.
See full documentation of JSON_THROW_USER(exception).
JSON_TRY_USER","text":"This macro overrides try calls inside the library.
See full documentation of JSON_TRY_USER.
JSON_USE_IMPLICIT_CONVERSIONS","text":"When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on.
See full documentation of JSON_USE_IMPLICIT_CONVERSIONS.
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_derived_type_intrusive_with_defaulttype-base_type-member","title":"NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_derived_type_non_intrusivetype-base_type-member","title":"NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_derived_type_non_intrusive_with_defaulttype-base_type-member","title":"NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE.
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.
See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT.
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE except that it defines only the serialization code. This is useful when the user type does not have a default constructor and only the serialization is required.
See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members.
See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.
See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE except that it defines only the serialization code. This is useful when the user type does not have a default constructor and only the serialization is required.
See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE.
NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)","text":"This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information.
See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM.
NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.
See full documentation of NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH.
The library supports JSON Merge Patch (RFC 7386) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.
ExampleThe following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n Output:
{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n"},{"location":"features/namespace/","title":"nlohmann Namespace","text":"The 3.11.0 release introduced an inline namespace to allow different parts of a codebase to safely use different versions of the JSON library as long as they never exchange instances of library types.
"},{"location":"features/namespace/#structure","title":"Structure","text":"The complete default namespace name is derived as follows:
nlohmann.json_abi and is followed by serveral optional ABI tags according to the value of these ABI-affecting macros, in order:JSON_DIAGNOSTICS defined non-zero appends _diag.JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON defined non-zero appends _ldvcmp._v followed by the 3 components of the version number separated by underscores. To omit the version component, see Disabling the version component below.For example, the namespace name for version 3.11.2 with JSON_DIAGNOSTICS defined to 1 is:
nlohmann::json_abi_diag_v3_11_2\n"},{"location":"features/namespace/#purpose","title":"Purpose","text":"Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS. This is illustrated in the diagram below.
graph\n json[\"<strong>nlohmann_json (v3.10.5)</strong><br>JSON_DIAGNOSTICS=0\"]\n json_diag[\"<strong>nlohmann_json (v3.10.5)</strong><br>JSON_DIAGNOSTICS=1\"]\n library[\"<strong>some library</strong>\"]\n app[\"<strong>application</strong>\"]\n\n library --> json\n app --> json_diag\n app --> library In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.
Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types.
There is an exception when forward declarations are used (i.e., when including json_fwd.hpp) in which case the linker may complain about undefined references.
Different versions are not necessarily ABI-incompatible, but the project does not actively track changes in the ABI and recommends that all parts of a codebase exchanging library types be built with the same version. Users can, at their own risk, disable the version component of the linline namespace, allowing different versions \u2013 but not configurations \u2013 to be used in cases where the linker would otherwise output undefined reference errors.
To do so, define NLOHMANN_JSON_NAMESPACE_NO_VERSION to 1.
This applies to version 3.11.2 and above only, versions 3.11.0 and 3.11.1 can apply the technique described in the next section to emulate the effect of the NLOHMANN_JSON_NAMESPACE_NO_VERSION macro.
Use at your own risk
Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!
"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows:
#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {\n#define NLOHMANN_JSON_NAMESPACE_END }\n Use at your own risk
Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!
"},{"location":"features/namespace/#version-history","title":"Version history","text":"json_v3_11_0[_abi-tag]*) in version 3.11.0.The JSON standard defines objects as \"an unordered collection of zero or more name/value pairs\". As such, an implementation does not need to preserve any specific order of object keys.
"},{"location":"features/object_order/#default-behavior-sort-keys","title":"Default behavior: sort keys","text":"The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.
#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n Output:
{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","title":"Alternative behavior: preserve insertion order","text":"If you do want to preserve the insertion order, you can try the type nlohmann::ordered_json.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing ordered_json = nlohmann::ordered_json;\n\nint main()\n{\n ordered_json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n Output:
{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map (integration) or nlohmann::fifo_map (integration).
Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above:
{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n Right way
The following code correctly calls the parse function from nlohmann::ordered_json:
std::ifstream i(\"input.json\");\nauto j = nlohmann::ordered_json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n The output will be:
{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n Wrong way The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file.
std::ifstream i(\"input.json\");\nnlohmann::ordered_json j = nlohmann::json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n The output will be:
{\n \"one\": 1,\n \"three\": 3\n \"two\": 2,\n}\n"},{"location":"features/binary_formats/","title":"Binary Formats","text":"Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports
to efficiently encode JSON values to byte vectors and to decode such vectors.
"},{"location":"features/binary_formats/#comparison","title":"Comparison","text":""},{"location":"features/binary_formats/#completeness","title":"Completeness","text":"Format Serialization Deserialization BJData complete complete BSON incomplete: top-level value must be an object incomplete, but all JSON types are supported CBOR complete incomplete, but all JSON types are supported MessagePack complete complete UBJSON complete complete"},{"location":"features/binary_formats/#binary-values","title":"Binary values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supportedSee binary values for more information.
"},{"location":"features/binary_formats/#sizes","title":"Sizes","text":"Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 %Sizes compared to minified JSON value.
"},{"location":"features/binary_formats/bjdata/","title":"BJData","text":"The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays (ND-arrays); it also adds 4 new type markers - [u] - uint16, [m] - uint32, [M] - uint64 and [h] - float16 - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms.
Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable. This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing.
References
The library uses the following mapping from JSON values types to BJData types according to the BJData specification:
JSON value type value/range BJData type marker nullnull null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a BJData value.
Any BJData output created by to_bjdata can be successfully parsed by from_bjdata.
Size constraints
The following values can not be converted to a BJData value:
Unused BJData markers
The following markers are not used in the conversion:
Z: no-op values are not created.C: single-byte strings are serialized with S markers.NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.
Endianness
A breaking difference between BJData and UBJSON is the endianness of numerical values. In BJData, all numerical data types (integers UiuImlML and floating-point values hdD) are stored in the little-endian (LE) byte order as opposed to big-endian as used by UBJSON. Adopting LE to store numeric records avoids unnecessary byte swapping on most modern computers where LE is used as the default byte order.
Optimized formats
Optimized formats for containers are supported via two parameters of to_bjdata:
use_size adds size information to the beginning of a container and removes the closing marker.use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The use_type parameter must only be used together with use_size = true.Note that use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed of the number of elements in the container.
ND-array optimized format
BJData extends UBJSON's optimized array size marker to support ND-arrays of uniform numerical data types (referred to as packed arrays). For example, the 2-D uint8 integer array [[1,2],[3,4],[5,6]], stored as nested optimized array in UBJSON [ [$U#i2 1 2 [$U#i2 3 4 [$U#i2 5 6 ], can be further compressed in BJData to [$U#[$i#i2 2 3 1 2 3 4 5 6 or [$U#[i2 i3] 1 2 3 4 5 6.
To maintain type and size information, ND-arrays are converted to JSON objects following the annotated array format (defined in the JData specification (Draft 3)), when parsed using from_bjdata. For example, the above 2-D uint8 array can be parsed and accessed as
{\n \"_ArrayType_\": \"uint8\",\n \"_ArraySize_\": [2,3],\n \"_ArrayData_\": [1,2,3,4,5,6]\n}\n Likewise, when a JSON object in the above form is serialzed using to_bjdata, it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated.
The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array.
Restrictions in optimized data types for arrays and objects
Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of UiuImlMLhdDC. This also means other variable ([{SH) or zero-length types (TFN) can not be used in an optimized array or object in BJData.
Binary values
If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print BJData's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to BJData\n std::vector<std::uint8_t> v = json::to_bjdata(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to BJData using default representation\n std::vector<std::uint8_t> v_array = json::to_bjdata(array);\n // serialize it to BJData using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);\n // serialize it to BJData using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"features/binary_formats/bjdata/#deserialization","title":"Deserialization","text":"The library maps BJData types to JSON value types as follows:
BJData type JSON value type marker no-op no value, next value is readN null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) { Complete mapping
The mapping is complete in the sense that any BJData value can be converted to a JSON value.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with BJData\n json j = json::from_bjdata(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/bson/","title":"BSON","text":"BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type.
References
The library uses the following mapping from JSON values types to BSON types:
JSON value type value/range BSON type marker nullnull null 0x0A boolean true, false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 Incomplete mapping
The mapping is incomplete, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector<std::uint8_t> v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 \n"},{"location":"features/binary_formats/bson/#deserialization","title":"Deserialization","text":"The library maps BSON record types to JSON value types as follows:
BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupportedIncomplete mapping
The mapping is incomplete. The unsupported mappings are indicated in the table above.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d,\n 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73,\n 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00\n };\n\n // deserialize it with BSON\n json j = json::from_bson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/cbor/","title":"CBOR","text":"The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation.
References
The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049):
JSON value type value/range CBOR type first byte nullnull Null 0xF6 boolean true True 0xF5 boolean false False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length: 0..23 UTF-8 string 0x60..0x77 string length: 23..255 UTF-8 string (1 byte follow) 0x78 string length: 256..65535 UTF-8 string (2 bytes follow) 0x79 string length: 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length: 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size: 0..23 array 0x80..0x97 array size: 23..255 array (1 byte follow) 0x98 array size: 256..65535 array (2 bytes follow) 0x99 array size: 65536..4294967295 array (4 bytes follow) 0x9A array size: 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size: 0..23 map 0xA0..0xB7 object size: 23..255 map (1 byte follow) 0xB8 object size: 256..65535 map (2 bytes follow) 0xB9 object size: 65536..4294967295 map (4 bytes follow) 0xBA object size: 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size: 0..23 byte string 0x40..0x57 binary size: 23..255 byte string (1 byte follow) 0x58 binary size: 256..65535 byte string (2 bytes follow) 0x59 binary size: 65536..4294967295 byte string (4 bytes follow) 0x5A binary size: 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above.
Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a CBOR value.
NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to null.
Unused CBOR types
The following CBOR types are not used in the conversion:
Tagged items
Binary subtypes will be serialized as tagged items. See binary values for an example.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to CBOR\n std::vector<std::uint8_t> v = json::to_cbor(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"features/binary_formats/cbor/#deserialization","title":"Deserialization","text":"The library maps CBOR types to JSON value types as follows:
CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF Falsefalse 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB Incomplete mapping
The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors:
Object keys
CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected.
Tagged items
Tagged items will throw a parse error by default. They can be ignored by passing cbor_tag_handler_t::ignore to function from_cbor. They can be stored by passing cbor_tag_handler_t::store to function from_cbor.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with CBOR\n json j = json::from_cbor(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/messagepack/","title":"MessagePack","text":"MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.
References
The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification:
JSON value type value/range MessagePack type first byte nullnull nil 0xC0 boolean true true 0xC3 boolean false false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length: 0..31 fixstr 0xA0..0xBF string length: 32..255 str 8 0xD9 string length: 256..65535 str 16 0xDA string length: 65536..4294967295 str 32 0xDB array size: 0..15 fixarray 0x90..0x9F array size: 16..65535 array 16 0xDC array size: 65536..4294967295 array 32 0xDD object size: 0..15 fix map 0x80..0x8F object size: 16..65535 map 16 0xDE object size: 65536..4294967295 map 32 0xDF binary size: 0..255 bin 8 0xC4 binary size: 256..65535 bin 16 0xC5 binary size: 65536..4294967295 bin 32 0xC6 Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value.
Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.
Size constraints
The following values can not be converted to a MessagePack value:
NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the dump function which serializes NaN or Infinity to null.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"features/binary_formats/messagepack/#deserialization","title":"Deserialization","text":"The library maps MessagePack types to JSON value types as follows:
MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nilnull 0xC0 false false 0xC2 true true 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF Info
Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/ubjson/","title":"UBJSON","text":"Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON.
References
The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:
JSON value type value/range UBJSON type marker nullnull null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map { Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.
Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson.
Size constraints
The following values can not be converted to a UBJSON value:
Unused UBJSON markers
The following markers are not used in the conversion:
Z: no-op values are not created.C: single-byte strings are serialized with S markers.NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.
Optimized formats
The optimized formats for containers are supported: Parameter use_size adds size information to the beginning of a container and removes the closing marker. Parameter use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The use_type parameter must only be used together with use_size = true.
Note that use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container.
Binary values
If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON documentation. In particular, this means that serialization and the deserialization of a JSON containing binary values into UBJSON and back will result in a different JSON object.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print UBJSON's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to UBJSON\n std::vector<std::uint8_t> v = json::to_ubjson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to UBJSON using default representation\n std::vector<std::uint8_t> v_array = json::to_ubjson(array);\n // serialize it to UBJSON using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);\n // serialize it to UBJSON using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"features/binary_formats/ubjson/#deserialization","title":"Deserialization","text":"The library maps UBJSON types to JSON value types as follows:
UBJSON type JSON value type marker no-op no value, next value is readN null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) { Complete mapping
The mapping is complete in the sense that any UBJSON value can be converted to a JSON value.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with UBJSON\n json j = json::from_ubjson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/element_access/","title":"Element Access","text":"There are many ways elements in a JSON value can be accessed:
operator[]atvalueThe at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise.
Consider the following JSON value:
{\n \"name\": \"Mary Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n Assume the value is parsed to a json variable j.
j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j.at(\"name\") \"Mary Smith\" j.at(\"age\") 42 j.at(\"hobbies\") [\"hiking\", \"reading\"] j.at(\"hobbies\").at(0) \"hiking\" j.at(\"hobbies\").at(1) \"reading\" The return value is a reference, so it can be modified by the original value.
Write accessj.at(\"name\") = \"John Smith\";\n This code produces the following JSON value:
{\n \"name\": \"John Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n When accessing an invalid index (i.e., an index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown.
Accessing via invalid index or missing keyj.at(\"hobbies\").at(3) = \"cooking\";\n This code produces the following exception:
[json.exception.out_of_range.401] array index 3 is out of range\n When you extended diagnostic messages are enabled by defining JSON_DIAGNOSTICS, the exception further gives information where the key or index is missing or out of range.
[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n"},{"location":"features/element_access/checked_access/#notes","title":"Notes","text":"Exceptions
at can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown.basic_json::out_of_range exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid.basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown access to invalid array index basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown"},{"location":"features/element_access/default_value/","title":"Access with default value: value","text":""},{"location":"features/element_access/default_value/#overview","title":"Overview","text":"In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present.
ExampleConsider the following JSON value:
{\n \"logOutput\": \"result.log\",\n \"append\": true\n}\n Assume the value is parsed to a json variable j.
j {\"logOutput\": \"result.log\", \"append\": true} j.value(\"logOutput\", \"logfile.log\") \"result.log\" j.value(\"append\", true) true j.value(\"append\", false) true j.value(\"logLevel\", \"verbose\") \"verbose\""},{"location":"features/element_access/default_value/#note","title":"Note","text":"Exceptions
value can only be used with objects. For other types, a basic_json::type_error is thrown.Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std::map and a std::vector, respectively.
Consider the following JSON value:
{\n \"name\": \"Mary Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n Assume the value is parsed to a json variable j.
j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j[\"name\"] \"Mary Smith\" j[\"age\"] 42 j[\"hobbies\"] [\"hiking\", \"reading\"] j[\"hobbies\"][0] \"hiking\" j[\"hobbies\"][1] \"reading\" The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten.
j[\"name\"] = \"John Smith\";\nj[\"maidenName\"] = \"Jones\";\n This code produces the following JSON value:
{\n \"name\": \"John Smith\",\n \"maidenName\": \"Jones\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with null.
null values j[\"hobbies\"][0] = \"running\";\nj[\"hobbies\"][3] = \"cooking\";\n This code produces the following JSON value:
{\n \"name\": \"John Smith\",\n \"maidenName\": \"Jones\",\n \"age\": 42,\n \"hobbies\": [\"running\", \"reading\", null, \"cooking\"]\n}\n"},{"location":"features/element_access/unchecked_access/#notes","title":"Notes","text":"Design rationale
The library behaves differently to std::vector and std::map:
std::vector::operator[] never inserts a new element.std::map::operator[] is not available for const values.The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.
Info
The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.
Danger
NDEBUG or redefine the macro JSON_ASSERT(x). See the documentation on runtime assertions for more information.Exceptions
operator[] can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown.
null value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted null value is returned; any index between previous maximal index and passed index are filled with null undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"Note
This page is under construction.
"},{"location":"features/parsing/#input","title":"Input","text":""},{"location":"features/parsing/#sax-vs-dom-parsing","title":"SAX vs. DOM parsing","text":""},{"location":"features/parsing/#exceptions","title":"Exceptions","text":"See parsing and exceptions.
"},{"location":"features/parsing/json_lines/","title":"JSON Lines","text":"The JSON Lines format is a text format of newline-delimited JSON. In particular:
\\n. As \\r is silently ignored, \\r\\n is also supported.\\n, but is not required to be one.JSON Text example
{\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]}\n{\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]}\n{\"name\": \"May\", \"wins\": []}\n{\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]}\n JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used:
Example: Parse JSON Text input line by line
The example below demonstrates how JSON Lines can be processed.
#include <sstream>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // JSON Lines (see https://jsonlines.org)\n std::stringstream input;\n input << R\"({\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]}\n{\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]}\n{\"name\": \"May\", \"wins\": []}\n{\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]}\n)\";\n\n std::string line;\n while (std::getline(input, line))\n {\n std::cout << json::parse(line) << std::endl;\n }\n}\n Output:
{\"name\":\"Gilbert\",\"wins\":[[\"straight\",\"7\u2663\"],[\"one pair\",\"10\u2665\"]]}\n{\"name\":\"Alexa\",\"wins\":[[\"two pair\",\"4\u2660\"],[\"two pair\",\"9\u2660\"]]}\n{\"name\":\"May\",\"wins\":[]}\n{\"name\":\"Deloise\",\"wins\":[[\"three of a kind\",\"5\u2663\"]]}\n Note
Using operator>> like
json j;\nwhile (input >> j)\n{\n std::cout << j << std::endl;\n}\n with a JSON Lines input does not work, because the parser will try to parse one value after the last one.
"},{"location":"features/parsing/parse_exceptions/","title":"Parsing and Exceptions","text":"When the input is not valid JSON, an exception of type parse_error is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions. In case you process untrusted input, always enclose your code with a try/catch block, like
json j;\ntry\n{\n j = json::parse(my_input);\n}\ncatch (json::parse_error& ex)\n{\n std::cerr << \"parse error at byte \" << ex.byte << std::endl;\n}\n In case exceptions are undesired or not supported by the environment, there are different ways to proceed:
"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs (true, default) or whether a discarded value should be returned (false).
json j = json::parse(my_input, nullptr, false);\nif (j.is_discarded())\n{\n std::cerr << \"parse error\" << std::endl;\n}\n Note there is no diagnostic information available in this scenario.
"},{"location":"features/parsing/parse_exceptions/#use-accept-function","title":"Use accept() function","text":"Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON.
if (!json::accept(my_input))\n{\n std::cerr << \"parse error\" << std::endl;\n}\n Again, there is no diagnostic information available.
"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","title":"User-defined SAX interface","text":"Finally, you can implement the SAX interface and decide what should happen in case of a parse error.
This function has the following interface:
bool parse_error(std::size_t position,\n const std::string& last_token,\n const json::exception& ex);\n The return value indicates whether the parsing should continue, so the function should usually return false.
#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nclass sax_no_exception : public nlohmann::detail::json_sax_dom_parser<json>\n{\n public:\n sax_no_exception(json& j)\n : nlohmann::detail::json_sax_dom_parser<json>(j, false)\n {}\n\n bool parse_error(std::size_t position,\n const std::string& last_token,\n const json::exception& ex)\n {\n std::cerr << \"parse error at input byte \" << position << \"\\n\"\n << ex.what() << \"\\n\"\n << \"last read: \\\"\" << last_token << \"\\\"\"\n << std::endl;\n return false;\n }\n};\n\nint main()\n{\n std::string myinput = \"[1,2,3,]\";\n\n json result;\n sax_no_exception sax(result);\n\n bool parse_result = json::sax_parse(myinput, &sax);\n if (!parse_result)\n {\n std::cerr << \"parsing unsuccessful!\" << std::endl;\n }\n\n std::cout << \"parsed value: \" << result << std::endl;\n}\n Output:
parse error at input byte 8\n[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nlast read: \"3,]\"\nparsing unsuccessful!\nparsed value: [1,2,3]\n"},{"location":"features/parsing/parser_callbacks/","title":"Parser Callbacks","text":""},{"location":"features/parsing/parser_callbacks/#overview","title":"Overview","text":"With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
The type of the callback function is:
template<typename BasicJsonType>\nusing parser_callback_t =\n std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n"},{"location":"features/parsing/parser_callbacks/#callback-event-types","title":"Callback event types","text":"We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example When parsing the following JSON text,
{\n \"name\": \"Berlin\",\n \"location\": [\n 52.519444,\n 13.406667\n ]\n}\n these calls are made to the callback function:
event depth parsedobject_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [52.519444,13.406667] object_end 0 {\"location\":[52.519444,13.406667],\"name\":\"Berlin\"}"},{"location":"features/parsing/parser_callbacks/#return-value","title":"Return value","text":"Discarding a value (i.e., returning false) has different effects depending on the context in which the function was called:
null. This case happens if the top-level element is skipped.The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n"},{"location":"features/parsing/sax_interface/","title":"SAX Interface","text":"The library uses a SAX-like interface with the following functions:
classDiagram\n\nclass sax_t [\"json::sax_t\"] {\n <<interface>>\n +bool null()*\n\n +bool boolean(bool val)*\n\n +bool number_integer(number_integer_t val)*\n +bool number_unsigned(number_unsigned_t val)*\n\n +bool number_float(number_float_t val, const string_t& s)*\n\n +bool string(string_t& val)*\n +bool binary(binary_t& val)*\n\n +bool start_object(std::size_t elements)*\n +bool end_object()*\n +bool start_array(std::size_t elements)*\n +bool end_array()*\n +bool key(string_t& val)*\n\n +bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex)*\n} // called when null is parsed\nbool null();\n\n// called when a boolean is parsed; value is passed\nbool boolean(bool val);\n\n// called when a signed or unsigned integer number is parsed; value is passed\nbool number_integer(number_integer_t val);\nbool number_unsigned(number_unsigned_t val);\n\n// called when a floating-point number is parsed; value and original string is passed\nbool number_float(number_float_t val, const string_t& s);\n\n// called when a string is parsed; value is passed and can be safely moved away\nbool string(string_t& val);\n// called when a binary value is parsed; value is passed and can be safely moved away\nbool binary(binary& val);\n\n// called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)\nbool start_object(std::size_t elements);\nbool end_object();\nbool start_array(std::size_t elements);\nbool end_array();\n// called when an object key is parsed; value is passed and can be safely moved away\nbool key(string_t& val);\n\n// called when a parse error occurs; byte position, the last token, and an exception is passed\nbool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex);\n The return value of each function determines whether parsing should proceed.
To implement your own SAX handler, proceed as follows:
nlohmann::json_sax<json> as base class, but you can also use any class where the functions described above are implemented and public.my_sax.bool json::sax_parse(input, &my_sax); where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return json value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error - it is up to you what to do with the exception object passed to your parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file json_sax.hpp.
This page gives an overview how JSON values are stored and how this can be configured.
"},{"location":"features/types/#overview","title":"Overview","text":"By default, JSON values are stored as follows:
JSON type C++ type objectstd::map<std::string, basic_json> array std::vector<basic_json> null std::nullptr_t string std::string boolean bool number std::int64_t, std::uint64_t, and double Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.
"},{"location":"features/types/#storage","title":"Storage","text":"classDiagram\n\nclass value_t {\n <<enumeration>>\n null\n object\n array\n string\n boolean\n number_integer\n number_unsigned\n number_float\n binary\n discarded\n}\n\nclass json_value {\n <<union>>\n object_t* object\n array_t* array\n string_t* string\n binary_t* binary\n boolean_t boolean\n number_integer_t number_integer\n number_unsigned_t number_unsigned\n number_float_t number_float\n}\n\nclass basic_json {\n -value_t m_type\n -json_value m_value\n +typedef object_t\n +typedef array_t\n +typedef binary_t\n +typedef boolean_t\n +typedef number_integer_t\n +typedef number_unsigned_t\n +typedef number_float_t\n}\n\nbasic_json .. json_value\nbasic_json .. value_t"},{"location":"features/types/#template-arguments","title":"Template arguments","text":"The data types to store a JSON value are derived from the template arguments passed to class basic_json:
template<\n template<typename U, typename V, typename... Args> class ObjectType = std::map,\n template<typename U, typename... Args> class ArrayType = std::vector,\n class StringType = std::string,\n class BooleanType = bool,\n class NumberIntegerType = std::int64_t,\n class NumberUnsignedType = std::uint64_t,\n class NumberFloatType = double,\n template<typename U> class AllocatorType = std::allocator,\n template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,\n class BinaryType = std::vector<std::uint8_t>\n>\nclass basic_json;\n Type json is an alias for basic_json<> and uses the default types.
From the template arguments, the following types are derived:
using object_comparator_t = std::less<>;\nusing object_t = ObjectType<StringType, basic_json, object_comparator_t,\n AllocatorType<std::pair<const StringType, basic_json>>>;\n\nusing array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n\nusing string_t = StringType;\n\nusing boolean_t = BooleanType;\n\nusing number_integer_t = NumberIntegerType;\nusing number_unsigned_t = NumberUnsignedType;\nusing number_float_t = NumberFloatType;\n\nusing binary_t = nlohmann::byte_container_with_subtype<BinaryType>;\n"},{"location":"features/types/#objects","title":"Objects","text":"RFC 8259 describes JSON objects as follows:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
"},{"location":"features/types/#default-type","title":"Default type","text":"With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:
std::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n"},{"location":"features/types/#behavior","title":"Behavior","text":"The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
{\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.dump) in this order. For instance, both {\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be stored and serialized as {\"a\": 2, \"b\": 1}.{\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be treated as equal.The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.
RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.
Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.
RFC 8259 describes JSON arrays as follows:
An array is an ordered sequence of zero or more values.
"},{"location":"features/types/#default-type_1","title":"Default type","text":"With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:
std::vector<\n basic_json, // value_type\n std::allocator<basic_json> // allocator_type\n>\n"},{"location":"features/types/#limits_1","title":"Limits","text":"RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.
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.
RFC 8259 describes JSON strings as follows:
A string is a sequence of zero or more Unicode characters.
Unicode values are split by the JSON class into byte-sized characters during deserialization.
"},{"location":"features/types/#default-type_2","title":"Default type","text":"With the default values for StringType (std::string), the default value for string_t is std::string.
Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.
RFC 8259 states:
Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal.
This implementation is interoperable as it does compare strings code unit by code unit.
"},{"location":"features/types/#storage_3","title":"Storage","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.
RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.
With the default values for BooleanType (bool), the default value for boolean_t is bool.
Boolean values are stored directly inside a basic_json type.
See the number handling article for a detailed discussion on how numbers are handled by this library.
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t, and number_float_t are used.
With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t. With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t. With the default values for NumberFloatType (double), the default value for number_float_t is double.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t.
When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.
RFC 8259 states:
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.
This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.
Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.
This document describes how the library is handling numbers.
"},{"location":"features/types/number_handling/#background","title":"Background","text":"This section briefly summarizes how the JSON specification describes how numbers should be handled.
"},{"location":"features/types/number_handling/#json-number-syntax","title":"JSON number syntax","text":"JSON defines the syntax of numbers as follows:
RFC 8259, Section 6
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed.
A fraction part is a decimal point followed by one or more digits.
An exponent part begins with the letter E in uppercase or lowercase, which may be followed by a plus or minus sign. The E and optional sign are followed by one or more digits.
The following railroad diagram from json.org visualizes the number syntax:
"},{"location":"features/types/number_handling/#number-interoperability","title":"Number interoperability","text":"On number interoperability, the following remarks are made:
RFC 8259, Section 6
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available.
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
"},{"location":"features/types/number_handling/#library-implementation","title":"Library implementation","text":"This section describes how the above number specification is implemented by this library.
"},{"location":"features/types/number_handling/#number-storage","title":"Number storage","text":"In the default json type, numbers are stored as std::uint64_t, std::int64_t, and double, respectively. Thereby, std::uint64_t and std::int64_t are used only if they can store the number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as double.
Notes
double.std::strtoull, std::strtoll, and std::strtod, respectively.Examples
-12345678912345789123456789 is smaller than INT64_MIN and will be stored as floating-point number -1.2345678912345788e+25.1E3 will be stored as floating-point number 1000.0.double (i.e., numbers that after conversion via std::strtod are not satisfying std::isfinite such as 1E400) will throw exception json.exception.out_of_range.406 during parsing.double. For instance 3.141592653589793238462643383279 is stored as 0x400921fb54442d18. This is the same behavior as the code double x = 3.141592653589793238462643383279;.Interoperability
double. This also concurs with the specification above.The JSON number grammar allows for different ways to express zero, and this library will store zeros differently:
Literal Stored value and type Serialization0 std::uint64_t(0) 0 -0 std::int64_t(0) 0 0.0 double(0.0) 0.0 -0.0 double(-0.0) -0.0 0E0 double(0.0) 0.0 -0E0 double(-0.0) -0.0 That is, -0 is stored as a signed integer, but the serialization does not reproduce the -.
%g printf modifier with std::numeric_limits<double>::max_digits10 significant digits. The rationale is to use the shortest representation while still allow round-tripping.Notes regarding precision of floating-point numbers
As described above, floating-point numbers are rounded to the nearest double and serialized with the shortest representation to allow round-tripping. This can yield confusing examples:
2555.5599999999999 will be serialized as 2555.56. The reverse can also be true.0.0000972439793401814 will be serialized as 9.72439793401814e-05. The reverse can also be true: 12345E-5 will be serialized as 0.12345.float to double can also introduce rounding errors: float f = 0.3;\njson j = f;\nstd::cout << j << '\\n';\n yields 0.30000001192092896.All examples here can be reproduced by passing the original double value to
std::printf(\"%.*g\\n\", std::numeric_limits<double>::max_digits10, double_value);\n"},{"location":"features/types/number_handling/#nan-handling","title":"NaN handling","text":"NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded:
RFC 8259, Section 6
Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment.
This library serializes NaN values as null. This corresponds to the behavior of JavaScript's JSON.stringify function.
Example
The following example shows how a NaN value is stored in a json value.
int main()\n{\n double val = std::numeric_limits<double>::quiet_NaN();\n std::cout << \"val=\" << val << std::endl;\n json j = val;\n std::cout << \"j=\" << j.dump() << std::endl;\n val = j;\n std::cout << \"val=\" << val << std::endl;\n}\n output:
val=nan\nj=null\nval=nan\n"},{"location":"features/types/number_handling/#number-comparison","title":"Number comparison","text":"Floating-point inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default.
Alternative comparison functions
To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance
template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\ninline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n{\n return std::abs(a - b) <= epsilon;\n}\n Or you can self-define an operator equal function like this: bool my_equal(const_reference lhs, const_reference rhs)\n{\n const auto lhs_type lhs.type();\n const auto rhs_type rhs.type();\n if (lhs_type == rhs_type)\n {\n switch(lhs_type)\n {\n // self_defined case\n case value_t::number_float:\n return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();\n\n // other cases remain the same with the original\n ...\n }\n }\n ...\n}\n (see #703 for more information.)
Note
NaN values never compare equal to themselves or to other NaN values. See #514.
"},{"location":"features/types/number_handling/#number-conversion","title":"Number conversion","text":"Just like the C++ language itself, the get family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising.
Unconditional number conversions
double d = 42.3; // non-integer double value 42.3\njson jd = d; // stores double value 42.3\nstd::int64_t i = jd.template get<std::int64_t>(); // now i==42; no warning or error is produced\n Note the last line with throw a json.exception.type_error.302 exception if jd is not a numerical type, for instance a string.
The rationale is twofold:
Conditional number conversion
The code above can be solved by explicitly checking the nature of the value with members such as is_number_integer() or is_number_unsigned():
// check if jd is really integer-valued\nif (jd.is_number_integer())\n{\n // if so, do the conversion and use i\n std::int64_t i = jd.template get<std::int64_t>();\n // ...\n}\nelse\n{\n // otherwise, take appropriate action\n // ...\n}\n Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.
(Example taken from #777.)
"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"As the example in Number conversion shows, there are different functions to determine the type of the stored number:
is_number() returns true for any number typeis_number_integer() returns true for signed and unsigned integersis_number_unsigned() returns true for unsigned integers onlyis_number_float() returns true for floating-point numberstype_name() returns \"number\" for any number typetype() returns a different enumerator of value_t for all number typesis_number() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"The number types can be changed with template parameters.
position number type default type possible values 5 signed integersstd::int64_t std::int32_t, std::int16_t, etc. 6 unsigned integers std::uint64_t std::uint32_t, std::uint16_t, etc. 7 floating-point double float, long double Constraints on number types
long long. The type for floating-point numbers is used in case of overflow.unsigned long long. The type for floating-point numbers is used in case of overflow.double, float, and long double are supported for floating-point numbers.Example
A basic_json type that uses long double as floating-point type.
using json_ld = nlohmann::basic_json<std::map, std::vector, std::string, bool,\n std::int64_t, std::uint64_t, long double>;\n Note values should then be parsed with json_ld::parse rather than json::parse as the latter would parse floating-point values to double before then converting them to long double.
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
"},{"location":"home/code_of_conduct/#our-standards","title":"Our Standards","text":"Examples of behavior that contributes to creating a positive environment include:
Examples of unacceptable behavior by participants include:
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
"},{"location":"home/code_of_conduct/#scope","title":"Scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
"},{"location":"home/code_of_conduct/#enforcement","title":"Enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
"},{"location":"home/code_of_conduct/#attribution","title":"Attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4
"},{"location":"home/customers/","title":"Customers","text":"The library is used in multiple projects, applications, operating systems, etc. The list below is not exhaustive, but the result of an internet search. If you know further customers of the library, please let me know.
"},{"location":"home/customers/#space-exploration","title":"Space Exploration","text":"#include \"json.hpp\"#include <nlohmann/json.hpp>.There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:
Intuitive syntax. In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code.
Trivial integration. Our whole code consists of a single header file json.hpp. That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings.
Serious testing. Our class is heavily unit-tested and covers 100% of the code, including all exceptional behavior. Furthermore, we checked with Valgrind and the Clang Sanitizers that there are no memory leaks. Google OSS-Fuzz additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the Core Infrastructure Initiative (CII) best practices.
Other aspects were not so important to us:
Memory efficiency. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C++ data types: std::string for strings, int64_t, uint64_t or double for numbers, std::map for objects, std::vector for arrays, and bool for Booleans. However, you can template the generalized class basic_json to your needs.
Speed. There are certainly faster JSON libraries out there. However, if your goal is to speed up your development by adding JSON support with a single header, then this library is the way to go. If you know how to use a std::vector or std::map, you are already set.
See the contribution guidelines for more information.
"},{"location":"home/exceptions/","title":"Exceptions","text":""},{"location":"home/exceptions/#overview","title":"Overview","text":""},{"location":"home/exceptions/#base-type","title":"Base type","text":"All exceptions inherit from class json::exception (which in turn inherits from std::exception). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions.
classDiagram\n direction LR\n class `std::exception` {\n <<interface>>\n }\n\n class `json::exception` {\n +const int id\n +const char* what() const\n }\n\n class `json::parse_error` {\n +const std::size_t byte\n }\n\n class `json::invalid_iterator`\n class `json::type_error`\n class `json::out_of_range`\n class `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`"},{"location":"home/exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION. In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw), JSON_TRY_USER (overriding try), and JSON_CATCH_USER (overriding catch).
Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>\n\n#define JSON_TRY_USER if(true)\n#define JSON_CATCH_USER(exception) if(false)\n#define JSON_THROW_USER(exception) \\\n {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\\n << \" (function \" << __FUNCTION__ << \") - \" \\\n << (exception).what() << std::endl; \\\n std::abort();}\n\n#include <nlohmann/json.hpp>\n Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
See documentation of JSON_TRY_USER, JSON_CATCH_USER and JSON_THROW_USER for more information.
Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult.
Example#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] type must be number, but is string\n This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.
To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer.
As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp.
#include <iostream>\n\n# define JSON_DIAGNOSTICS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.
See documentation of JSON_DIAGNOSTICS for more information.
This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.
Exceptions have ids 1xx.
Byte index
Member byte holds the byte index of the last read character in the input file.
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).
ExampleThe following code shows how a parse_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // parsing input with a syntax error\n json::parse(\"[1,2,3,]\");\n }\n catch (const json::parse_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << '\\n'\n << \"byte position of error: \" << e.byte << std::endl;\n }\n}\n Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nexception id: 101\nbyte position of error: 8\n"},{"location":"home/exceptions/#jsonexceptionparse_error101","title":"json.exception.parse_error.101","text":"This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte indicates the error position.
Example message
Input ended prematurely:
[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal\n No input:
[json.exception.parse_error.101] parse error at line 1, column 1: attempting to parse an empty input; check that your input string or stream contains the expected JSON\n Control character was not escaped:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\\\; last read: '\"<U+0009>'\"\n String was not closed:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '\"'\n Invalid number format:
[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'\n \\u was not be followed by four hex digits:
[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\\u' must be followed by 4 hex digits; last read: '\"\\u01\"'\n Invalid UTF-8 surrogate pair:
[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uD7FF\\uDC00'\"\n Invalid UTF-8 byte:
[json.exception.parse_error.101] parse error at line 3, column 24: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '\"vous \\352t'\n Tip
JSON uses the \\uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \\uxxxx entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
Example message
parse error at 14: missing or wrong low surrogate\n Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
"},{"location":"home/exceptions/#jsonexceptionparse_error103","title":"json.exception.parse_error.103","text":"Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
Example message
parse error: code points above 0x10FFFF are invalid\n Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
"},{"location":"home/exceptions/#jsonexceptionparse_error104","title":"json.exception.parse_error.104","text":"RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.
Example message
[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\n"},{"location":"home/exceptions/#jsonexceptionparse_error105","title":"json.exception.parse_error.105","text":"An operation of a JSON Patch document must contain exactly one \"op\" member, whose value indicates the operation to perform. Its value must be one of \"add\", \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are errors.
Example message
[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'\n [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'\n [json.exception.parse_error.105] parse error: operation value 'foo' is invalid\n"},{"location":"home/exceptions/#jsonexceptionparse_error106","title":"json.exception.parse_error.106","text":"An array index in a JSON Pointer (RFC 6901) may be 0 or any number without a leading 0.
Example message
[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n"},{"location":"home/exceptions/#jsonexceptionparse_error107","title":"json.exception.parse_error.107","text":"A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character.
Example message
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n"},{"location":"home/exceptions/#jsonexceptionparse_error108","title":"json.exception.parse_error.108","text":"In a JSON Pointer, only ~0 and ~1 are valid escape sequences.
Example message
[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n"},{"location":"home/exceptions/#jsonexceptionparse_error109","title":"json.exception.parse_error.109","text":"A JSON Pointer array index must be a number.
Example messages
[json.exception.parse_error.109] parse error: array index 'one' is not a number\n [json.exception.parse_error.109] parse error: array index '+1' is not a number\n"},{"location":"home/exceptions/#jsonexceptionparse_error110","title":"json.exception.parse_error.110","text":"When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
Example message
[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input\n [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A\n"},{"location":"home/exceptions/#jsonexceptionparse_error112","title":"json.exception.parse_error.112","text":"An unexpected byte was read in a binary format or length information is invalid (BSON).
Example messages
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C\n [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1\n [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02\n [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02\n [json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648\n [json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1\n"},{"location":"home/exceptions/#jsonexceptionparse_error113","title":"json.exception.parse_error.113","text":"While parsing a map key, a value that is not a string has been read.
Example messages
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF\n [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack string: expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0xFF\n [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing UBJSON char: byte after 'C' must be in range 0x00..0x7F; last byte: 0x82\n"},{"location":"home/exceptions/#jsonexceptionparse_error114","title":"json.exception.parse_error.114","text":"The parsing of the corresponding BSON record type is not implemented (yet).
Example message
[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF\n"},{"location":"home/exceptions/#jsonexceptionparse_error115","title":"json.exception.parse_error.115","text":"A UBJSON high-precision number could not be parsed.
Example message
[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A\n"},{"location":"home/exceptions/#iterator-errors","title":"Iterator errors","text":"This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx.
ExampleThe following code shows how an invalid_iterator exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling iterator::key() on non-object iterator\n json j = \"string\";\n json::iterator it = j.begin();\n auto k = it.key();\n }\n catch (const json::invalid_iterator& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","title":"json.exception.invalid_iterator.201","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.
Example message
[json.exception.invalid_iterator.201] iterators are not compatible\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","title":"json.exception.invalid_iterator.202","text":"In the erase or insert function, the passed iterator pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
Example messages
[json.exception.invalid_iterator.202] iterator does not fit current value\n [json.exception.invalid_iterator.202] iterators first and last must point to objects\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","title":"json.exception.invalid_iterator.203","text":"Either iterator passed to function erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
Example message
[json.exception.invalid_iterator.203] iterators do not fit current value\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","title":"json.exception.invalid_iterator.204","text":"When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
Example message
[json.exception.invalid_iterator.204] iterators out of range\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","title":"json.exception.invalid_iterator.205","text":"When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
Example message
[json.exception.invalid_iterator.205] iterator out of range\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","title":"json.exception.invalid_iterator.206","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
Example message
[json.exception.invalid_iterator.206] cannot construct with iterators from null\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","title":"json.exception.invalid_iterator.207","text":"The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
Example message
[json.exception.invalid_iterator.207] cannot use key() for non-object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","title":"json.exception.invalid_iterator.208","text":"The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.208] cannot use operator[] for object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","title":"json.exception.invalid_iterator.209","text":"The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.209] cannot use offsets with object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","title":"json.exception.invalid_iterator.210","text":"The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.
Example message
[json.exception.invalid_iterator.210] iterators do not fit\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","title":"json.exception.invalid_iterator.211","text":"The iterator range passed to the insert function must not be a subrange of the container to insert to.
Example message
[json.exception.invalid_iterator.211] passed iterators may not belong to container\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","title":"json.exception.invalid_iterator.212","text":"When two iterators are compared, they must belong to the same container.
Example message
[json.exception.invalid_iterator.212] cannot compare iterators of different containers\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","title":"json.exception.invalid_iterator.213","text":"The order of object iterators cannot be compared, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.213] cannot compare order of object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","title":"json.exception.invalid_iterator.214","text":"Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin().
Example message
[json.exception.invalid_iterator.214] cannot get value\n"},{"location":"home/exceptions/#type-errors","title":"Type errors","text":"This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx.
ExampleThe following code shows how a type_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling push_back() on a string value\n json j = \"string\";\n j.push_back(\"another string\");\n }\n catch (const json::type_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n"},{"location":"home/exceptions/#jsonexceptiontype_error301","title":"json.exception.type_error.301","text":"To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
Example message
[json.exception.type_error.301] cannot create object from initializer list\n"},{"location":"home/exceptions/#jsonexceptiontype_error302","title":"json.exception.type_error.302","text":"During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
Example messages
[json.exception.type_error.302] type must be object, but is null\n [json.exception.type_error.302] type must be string, but is object\n"},{"location":"home/exceptions/#jsonexceptiontype_error303","title":"json.exception.type_error.303","text":"To retrieve a reference to a value stored in a basic_json object with get_ref, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t &.
Example messages
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object\n [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"\n"},{"location":"home/exceptions/#jsonexceptiontype_error304","title":"json.exception.type_error.304","text":"The at() member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.304] cannot use at() with string\n [json.exception.type_error.304] cannot use at() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error305","title":"json.exception.type_error.305","text":"The operator[] member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.305] cannot use operator[] with a string argument with array\n [json.exception.type_error.305] cannot use operator[] with a numeric argument with object\n"},{"location":"home/exceptions/#jsonexceptiontype_error306","title":"json.exception.type_error.306","text":"The value() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.306] cannot use value() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error307","title":"json.exception.type_error.307","text":"The erase() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.307] cannot use erase() with string\n"},{"location":"home/exceptions/#jsonexceptiontype_error308","title":"json.exception.type_error.308","text":"The push_back() and operator+= member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.308] cannot use push_back() with string\n"},{"location":"home/exceptions/#jsonexceptiontype_error309","title":"json.exception.type_error.309","text":"The insert() member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.309] cannot use insert() with array\n [json.exception.type_error.309] cannot use insert() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error310","title":"json.exception.type_error.310","text":"The swap() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.310] cannot use swap() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error311","title":"json.exception.type_error.311","text":"The emplace() and emplace_back() member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.311] cannot use emplace() with number\n [json.exception.type_error.311] cannot use emplace_back() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error312","title":"json.exception.type_error.312","text":"The update() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.312] cannot use update() with array\n"},{"location":"home/exceptions/#jsonexceptiontype_error313","title":"json.exception.type_error.313","text":"The unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined.
Example message
[json.exception.type_error.313] invalid value to unflatten\n"},{"location":"home/exceptions/#jsonexceptiontype_error314","title":"json.exception.type_error.314","text":"The unflatten function only works for an object whose keys are JSON Pointers.
Example message
Calling unflatten() on an array [1,2,3]:
[json.exception.type_error.314] only objects can be unflattened\n"},{"location":"home/exceptions/#jsonexceptiontype_error315","title":"json.exception.type_error.315","text":"The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive.
Example message
Calling unflatten() on an object {\"/1\", [1,2,3]}:
[json.exception.type_error.315] values in object must be primitive\n"},{"location":"home/exceptions/#jsonexceptiontype_error316","title":"json.exception.type_error.316","text":"The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded.
Example message
Calling dump() on a JSON value containing an ISO 8859-1 encoded string:
[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F\n Tip
dump() function to avoid this exception:json::error_handler_t::replace will replace invalid bytes sequences with U+FFFD json::error_handler_t::ignore will silently ignore invalid byte sequencesThe dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON)
Example messages
Serializing null to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n Serializing [1,2,3] to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n Tip
Encapsulate the JSON value in an object. That is, instead of serializing true, serialize {\"value\": true}
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx.
ExampleThe following code shows how an out_of_range exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for an invalid index\n json j = {1, 2, 3, 4};\n j.at(4) = 10;\n }\n catch (const json::out_of_range& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n"},{"location":"home/exceptions/#jsonexceptionout_of_range401","title":"json.exception.out_of_range.401","text":"The provided array index i is larger than size-1.
Example message
array index 3 is out of range\n"},{"location":"home/exceptions/#jsonexceptionout_of_range402","title":"json.exception.out_of_range.402","text":"The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
Example message
array index '-' (3) is out of range\n"},{"location":"home/exceptions/#jsonexceptionout_of_range403","title":"json.exception.out_of_range.403","text":"The provided key was not found in the JSON object.
Example message
key 'foo' not found\n"},{"location":"home/exceptions/#jsonexceptionout_of_range404","title":"json.exception.out_of_range.404","text":"A reference token in a JSON Pointer could not be resolved.
Example message
unresolved reference token 'foo'\n"},{"location":"home/exceptions/#jsonexceptionout_of_range405","title":"json.exception.out_of_range.405","text":"The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
Example message
JSON pointer has no parent\n"},{"location":"home/exceptions/#jsonexceptionout_of_range406","title":"json.exception.out_of_range.406","text":"A parsed number could not be stored as without changing it to NaN or INF.
Example message
number overflow parsing '10E1000'\n"},{"location":"home/exceptions/#jsonexceptionout_of_range407","title":"json.exception.out_of_range.407","text":"UBJSON and BSON only support integer numbers up to 9223372036854775807.
Example message
number overflow serializing '9223372036854775808'\n Note
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.
"},{"location":"home/exceptions/#jsonexceptionout_of_range408","title":"json.exception.out_of_range.408","text":"The size (following #) of an UBJSON array or object exceeds the maximal capacity.
Example message
excessive array size: 8658170730974374167\n"},{"location":"home/exceptions/#jsonexceptionout_of_range409","title":"json.exception.out_of_range.409","text":"Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.
Example message
BSON key cannot contain code point U+0000 (at byte 2)\n"},{"location":"home/exceptions/#further-exceptions","title":"Further exceptions","text":"This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx.
ExampleThe following code shows how an other_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n try\n {\n // executing a failing JSON Patch operation\n json value = R\"({\n \"best_biscuit\": {\n \"name\": \"Oreo\"\n }\n })\"_json;\n json patch = R\"([{\n \"op\": \"test\",\n \"path\": \"/best_biscuit/name\",\n \"value\": \"Choco Leibniz\"\n }])\"_json;\n value.patch(patch);\n }\n catch (const json::other_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n"},{"location":"home/exceptions/#jsonexceptionother_error501","title":"json.exception.other_error.501","text":"A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
Example message
Executing {\"op\":\"test\", \"path\":\"/baz\", \"value\":\"bar\"} on {\"baz\": \"qux\"}:
[json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}\n"},{"location":"home/faq/","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"home/faq/#known-bugs","title":"Known bugs","text":""},{"location":"home/faq/#brace-initialization-yields-arrays","title":"Brace initialization yields arrays","text":"Question
Why does
json j{true};\n and
json j(true);\n yield different results ([true] vs. true)?
This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like
json array = {1, 2, 3, 4};\n for arrays and
json object = {{\"one\", 1}, {\"two\", 2}}; \n for objects.
Tip
To avoid any confusion and ensure portable code, do not use brace initialization with the types basic_json, json, or ordered_json unless you want to create an object or array as shown in the examples above.
Question
Can you add an option to ignore trailing commas?
This library does not support any feature which would jeopardize interoperability.
"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","title":"Parse errors reading non-ASCII characters","text":"Questions
[json.exception.parse_error.101] parse error at line 1, column 53: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '\"Test\u00e9$')\"The library supports Unicode input as follows:
std::u16string and std::u32string can be parsed, assuming UTF-16 and UTF-32 encoding, respectively. These encodings are not supported when reading from files or other input containers.\\uDEAD) will yield parse errors.std::string), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.dump() may throw an exception unless json::error_handler_t::replace or json::error_handler_t::ignore are used as error handlers.In most cases, the parser is right to complain, because the input is not UTF-8 encoded. This is especially true for Microsoft Windows where Latin-1 or ISO 8859-1 is often the standard encoding.
"},{"location":"home/faq/#wide-string-handling","title":"Wide string handling","text":"Question
Why are wide strings (e.g., std::wstring) dumped as arrays of numbers?
As described above, the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding.
Example
#include <codecvt> // codecvt_utf8\n#include <locale> // wstring_convert\n\n// encoding function\nstd::string to_utf8(std::wstring& wide_string)\n{\n static std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;\n return utf8_conv.to_bytes(wide_string);\n}\n\njson j;\nstd::wstring ws = L\"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\";\n\nj[\"original\"] = ws;\nj[\"encoded\"] = to_utf8(ws);\n\nstd::cout << j << std::endl;\n The result is:
{\n \"encoded\": \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\",\n \"original\": [36554, 66, 49, 50, 51, 52, 32, 12371, 12435, 12395, 12385, 12399]\n}\n"},{"location":"home/faq/#exceptions","title":"Exceptions","text":""},{"location":"home/faq/#parsing-without-exceptions","title":"Parsing without exceptions","text":"Question
Is it possible to indicate a parse error without throwing an exception?
Yes, see Parsing and exceptions.
"},{"location":"home/faq/#key-name-in-exceptions","title":"Key name in exceptions","text":"Question
Can I get the key of the object item that caused an exception?
Yes, you can. Please define the symbol JSON_DIAGNOSTICS to get extended diagnostics messages.
Question
The library uses std::numeric_limits<number_float_t>::digits10 (15 for IEEE doubles) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip.
cppreference.com
The value of std::numeric_limits<T>::digits10 is the number of base-10 digits that can be represented by the type T without change, that is, any number with this many significant decimal digits can be converted to a value of type T and back to decimal form, without change due to rounding or overflow.
Tip
The website https://float.exposed gives a good insight into the internal storage of floating-point numbers.
See this section on the library's number handling for more information.
"},{"location":"home/faq/#compilation-issues","title":"Compilation issues","text":""},{"location":"home/faq/#android-sdk","title":"Android SDK","text":"Question
Why does the code not compile with Android SDK?
Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.
APP_STL := c++_shared\nNDK_TOOLCHAIN_VERSION := clang3.6\nAPP_CPPFLAGS += -frtti -fexceptions\n The code compiles successfully with Android NDK, Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.
"},{"location":"home/faq/#missing-stl-function","title":"Missing STL function","text":"Questions
'to_string' is not a member of 'std' (or similarly, for strtod or strtof)?This is not an issue with the code, but rather with the compiler itself. On Android, see above to build with a newer environment. For MinGW, please refer to this site and this discussion for information on how to fix this bug. For Android NDK using APP_STL := gnustl_static, please refer to this discussion.
The class is licensed under the MIT License:
Copyright \u00a9 2013-2024 Niels Lohmann
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de
The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch
The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0.
"},{"location":"home/releases/","title":"Releases","text":""},{"location":"home/releases/#v373","title":"v3.7.3","text":"Files
Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)
"},{"location":"home/releases/#summary","title":"Summary","text":"This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes","title":"Bug Fixes","text":"reserve() calls from the destructor which could lead to quadratic complexity. #1837 #1838This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)
"},{"location":"home/releases/#summary_1","title":"Summary","text":"Project bad_json_parsers tested how JSON parser libraries react on deeply nested inputs. It turns out that this library segfaulted at a certain nesting depth. This bug was fixed with this release. Now the parsing is only bounded by the available memory. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_1","title":"Bug Fixes","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)
"},{"location":"home/releases/#summary_2","title":"Summary","text":"This release fixes several small bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_2","title":"Bug Fixes","text":"std::int64_t minimum value. #1708 #1722contains() function for JSON Pointers. #1727 #1741std::pair and std::tuple to json. #1805 #1806 #1825 #1826iteration_proxy. #1797json to std::valarray.items() function can now be used with a custom string type. #1765json_pointer::back const. #1764 #1769ubuntu-latest/GCC 7.4.0 as CI step.JSON_THROW_USER, JSON_TRY_USER, and JSON_CATCH_USER macros to control user-defined exception handling.GLOB from CMake files. #1779This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)
"},{"location":"home/releases/#summary_3","title":"Summary","text":"This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.
"},{"location":"home/releases/#new-features","title":"New Features","text":"contains function to check if a JSON pointer is valid without throwing exceptions, just like its counterpart for object keys. #1600to_string to allow for generic conversion to strings. #916 #1585emplace_back function, returning a reference to the added element just like C++17 is introducing this for std::vector. #1609std::string_view in the unit tests. #1634 #1639get_to method to clear existing content before writing. #1511 #1555-Wc++17-extensions warning. nodiscard attributes are now only used with Clang when -std=c++17 is used. #1535 #1551GNUInstallDirs to set library install directories. #1673json type on the documentation start page. #1616value() function with respect to type_error.302 exception. #1601JSON_BuildTests, JSON_Install, JSON_MultipleHeaders, JSON_Sanitizer, JSON_Valgrind, JSON_NoExceptions, JSON_Coverage).JSON_DEPRECATED, JSON_NODISCARD, JSON_LIKELY, JSON_UNLIKELY, JSON_HAS_CPP_14, or JSON_HAS_CPP_17. Functions taking or returning pointers are annotated accordingly when a pointer will not be null.This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)
"},{"location":"home/releases/#summary_4","title":"Summary","text":"This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_4","title":"Bug Fixes","text":"<Windows.h> was included. #1531This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip)
\u2139\ufe0f This release introduced a regression. Please update to version 3.6.1!
"},{"location":"home/releases/#summary_5","title":"Summary","text":"This release adds some convenience functions for JSON Pointers, introduces a contains function to check if a key is present in an object, and improves the performance of integer serialization. Furthermore, a lot of small bug fixes and improvements have been made. All changes are backward-compatible.
operator/ and operator/=. JSON Pointers can be inspected with empty, back, and parent_pointer, and manipulated with push_back and pop_back. #1434contains to check whether an element exists in a JSON object with a given key. Returns false when called on non-object types. #1471 #1474JSON_Install to control whether the library should be installed (default: on). #1330nodiscard attribute to meta(), array(), object(), from_cbor, from_msgpack, from_ubjson, from_bson, and parse. #1433This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)
"},{"location":"home/releases/#summary_6","title":"Summary","text":"This release introduces the support for structured bindings and reading from FILE*. Besides, a few bugs have been fixed. All changes are backward-compatible.
Structured bindings are now supported for JSON objects and arrays via the items() member function, so finally this code is possible:
for (auto& [key, val] : j.items()) {\n std::cout << key << ':' << val << '\\n';\n}\n #1388 #1391 Added support for reading from FILE* to support situations in which streams are nit available or would require too much RAM. #1370 #1392
eofbit was not set for input streams when the end of a stream was reached while parsing. #1340 #1343-Wshadow warning #1346std::snprintf calls to avoid error in MSVC. #1337This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)
"},{"location":"home/releases/#summary_7","title":"Summary","text":"This release introduces three new features:
Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_3","title":"New Features","text":"dump function for examples. #1198 #1314NLOHMANN_JSON_SERIALIZE_ENUM has been introduced. See the README section for more information. #1208 #1323parse error at 2: syntax error - invalid string: control character must be escaped; last read: '<U+0009>' is now reported as parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t; last read: '<U+0009>'. #1280 #1288 #1303This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)
"},{"location":"home/releases/#summary_8","title":"Summary","text":"This release adds support for GCC 4.8. Furthermore, it adds a function get_to to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented.
Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_4","title":"New Features","text":"get_to to write a JSON value to a passed reference. The destination type is automatically derived which allows more succinct code compared to the get function. #1227 #1231target_link_libraries to not properly include nlohmann_json. #1243 #1245 #1260-Wctor-dtor-privacy warning. #1224JSON_CATCH_USER led to duplicate macro definition of JSON_INTERNAL_CATCH. #1213 #1214find_package(nlohmann_json) without installing the library. #1202operator[] is used with the wrong combination (json.exception.type_error.305) of JSON container type and argument type. Example: \"cannot use operator[] with a string argument\". #1220 #1221to_json or from_json functions as such assertions do not play well with SFINAE. These assertions also led to problems with GMock. #960 #1212 #1228This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)
"},{"location":"home/releases/#summary_9","title":"Summary","text":"This release introduces a SAX interface to the library. While this may be a very special feature used by only few people, it allowed to unify all functions that consumed input and created some kind of JSON value. Internally, now all existing functions like parse, accept, from_cbor, from_msgpack, and from_ubjson use the SAX interface with different event processors. This allowed to separate the input processing from the value generation. Furthermore, throwing an exception in case of a parse error is now optional and up to the event processor. Finally, the JSON parser is now non-recursive (meaning it does not use the call stack, but std::vector<bool> to track the hierarchy of structured values) which allows to process nested input more efficiently.
Furthermore, the library finally is able to parse from wide string types. This is the first step toward opening the library from UTF-8 to UTF-16 and UTF-32.
This release further fixes several bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_5","title":"New Features","text":"std::wstring, std::u16string, and std::u32string; the input will be converted to UTF-8 (#1031)std::string_view when using C++17 (#1028)std::map and std::unordered_map from JSON if key type is not convertible to string; in these cases, values are serialized to arrays of pairs (#1079, #1089, #1133, #1138)nullptr_t from JSON allowing to properly roundtrip null values (#1169)items() (#1045, #1134)std::swap (#1168)key() function for iterators returns a const reference rather than a string copy (#1098)float as type for floating-point numbers (#1021)JSON_SKIP_UNSUPPORTED_COMPILER_CHECK can skip the rejection of unsupported compilers - use at your own risk! (#1128)JSON_INTERNAL_CATCH/JSON_INTERNAL_CATCH_USER allows to control the behavior of exception handling inside the library (#1187)char to JSON conversionstd::stringstream (#1117)This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)
"},{"location":"home/releases/#summary_10","title":"Summary","text":"This release fixes several bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_10","title":"Bug Fixes","text":"basic_json (e.g., using different template arguments for strings or objects) can now be used in assignments (#972, #977, #986).make clang_analyze.This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)
"},{"location":"home/releases/#summary_11","title":"Summary","text":"This release fixes several bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_11","title":"Bug Fixes","text":"0x7F start byte.null elements with a few bytes and the library did not check whether this size exceeded max_size().run_benchmarks was added to quickly build and run the benchmark suite.#include <nlohmann/json.hpp> to allow for selecting single_include or include or whatever installation folder as include directory.This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)
"},{"location":"home/releases/#summary_12","title":"Summary","text":"This release adds support for the UBJSON format and JSON Merge Patch. It also contains some minor changes and bug fixes. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_6","title":"New features","text":"merge_patch for more information.json.hpp can be generated from these development sources. In the repository, folder include contains the development sources and single_include contains the single json.hpp header (#700, #906, #907, #910, #911, #915, #920, #924, #925, #928, #944).include/nlohmann/json_fwd.hpp to speed up compilation times (#314).benchmarks folder, #921).JSON_THROW_USER, JSON_TRY_USER, and JSON_CATCH_USER, defining the behavior of throw, try and catch, respectively. This allows to switch off C++'s exception mechanism yet still execute user-defined code in case an error condition occurs (#938).yytext any more as it could clash with macro definitions (#933).NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH to allow for conditional compilation based on the included library version (#943, #948).iterator_wrapper has been deprecated (#874). Since its introduction, the name was up for discussion, as it was too technical. We now introduced the member function items() with the same semantics. iterator_wrapper will be removed in the next major version (i.e., 4.0.0).Furthermore, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0):
friend std::istream& operator<<(basic_json&, std::istream&)friend std::ostream& operator>>(const basic_json&, std::ostream&)Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.
Files
Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c
"},{"location":"home/releases/#summary_13","title":"Summary","text":"This release fixes small issues in the implementation of JSON Pointer and JSON Patch. All changes are backward-compatible.
"},{"location":"home/releases/#changes","title":"Changes","text":"10e2 are used.at(ptr) function with JSON Pointers to list all possible exceptions (see #888).BUILD_TESTING option (see #846, #885)To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0):
friend std::istream& operator<<(basic_json&, std::istream&)friend std::ostream& operator>>(const basic_json&, std::ostream&)Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.
Files
Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462
"},{"location":"home/releases/#summary_14","title":"Summary","text":"After almost a year, here is finally a new release of JSON for Modern C++, and it is a major one! As we adhere to semantic versioning, this means the release includes some breaking changes, so please read the next section carefully before you update. But don't worry, we also added a few new features and put a lot of effort into fixing a lot of bugs and straighten out a few inconsistencies.
"},{"location":"home/releases/#breaking-changes","title":"Breaking changes","text":"This section describes changes that change the public API of the library and may require changes in code using a previous version of the library. In section \"Moving from 2.x.x to 3.0.0\" at the end of the release notes, we describe in detail how existing code needs to be changed.
<stdexcept> (#244). This not only allows to add more information to the exceptions (every exception now has an identifier, and parse errors contain the position of the error), but also to easily catch all library exceptions with a single catch(json::exception).json::type_error exception during serialization (#838). The check for valid UTF-8 is realized with code from Bj\u00f6rn Hoehrmann.null (#388).<iostream>, <ctype>, and <stdexcept> any more. You may need to add these headers to code relying on them.explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) which was deprecated in version 2.0.0 (#480).To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0):
friend std::istream& operator<<(basic_json&, std::istream&)friend std::ostream& operator>>(const basic_json&, std::ostream&)Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.
With all this breaking and deprecation out of the way, let's talk about features!
json::parse_error is thrown which contains a detailed message on the error, but also a member byte to indicate the byte offset in the input where the error occurred.accept function returns a Boolean indicating whether the input is proper JSON. We also added a Boolean parameter allow_exceptions to the existing parse functions to return a discarded value in case a syntax error occurs instead of throwing an exception.update function was added to merge two JSON objects (#428). In case you are wondering: the name was inspired by Python.insert function now also supports an iterator range to add elements to an object.dump now has two optional parameters ensure_ascii to escape all non-ASCII characters with \\uxxxx and an indent_char parameter to choose whether to indent with spaces or tabs (#654). std::pair and std::tuple (#563, #614), enum and enum class (#545), std::vector<bool> (#494). Fixed support for std::valarray (#702), std::array (#553), and std::map<std::string, std::string> (#600, #607).Furthermore, there have been a lot of changes under the hood:
__builtin_expect to optimize branch prediction as long as no error occurs.from_json or to_json function was not found for a user-defined type. We also added a debug visualizer nlohmann_json.natvis for better debugging in MSVC (#844).JSON_Coverage), compilation without exceptions (JSON_NoExceptions), LLVM sanitizers (JSON_Sanitizer), or execution with Valgrind (JSON_Valgrind).There are five different exceptions inheriting from json::exception:
json::parse_error for syntax errors (including the binary formats),json::invalid_iterator for errors related to iterators,json::type_error for errors where functions were called with the wrong JSON type,json::out_of_range for range errors, andjson::other_error for miscellaneous errors.To support these exception, the try/catch blocks of your code need to be adjusted:
If an overflow occurs during parsing a number from a JSON text, an exception json::out_of_range is thrown so that the overflow is detected early and roundtripping is guaranteed.
NaN and INF floating-point values can be stored in a JSON value and are not replaced by null. That is, the basic_json class behaves like double in this regard (no exception occurs). However, NaN and INF are serialized to null.
Function explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) should be replaced by the parse function: Let ss be a stream and cb be a parse callback function.
Old code:
json j(ss, cb);\n New code:
json j = json::parse(ss, cb);\n If no callback function is used, also the following code works:
json j;\nj << ss;\n or
json j;\nss >> j;\n"},{"location":"home/releases/#v211","title":"v2.1.1","text":"Files
Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57
"},{"location":"home/releases/#summary_15","title":"Summary","text":"This release fixes a locale-related bug in the parser. To do so, the whole number handling (lexer, parser, and also the serialization) have been overworked. Furthermore, a lot of small changes added up that were added to this release. All changes are backward-compatible.
"},{"location":"home/releases/#changes_1","title":"Changes","text":". as decimal separator (e.g., the Norwegian locale nb_NO.UTF-8) led to truncated number parsing or parse errors. The library now has been fixed to work with any locale. Note that . is still the only valid decimal separator for JSON input.1.0 were correctly parsed as floating-point number, but serialized as integer (1). Now, floating-point numbers correctly round trip.0123) could yield a buffer overflow. This is fixed now by detecting such errors directly by the lexer.0 led to a comparison with null. This is fixed now.-Weverything (well, it needs -Wno-documentation-unknown-command and -Wno-deprecated-declarations, but you get the point).UINT8_MAX which previously required defining a preprocessor macro for compilation.basic_json.Files
This release introduces a means to convert from/to user-defined types. The release is backwards compatible.
"},{"location":"home/releases/#changes_2","title":"Changes","text":"to_json and from_json. Then, a conversion is as simple as putting a = between variables. See the README for more information and examples.JSON_NOEXCEPTION or by passing -fno-exceptions to your compiler. In case the code would usually thrown an exception, abort() is now called.meta() which returns a JSON object with information on the version, compiler, and platform. See the documentation for an example.type_name() is now public. It allows to query the type of a JSON value as string.Files
This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_3","title":"Changes","text":"find() function to always return end() when called on non-object value types.test/thirdparty directory.Files
This release implements with CBOR and MessagePack two binary serialization/deserialization formats. It further contains some small fixes and improvements. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_4","title":"Changes","text":"-WdocumentationFiles
This release combines a lot of small fixes and improvements. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_5","title":"Changes","text":"std::invalid_argument is thrown)std::invalid_argument is thrown)emplace and emplace_back have been added to JSON values and work as expecteddump function)Files
This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_6","title":"Changes","text":"Files
This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible.
operator[] for JSON Pointers now behaves like the other versions of operator[] and transforms null values into objects or arrays if required. This allows to created nested structures like j[\"/foo/bar/2\"] = 17 (yielding {\"foo\": \"bar\": [null, null, 17]}) without problems.Files
This release fixes a regression bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.
Files
This release fixes a bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.
Files
This release combines a lot of small fixes and improvements. The release is backwards compatible.
"},{"location":"home/releases/#changes_10","title":"Changes","text":"char, unsigned char, uint8_t). This includes all kind of string representations (string literals, char arrays, std::string, const char*), contiguous containers (C-style arrays, std::vector, std::array, std::valarray, std::initializer_list). User-defined containers providing random-access iterator access via std::begin and std::end can be used as well. See the documentation (1, 2, 3, 4) for more information. Note that contiguous storage cannot be checked at compile time; if any of the parse functions are called with a noncompliant container, the behavior is undefined and will most likely yield segmentation violation. The preconditions are enforced by an assertion unless the library is compiled with preprocessor symbol NDEBUG.operator[] for const JSON objects. The behavior of this const version of the operator is undefined if the given key does not exist in the JSON object, because unlike the non-const version, it cannot add a null value at the given key. Assertions can be switched of by defining the preprocessor symbol NDEBUG. See the documentation of assert for more information.basic_json(std::istream&, const parser_callback_t) has been deprecated and will be deleted with the next major release 3.0.0 to unify the interface of the library. Deserialization will be done by stream operators or by calling one of the parse functions. That is, calls like json j(i); for an input stream i need to be replaced by json j = json::parse(i);. Compilers will produce a deprecation warning if client code uses this function./Wall now only warns about non-inlined functions (C4710) and the deprecation of the constructor from input-stream (C4996).make check.Files
This release combines a lot of small fixes and improvements. The release is backwards compatible.
"},{"location":"home/releases/#changes_11","title":"Changes","text":"\\x10-\\x1f are not accepted any more.NDEBUG, see the documentation of assert.#error command.get_ptr().sed.std::all_of, std::for_each, or std::accumulate. This facilitates reasoning about termination of loops and sometimes allowed to simplify functions to a single return statement.value() function for JSON pointers (similar to at function).std::cout in the test cases.Files
This release fixes a performance regression in the JSON serialization (function dump()). This fix is backwards compatible.
Files
This release adds several features such as JSON Pointers, JSON Patch, or support for 64 bit unsigned integers. Furthermore, several (subtle) bugs have been fixed.
As noexcept and constexpr specifier have been added to several functions, the public API has effectively been changed in a (potential) non-backwards compatible manner. As we adhere to Semantic Versioning, this calls for a new major version, so say hello to 2\ufe0f\u20e3.0\ufe0f\u20e3.0\ufe0f\u20e3.
uint64_t (default value for template parameter NumberUnsignedType) as data type for unsigned integer values. This type is used automatically when an unsigned number is parsed. Furthermore, constructors, conversion operators and an is_number_unsigned() test have been added.at() and operator[] functions. Furthermore, JSON values can be \u201cflattened\u201d to key/value pairs using flatten() where each key is a JSON Pointer. The original value can be restored by \u201cunflattening\u201d the flattened value using unflatten().diff(const basic_json&) and applied with patch(const basic_json&). Note the created patches use a rather primitive algorithm so far and leave room for improvement..) as decimal separator and ignores different settings from the locale.brew tap nlohmann/json && brew install nlohmann_json.std::istream (e.g., std::stringstream or std::ifstream).noexcept specifier to basic_json(boolean_t), basic_json(const number_integer_t), basic_json(const int), basic_json(const number_float_t), iterator functions (begin(), end(), etc.)0.0 (vs. -0.0) is preserved.std::move.re2c to version 0.16 to use a minimal DFAs for the lexer.is_number, etc.) and const value access constexpr.push_back and operator+= now work with key/value pairs passed as initializer list, e.g. j_object += {\"key\", 1}.CMakeLists.txt to make it easier to integrate the library into other projects.diff function is rather primitive and does not create minimal diffs.iteration_wrapper may change in the future and the function will be deprecated in the next release.Files
This release fixes several small bugs and adds functionality in a backwards-compatible manner. Compared to the last version (1.0.0), the following changes have been made:
"},{"location":"home/releases/#changes_14","title":"Changes","text":"assert is used, the assertions can be switched off by defining the preprocessor symbol NDEBUG during compilation. [#168]get_ref(). [#128, #184]operator[]) now works with all kind of string representations. [#171, #189]There are still known open issues (#178, #187) which will be fixed in version 2.0.0. However, these fixes will require a small API change and will not be entirely backwards-compatible.
"},{"location":"home/releases/#v100","title":"v1.0.0","text":"Files
This is the first official release. Compared to the prerelease version 1.0.0-rc1, only a few minor improvements have been made:
"},{"location":"home/releases/#changes_15","title":"Changes","text":"sprintf is no longer used.iterator_wrapper also works for const objects; note: the name may change!parse function now also works with type std::istream&&.value(key, default_value) returns either a copy of an object's element at the specified key or a given default value if no element with the key exists.You can sponsor this library at GitHub Sponsors.
"},{"location":"home/sponsors/#named-sponsors","title":"Named Sponsors","text":"Thanks everyone!
"},{"location":"integration/","title":"Header only","text":"json.hpp is the single required file in single_include/nlohmann or released here. You need to add
#include <nlohmann/json.hpp>\n\n// for convenience\nusing json = nlohmann::json;\n to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang).
You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.
You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags.
To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration:
Example
CMakeLists.txtcmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\nfind_package(nlohmann_json 3.11.3 REQUIRED)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.
To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.
Example
CMakeLists.txtcmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\n# If you only include this third party in PRIVATE source files, you do not need to install it\n# when your main project gets installed.\nset(JSON_Install OFF CACHE INTERNAL \"\")\n\nadd_subdirectory(nlohmann_json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n Note
Do not use include(nlohmann_json/CMakeLists.txt), since that carries with it unintended consequences that will break the build. It is generally discouraged (although not necessarily well documented as such) to use include(...) for pulling in other CMake projects anyways.
To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.
Example
CMakeLists.txtproject(ExampleProject LANGUAGES CXX)\n\noption(EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF)\n\nadd_subdirectory(thirdparty)\n\nadd_executable(example example.cpp)\n\n# Note that the namespaced target will always be available regardless of the import method\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n thirdparty/CMakeLists.txtif(EXAMPLE_USE_EXTERNAL_JSON)\n find_package(nlohmann_json 3.11.3 REQUIRED)\nelse()\n set(JSON_BuildTests OFF CACHE INTERNAL \"\")\n add_subdirectory(nlohmann_json)\nendif()\n thirdparty/nlohmann_json is then a complete copy of this source tree.
Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type.
Example
CMakeLists.txtcmake_minimum_required(VERSION 3.11)\nproject(ExampleProject LANGUAGES CXX)\n\ninclude(FetchContent)\n\nFetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)\nFetchContent_MakeAvailable(json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n Note
It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like
FetchContent_Declare(json\n GIT_REPOSITORY https://github.com/nlohmann/json\n GIT_TAG v3.11.3\n)\n However, the repository https://github.com/nlohmann/json download size is quite large.
"},{"location":"integration/cmake/#cmake-options","title":"CMake Options","text":""},{"location":"integration/cmake/#json_buildtests","title":"JSON_BuildTests","text":"Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option.
JSON_CI","text":"Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.
JSON_Diagnostics","text":"Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS. This option is OFF by default.
JSON_DisableEnumSerialization","text":"Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION. This option is OFF by default.
JSON_FastTests","text":"Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests.
JSON_GlobalUDLs","text":"Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS. This option is OFF by default.
JSON_ImplicitConversions","text":"Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS. This option is ON by default.
JSON_Install","text":"Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project.
JSON_MultipleHeaders","text":"Use non-amalgamated version of the library. This option is OFF by default.
JSON_SystemInclude","text":"Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default.
JSON_Valgrind","text":"Execute test suite with Valgrind. This option is OFF by default. Depends on JSON_BuildTests.
This page collects some guidelines on how to future-proof your code for future versions of this library.
"},{"location":"integration/migration_guide/#replace-deprecated-functions","title":"Replace deprecated functions","text":"The following functions have been deprecated and will be removed in the next major version (i.e., 4.0.0). All deprecations are annotated with HEDLEY_DEPRECATED_FOR to report which function to use instead.
Function friend std::istream& operator<<(basic_json&, std::istream&) is deprecated since 3.0.0. Please use friend std::istream& operator>>(std::istream&, basic_json&) instead.
nlohmann::json j;\nstd::stringstream ss(\"[1,2,3]\");\nj << ss;\n nlohmann::json j;\nstd::stringstream ss(\"[1,2,3]\");\nss >> j;\n Passing iterator pairs or pointer/length pairs to parsing functions (parse, accept, sax_parse, from_cbor, from_msgpack, from_ubjson, and from_bson via initializer lists is deprecated since 3.8.0. Instead, pass two iterators; for instance, call from_cbor(ptr, ptr+len) instead of from_cbor({ptr, len}).
const char* s = \"[1,2,3]\";\nbool ok = nlohmann::json::accept({s, s + std::strlen(s)});\n const char* s = \"[1,2,3]\";\nbool ok = nlohmann::json::accept(s, s + std::strlen(s));\n Comparing JSON Pointers with strings via operator== and operator!= is deprecated since 3.11.2. To compare a json_pointer p with a string s, convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!=.
nlohmann::json::json_pointer lhs(\"/foo/bar/1\");\nassert(lhs == \"/foo/bar/1\");\n nlohmann::json::json_pointer lhs(\"/foo/bar/1\");\nassert(lhs == nlohmann::json::json_pointer(\"/foo/bar/1\"));\n The implicit conversion from JSON Pointers to string (json_pointer::operator string_t) is deprecated since 3.11.0. Use json_pointer::to_string instead.
nlohmann::json::json_pointer ptr(\"/foo/bar/1\");\nstd::string s = ptr;\n nlohmann::json::json_pointer ptr(\"/foo/bar/1\");\nstd::string s = ptr.to_string();\n Passing a basic_json specialization as template parameter RefStringType to json_pointer is deprecated since 3.11.0. The string type can now be directly provided.
using my_json = nlohmann::basic_json<std::map, std::vector, my_string_type>;\nnlohmann::json_pointer<my_json> ptr(\"/foo/bar/1\");\n nlohmann::json_pointer<my_string_type> ptr(\"/foo/bar/1\");\n Thereby, nlohmann::my_json::json_pointer is an alias for nlohmann::json_pointer<my_string_type> and is always an alias to the json_pointer with the appropriate string type for all specializations of basic_json.
The function iterator_wrapper is deprecated since 3.1.0. Please use the member function items instead.
for (auto &x : nlohmann::json::iterator_wrapper(j))\n{\n std::cout << x.key() << \":\" << x.value() << std::endl;\n}\n for (auto &x : j.items())\n{\n std::cout << x.key() << \":\" << x.value() << std::endl;\n}\n Function friend std::ostream& operator>>(const basic_json&, std::ostream&) is deprecated since 3.0.0. Please use friend operator<<(std::ostream&, const basic_json&) instead.
j >> std::cout;\n std::cout << j;\n The legacy comparison behavior for discarded values is deprecated since 3.11.0. It is already disabled by default and can still be enabled by defining JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON to 1.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n #include <nlohmann/json.hpp>\n Implicit conversions via operator ValueType will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get, get_to, get_ref, or get_ptr.
nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n nlohmann::json j = \"Hello, world!\";\nstd::string s;\nj.get_to(s);\n You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
literals for UDLs","text":"The user-defined string literals operator\"\"_json and operator\"\"_json_pointer will be removed from the global namespace in the next major release of the library.
nlohmann::json j = \"[1,2,3]\"_json;\n using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.
The nlohmann namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use nlohmann as namespace or, when the exact version and configuration is relevant, use macro NLOHMANN_JSON_NAMESPACE to denote the namespace.
void to_json(nlohmann::json_abi_v3_11_2::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n void to_json(nlohmann::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n void to_json(NLOHMANN_JSON_NAMESPACE::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n"},{"location":"integration/migration_guide/#do-not-use-the-details-namespace","title":"Do not use the details namespace","text":"The details namespace is not part of the public API of the library and can change in any version without announcement. Do not rely on any function or type in the details namespace.
Throughout this page, we will describe how to compile the example file example.cpp below.
#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n When executed, this program should create output similar to
{\n \"compiler\": {\n \"c++\": \"201103\",\n \"family\": \"gcc\",\n \"version\": \"12.3.0\"\n },\n \"copyright\": \"(C) 2013-2022 Niels Lohmann\",\n \"name\": \"JSON for Modern C++\",\n \"platform\": \"apple\",\n \"url\": \"https://github.com/nlohmann/json\",\n \"version\": {\n \"major\": 3,\n \"minor\": 11,\n \"patch\": 3,\n \"string\": \"3.11.3\"\n }\n}\n"},{"location":"integration/package_managers/#homebrew","title":"Homebrew","text":"Summary
formula: nlohmann-json
--HEAD parameter)If you are using Homebrew, you can install the library with
brew install nlohmann-json\n The header can be used directly in your code or via CMake.
Example: Raw compilationCreate the following file:
example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Install the package:
brew install nlohmann-json\n Compile the code and pass the Homebrew prefix to the include path such that the library can be found:
c++ example.cpp -I$(brew --prefix nlohmann-json)/include -std=c++11 -o example\n Create the following files:
example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n Install the package:
brew install nlohmann-json\n Compile the code and pass the Homebrew prefix to CMake to find installed packages via find_package:
CMAKE_PREFIX_PATH=$(brew --prefix) cmake -S . -B build\ncmake --build build\n Summary
wrap: nlohmann_json
meson.build.If you are using the Meson Build System, add this source tree as a meson subproject. You may also use the include.zip published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB, or simply use
meson wrap install nlohmann_json\n Please see the Meson project for any issues regarding the packaging.
The provided meson.build can also be used as an alternative to CMake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly.
Create the following files:
meson.buildproject('json_example', 'cpp',\n version: '1.0',\n default_options: ['cpp_std=c++11']\n)\n\ndependency_json = dependency('nlohmann_json', required: true)\n\nexecutable('json_example',\n sources: ['example.cpp'],\n dependencies: [dependency_json],\n install: true\n)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Use the Meson WrapDB to fetch the nlohmann/json wrap:
mkdir subprojects\nmeson wrap install nlohmann_json\n Build:
meson setup build\nmeson compile -C build\n Summary
use http_archive, git_repository, or local_repository
WORKSPACE fileThis repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive, git_repository, or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g., via deps attribute).
Create the following files:
BUILDcc_binary(\n name = \"main\",\n srcs = [\"example.cpp\"],\n deps = [\"@nlohmann_json//:json\"],\n)\n WORKSPACEload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\nhttp_archive(\n name = \"nlohmann_json\",\n urls = [\"https://github.com/nlohmann/json/archive/refs/tags/v3.11.3.tar.gz\"],\n strip_prefix = \"json-3.11.3\",\n)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Build and run:
bazel build //:main\nbazel run //:main\n Summary
recipe: nlohmann_json
If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile's requires, where x.y.z is the release version you want to use.
Create the following files:
Conanfile.txt[requires]\nnlohmann_json/3.11.3\n\n[generators]\nCMakeToolchain\nCMakeDeps\n CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Call Conan:
conan install . --output-folder=build --build=missing\n Build:
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=\"conan_toolchain.cmake\" -DCMAKE_BUILD_TYPE=Release\ncmake --build build\n Summary
package: nlohmann-json
If you are using Spack to manage your dependencies, you can use the nlohmann-json package via
spack install nlohmann-json\n Please see the Spack project for any issues regarding the packaging.
ExampleCreate the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Install the library:
spack install nlohmann-json\n Load the environment for your Spack-installed packages:
spack load nlohmann-json\n Build the project with CMake:
cmake -S . -B build -DCMAKE_PREFIX_PATH=$(spack location -i nlohmann-json)\ncmake --build build\n Summary
package: nlohmann_json
If you are using Hunter on your project for external dependencies, then you can use the nlohmann_json package via
hunter_add_package(nlohmann_json)\n Please see the Hunter project for any issues regarding the packaging.
ExampleCreate the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\n\ninclude(\"cmake/HunterGate.cmake\")\nHunterGate(\n URL \"https://github.com/cpp-pm/hunter/archive/v0.23.297.tar.gz\"\n SHA1 \"3319fe6a3b08090df7df98dee75134d68e2ef5a3\"\n)\n\nproject(json_example)\n\nhunter_add_package(nlohmann_json)\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Download required files
mkdir cmake\nwget https://raw.githubusercontent.com/cpp-pm/gate/master/cmake/HunterGate.cmake -O cmake/HunterGate.cmake\n Build the project with CMake:
cmake -S . -B build\ncmake --build build\n If you are using Buckaroo, you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json. There is a demo repo here.
Warning
The module is outdated as the respective repository has not been updated in years.
"},{"location":"integration/package_managers/#vcpkg","title":"vcpkg","text":"Summary
package: nlohmann-json
If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with
vcpkg install nlohmann-json\n and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging.
ExampleCreate the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Install package:
vcpkg install nlohmann-json\n Build:
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake\ncmake --build build\n Summary
package: nlohmann/json
If you are using cget, you can install the latest master version with
cget install nlohmann/json\n A specific version can be installed with cget install nlohmann/json@v3.11.3. Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON).
Create the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Initialize cget
cget init\n Install the library
cget install nlohmann/json\n Build
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=cget/cget/cget.cmake\ncmake --build build\n If you are using CocoaPods, you can use the library by adding pod \"nlohmann_json\", '~>3.1.2' to your podfile (see an example). Please file issues here.
If you are using NuGet, you can use the package nlohmann.json. Please check this extensive description on how to use the package. Please file issues here.
"},{"location":"integration/package_managers/#conda","title":"Conda","text":"If you are using conda, you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json. Please file issues here.
If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages.
The package is updated automatically.
"},{"location":"integration/package_managers/#macports","title":"MacPorts","text":"If you are using MacPorts, execute sudo port install nlohmann-json to install the nlohmann-json package.
The package is updated automatically.
"},{"location":"integration/package_managers/#build2","title":"build2","text":"If you are using build2, you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository. In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints). If you are not familiar with using dependencies in build2, please read this introduction. Please file issues here if you experience problems with the packages.
The package is updated automatically.
"},{"location":"integration/package_managers/#wsjcpp","title":"wsjcpp","text":"If you are using wsjcpp, you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch.
wsjcpp reads directly from the GitHub repository and is always up-to-date.
"},{"location":"integration/package_managers/#cpmcmake","title":"CPM.cmake","text":"If you are using CPM.cmake, you can check this example. After adding CPM script to your project, implement the following snippet to your CMake:
CPMAddPackage(\"gh:nlohmann/json@3.11.3\")\n Example mkdir -p cmake\nwget -O cmake/CPM.cmake https://github.com/cpm-cmake/CPM.cmake/releases/latest/download/get_cpm.cmake\n cmake -S . -B build\ncmake --build build\n"},{"location":"integration/pkg-config/","title":"Pkg-config","text":"If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed:
pkg-config nlohmann_json --cflags\n Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config:
json = dependency('nlohmann_json', required: true)\n"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"JSON for Modern C++","text":""},{"location":"api/json/","title":"nlohmann::json","text":"using json = basic_json<>;\n This type is the default specialization of the basic_json class which uses the standard template types.
"},{"location":"api/json/#examples","title":"Examples","text":"ExampleThe 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
parse_error.101 in case of an unexpected token.parse_error.102 if to_unicode fails or surrogate error.parse_error.103 if to_unicode fails.Linear in the length of the input. The parser is a predictive LL(1) parser.
"},{"location":"api/operator_gtgt/#notes","title":"Notes","text":"A UTF-8 byte order mark is silently ignored.
Deprecation
This function replaces function std::istream& operator<<(basic_json& j, std::istream& i) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i; with i >> j;.
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":"json operator \"\"_json(const char* s, std::size_t n);\n This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred.
It is recommended to bring the operator into scope using any of the following lines:
using nlohmann::literals::operator \"\"_json;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS for details.
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
The function can throw anything that parse(s, s+n) would throw.
Linear.
"},{"location":"api/operator_literal_json/#examples","title":"Examples","text":"ExampleThe following code shows how to create JSON values from string literals.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n json j = R\"( {\"hello\": \"world\", \"answer\": 42} )\"_json;\n\n std::cout << std::setw(2) << j << '\\n';\n}\n Output:
{\n \"answer\": 42,\n \"hello\": \"world\"\n}\n"},{"location":"api/operator_literal_json/#version-history","title":"Version history","text":"nlohmann::literals::json_literals in 3.11.0.json_pointer operator \"\"_json_pointer(const char* s, std::size_t n);\n This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred.
It is recommended to bring the operator into scope using any of the following lines:
using nlohmann::literals::operator \"\"_json_pointer;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS for details."},{"location":"api/operator_literal_json_pointer/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON Pointer n (in) length of string s"},{"location":"api/operator_literal_json_pointer/#return-value","title":"Return value","text":"json_pointer value parsed from s
The function can throw anything that json_pointer::json_pointer would throw.
Linear.
"},{"location":"api/operator_literal_json_pointer/#examples","title":"Examples","text":"ExampleThe 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":"nlohmann::literals::json_literals in 3.11.0.std::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)\n j to the output stream o. The JSON value will be serialized using the dump member function.width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).fill of the output stream o. For instance, the manipulator std::setfill('\\\\t') sets indentation to use a tab character rather than the default space character.ptr to the output stream o. The string representation is obtained using the to_string member function.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
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.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;.
The example below shows the serialization with different parameters to width to adjust the indentation level.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // serialize without indentation\n std::cout << j_object << \"\\n\\n\";\n std::cout << j_array << \"\\n\\n\";\n\n // serialize with indentation\n std::cout << std::setw(4) << j_object << \"\\n\\n\";\n std::cout << std::setw(2) << j_array << \"\\n\\n\";\n std::cout << std::setw(1) << std::setfill('\\t') << j_object << \"\\n\\n\";\n}\n Output:
{\"one\":1,\"two\":2}\n\n[1,2,4,8,16]\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\n{\n \"one\": 1,\n \"two\": 2\n}\n Example: (2) write JSON pointer to stream The example below shows how to write a JSON pointer to a stream.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON poiner\n json::json_pointer ptr(\"/foo/bar/baz\");\n\n // write string representation to stream\n std::cout << ptr << std::endl;\n}\n Output:
/foo/bar/baz\n"},{"location":"api/operator_ltlt/#version-history","title":"Version history","text":"std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.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.
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":"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>).
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.
Key)T)std::vector<std::pair<const Key, T>, Allocator>)std::equal_to<Key> // until C++14\n\nstd::equal_to<> // since C++14\nThe 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":"nlohmann::ordered_json.template<typename, typename>\nstruct adl_serializer;\n Serializer that uses ADL (Argument-Dependent Lookup) to choose to_json/from_json functions from the types' namespaces.
It is implemented similar to
template<typename ValueType>\nstruct adl_serializer {\n template<typename BasicJsonType>\n static void to_json(BasicJsonType& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n template<typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n"},{"location":"api/adl_serializer/#member-functions","title":"Member functions","text":"// (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).
j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"Copy of the JSON value, converted to ValueType
The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when template get<ns::person>() is called.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid from_json(const json& j, person& p)\n{\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n}\n} // namespace ns\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n Example: (2) Non-default-constructible type The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n"},{"location":"api/adl_serializer/from_json/#see-also","title":"See also","text":"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":"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":"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.
The class satisfies the following concept requirements:
"},{"location":"api/basic_json/#basic","title":"Basic","text":"==, see operator==.<, see operator<.swap.std::nullptr_t objects which are used to model the null value.basic_json valuesbasic_json classvalue_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":"Functions to inspect the type of a JSON value.
Direct access to the stored value of a JSON value.
Access to the JSON value
to_string function for JSON valuesThe 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":"// (1)\ntemplate<typename InputType>\nstatic bool accept(InputType&& i,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic bool accept(IteratorType first, IteratorType last,\n const bool ignore_comments = false);\n Checks whether the input is valid JSON.
Reads from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.
InputType A compatible input, for instance:
std::istream objectFILE pointer (throws if null)std::stringobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type, for instance.
std::string::iterator or std::vector<std::uint8_t>::iteratorptr and ptr + leni (in) Input to parse from. ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"Whether the input is valid JSON.
"},{"location":"api/basic_json/accept/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/accept/#exceptions","title":"Exceptions","text":"Throws parse_error.101 in case of an empty input like a null FILE* or char* pointer.
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":"ExampleThe 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":"ignore_comments added in version 3.9.0.FILE* null pointers to exception in version 3.11.4.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.
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.
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.
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:
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":"basic_json(initializer_list_t) - create a JSON value from an initializer listobject - create a JSON object value from an initializer listusing 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.
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.
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":"// (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 idx, with bounds checking.key, with bounds checking.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr, with bounds checking.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":"idxkeykeyptrStrong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/at/#exceptions","title":"Exceptions","text":"type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.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":"operator[] for unchecked access by referencevalue for access with default valuereference back();\n\nconst_reference back() const;\n Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to
auto tmp = c.end();\n--tmp;\nreturn *tmp;\n"},{"location":"api/basic_json/back/#return-value","title":"Return value","text":"In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.
"},{"location":"api/basic_json/back/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/back/#exceptions","title":"Exceptions","text":"If the JSON value is null, exception invalid_iterator.214 is thrown.
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.
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":"// (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 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 nullnull boolean false string \"\" number 0 object {} array [] binary empty array The postcondition of this constructor can be restored by calling clear().
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.
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:
array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.string_t, string literals, and all compatible string containers can be used.number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.boolean_t / bool can be used.binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type.See the examples below.
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.
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:
{} is created.The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
{} which is exactly an empty JSON object.With the rules described above, the following JSON values cannot be expressed by an initializer list:
[]): use array(initializer_list_t) with an empty initializer list in this casearray(initializer_list_t) with the same initializer list in this caseFunction array() and object() force array and object creation from initializer lists, respectively.
Constructs a JSON array value by creating cnt copies of a passed value. In case cnt is 0, an empty array is created.
Constructs the JSON value with the contents of the range [first, last). The semantics depends on the different types a JSON value can have:
null type, invalid_iterator.206 is thrown.first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.Creates a copy of a given JSON value.
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.
CompatibleType a type such that:
CompatibleType is not derived from std::istream,CompatibleType is not basic_json (to avoid hijacking copy/move constructors),CompatibleType is not a different basic_json type (i.e. with different template arguments)CompatibleType is not a basic_json nested type (e.g., json_pointer, iterator, etc.)json_serializer<U> (with U = uncvref_t<CompatibleType>) has a to_json(basic_json_t&, CompatibleType&&) methodBasicJsonType: a type such that:
BasicJsonType is a basic_json type.BasicJsonType has different template arguments than basic_json_t.U: uncvref_t<CompatibleType>"},{"location":"api/basic_json/basic_json/#parameters","title":"Parameters","text":"v (in) the type of the value to create val (in) the value to be forwarded to the respective constructor init (in) initializer list with JSON values type_deduction (in) internal parameter; when set to true, the type of the JSON value is deducted from the initializer list init; when set to false, the type provided via manual_type is forced. This mode is used by the functions array(initializer_list_t) and object(initializer_list_t). manual_type (in) internal parameter; when type_deduction is set to false, the created JSON value will use the provided type (only value_t::array and value_t::object are valid); when type_deduction is set to true, this parameter has no effect cnt (in) the number of JSON copies of val to create first (in) begin of the range to copy from (included) last (in) end of the range to copy from (excluded) other (in) the JSON value to copy/move"},{"location":"api/basic_json/basic_json/#exception-safety","title":"Exception safety","text":"to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.type_error.301 if type_deduction is false, manual_type is value_t::object, but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.val, also depending on the implementation of the called to_json() method.val, also depending on the implementation of the called to_json() method.init.cnt.first and last.other.Overload 5:
Empty initializer list
When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value.
Overload 7:
Preconditions
first and last must be initialized. **This precondition is enforced with a runtime assertion.[first, last) is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior.Runtime assertion
A precondition is enforced with a runtime assertion.
Overload 8:
Postcondition
*this == other
Overload 9:
Postconditions
`*this has the same value as other before the call.other is a JSON null valueThe 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 listThe example below shows how JSON values are created from initializer lists.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_empty_init_list = json({});\n json j_object = { {\"one\", 1}, {\"two\", 2} };\n json j_array = {1, 2, 3, 4};\n json j_nested_object = { {\"one\", {1}}, {\"two\", {1, 2}} };\n json j_nested_array = { {{1}, \"one\"}, {{1, 2}, \"two\"} };\n\n // serialize the JSON value\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_nested_object << '\\n';\n std::cout << j_nested_array << '\\n';\n}\n Output:
{}\n{\"one\":1,\"two\":2}\n[1,2,3,4]\n{\"one\":[1],\"two\":[1,2]}\n[[[1],\"one\"],[[1,2],\"two\"]]\n Example: (6) construct an array with count copies of given value The following code shows examples for creating arrays with several copies of a given value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array by creating copies of a JSON value\n json value = \"Hello\";\n json array_0 = json(0, value);\n json array_1 = json(1, value);\n json array_5 = json(5, value);\n\n // serialize the JSON arrays\n std::cout << array_0 << '\\n';\n std::cout << array_1 << '\\n';\n std::cout << array_5 << '\\n';\n}\n Output:
[]\n[\"Hello\"]\n[\"Hello\",\"Hello\",\"Hello\",\"Hello\",\"Hello\"]\n Example: (7) construct a JSON container given an iterator range The example below shows several ways to create JSON values by specifying a subrange with iterators.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_array = {\"alpha\", \"bravo\", \"charly\", \"delta\", \"easy\"};\n json j_number = 42;\n json j_object = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n\n // create copies using iterators\n json j_array_range(j_array.begin() + 1, j_array.end() - 2);\n json j_number_range(j_number.begin(), j_number.end());\n json j_object_range(j_object.begin(), j_object.find(\"two\"));\n\n // serialize the values\n std::cout << j_array_range << '\\n';\n std::cout << j_number_range << '\\n';\n std::cout << j_object_range << '\\n';\n\n // example for an exception\n try\n {\n json j_invalid(j_number.begin() + 1, j_number.end());\n }\n catch (const json::invalid_iterator& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[\"bravo\",\"charly\"]\n42\n{\"one\":\"eins\"}\n[json.exception.invalid_iterator.204] iterators out of range\n Example: (8) copy constructor The following code shows an example for the copy constructor.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j1 = {\"one\", \"two\", 3, 4.5, false};\n\n // create a copy\n json j2(j1);\n\n // serialize the JSON array\n std::cout << j1 << \" = \" << j2 << '\\n';\n std::cout << std::boolalpha << (j1 == j2) << '\\n';\n}\n Output:
[\"one\",\"two\",3,4.5,false] = [\"one\",\"two\",3,4.5,false]\ntrue\n Example: (9) move constructor The code below shows the move constructor explicitly called via std::move.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json a = 23;\n\n // move contents of a to b\n json b(std::move(a));\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n Output:
null\n23\n"},{"location":"api/basic_json/basic_json/#version-history","title":"Version history","text":"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":"ExampleThe 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":"// (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 Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"JSON binary array value
"},{"location":"api/basic_json/binary/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/binary/#complexity","title":"Complexity","text":"Linear in the size of init; constant for typename binary_t::container_type&& init versions.
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.
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":"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++.
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>.
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.
CBOR
MessagePack
BSON
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":"std::uint64_t in version 3.10.0.using boolean_t = BooleanType;\n The type used to store JSON booleans.
RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.
To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.
With the default values for BooleanType (bool), the default value for boolean_t is bool.
Boolean values are stored directly inside a basic_json type.
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":"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":"ExampleThe 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":"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:
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":"store in 3.10.0.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":"ExampleThe 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":"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():
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":"ExampleThe 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":"// (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 key. If the element is not found or the JSON value is not an object, false is returned.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr can be resolved in the current JSON value.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":"true if an element with specified key exists. If no such element with such key is found or the JSON value is not an object, false is returned.true if the JSON pointer can be resolved to a stored value, false otherwise.Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/contains/#exceptions","title":"Exceptions","text":"parse_error.106 if an array index begins with 0.parse_error.109 if an array index was not a number.Logarithmic in the size of the JSON object.
"},{"location":"api/basic_json/contains/#notes","title":"Notes","text":"false when executed on a JSON type that is not an object.Postconditions
If j.contains(x) returns true for a key or JSON pointer x, then it is safe to call j[x].
The example shows how contains() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create some JSON values\n json j_object = R\"( {\"key\": \"value\"} )\"_json;\n json j_array = R\"( [1, 2, 3] )\"_json;\n\n // call contains\n std::cout << std::boolalpha <<\n \"j_object contains 'key': \" << j_object.contains(\"key\") << '\\n' <<\n \"j_object contains 'another': \" << j_object.contains(\"another\") << '\\n' <<\n \"j_array contains 'key': \" << j_array.contains(\"key\") << std::endl;\n}\n Output:
j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n Example: (2) check with key using string_view The example shows how contains() is used.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create some JSON values\n json j_object = R\"( {\"key\": \"value\"} )\"_json;\n json j_array = R\"( [1, 2, 3] )\"_json;\n\n // call contains\n std::cout << std::boolalpha <<\n \"j_object contains 'key': \" << j_object.contains(\"key\"sv) << '\\n' <<\n \"j_object contains 'another': \" << j_object.contains(\"another\"sv) << '\\n' <<\n \"j_array contains 'key': \" << j_array.contains(\"key\"sv) << std::endl;\n}\n Output:
j_object contains 'key': true\nj_object contains 'another': false\nj_array contains 'key': false\n Example: (3) check with JSON pointer The example shows how contains() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n std::cout << std::boolalpha\n << j.contains(\"/number\"_json_pointer) << '\\n'\n << j.contains(\"/string\"_json_pointer) << '\\n'\n << j.contains(\"/array\"_json_pointer) << '\\n'\n << j.contains(\"/array/1\"_json_pointer) << '\\n'\n << j.contains(\"/array/-\"_json_pointer) << '\\n'\n << j.contains(\"/array/4\"_json_pointer) << '\\n'\n << j.contains(\"/baz\"_json_pointer) << std::endl;\n\n try\n {\n // try to use an array index with leading '0'\n j.contains(\"/array/01\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n try\n {\n // try to use an array index that is not a number\n j.contains(\"/array/one\"_json_pointer);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
true\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/contains/#version-history","title":"Version history","text":"KeyType to support comparable types in version 3.11.0.// (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 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).KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.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.
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.
The example shows how count() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call count()\n auto count_two = j_object.count(\"two\");\n auto count_three = j_object.count(\"three\");\n\n // print values\n std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n Output:
number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n Example: (2) count number of elements using string_view The example shows how count() is used.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call count()\n auto count_two = j_object.count(\"two\"sv);\n auto count_three = j_object.count(\"three\"sv);\n\n // print values\n std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n Output:
number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n"},{"location":"api/basic_json/count/#version-history","title":"Version history","text":"key type to KeyType&& in version 3.11.0.const_reverse_iterator crbegin() const noexcept;\n Returns an iterator to the reverse-beginning; that is, the last element.
"},{"location":"api/basic_json/crbegin/#return-value","title":"Return value","text":"reverse iterator to the first element
"},{"location":"api/basic_json/crbegin/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/crbegin/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/crbegin/#examples","title":"Examples","text":"ExampleThe 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":"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":"ExampleThe following code shows an example for eend().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-end\n json::const_reverse_iterator it = array.crend();\n\n // increment the iterator to point to the first element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n Output:
1\n"},{"location":"api/basic_json/crend/#version-history","title":"Version history","text":"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.
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":"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
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.
Currently, only remove, add, and replace operations are generated.
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":"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.
indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are three possible values (see error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged))."},{"location":"api/basic_json/dump/#return-value","title":"Return value","text":"string containing the serialization of the JSON value
"},{"location":"api/basic_json/dump/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/dump/#exceptions","title":"Exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict
Linear.
"},{"location":"api/basic_json/dump/#notes","title":"Notes","text":"Binary values are serialized as object containing two keys:
null if the binary has no subtypeThe following example shows the effect of different indent, indent_char, and ensure_ascii parameters to the result of the serialization.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hell\u00f6 \ud83d\ude00!\";\n\n // call dump()\n std::cout << \"objects:\" << '\\n'\n << j_object.dump() << \"\\n\\n\"\n << j_object.dump(-1) << \"\\n\\n\"\n << j_object.dump(0) << \"\\n\\n\"\n << j_object.dump(4) << \"\\n\\n\"\n << j_object.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"arrays:\" << '\\n'\n << j_array.dump() << \"\\n\\n\"\n << j_array.dump(-1) << \"\\n\\n\"\n << j_array.dump(0) << \"\\n\\n\"\n << j_array.dump(4) << \"\\n\\n\"\n << j_array.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"strings:\" << '\\n'\n << j_string.dump() << '\\n'\n << j_string.dump(-1, ' ', true) << '\\n';\n\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"\u00e4\\xA9\u00fc\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}\n Output:
objects:\n{\"one\":1,\"two\":2}\n\n{\"one\":1,\"two\":2}\n\n{\n\"one\": 1,\n\"two\": 2\n}\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\n{\n \"one\": 1,\n \"two\": 2\n}\n\narrays:\n[1,2,4,8,16]\n\n[1,2,4,8,16]\n\n[\n1,\n2,\n4,\n8,\n16\n]\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\n[\n 1,\n 2,\n 4,\n 8,\n 16\n]\n\nstrings:\n\"Hell\u00f6 \ud83d\ude00!\"\n\"Hell\\u00f6 \\ud83d\\ude00!\"\n[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n"},{"location":"api/basic_json/dump/#version-history","title":"Version history","text":"indent_char, option ensure_ascii and exceptions added in version 3.0.0.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.
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.
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.
Throws type_error.311 when called on a type other than JSON object or null; example: \"cannot use emplace() with number\"
Logarithmic in the size of the container, O(log(size())).
The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n auto res1 = object.emplace(\"three\", 3);\n null.emplace(\"A\", \"a\");\n null.emplace(\"B\", \"b\");\n\n // the following call will not add an object, because there is already\n // a value stored at key \"B\"\n auto res2 = null.emplace(\"B\", \"c\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << *res1.first << \" \" << std::boolalpha << res1.second << '\\n';\n\n std::cout << null << '\\n';\n std::cout << *res2.first << \" \" << std::boolalpha << res2.second << '\\n';\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"one\":1,\"three\":3,\"two\":2}\n3 true\n{\"A\":\"a\",\"B\":\"b\"}\n\"b\" false\n"},{"location":"api/basic_json/emplace/#version-history","title":"Version history","text":"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.
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.
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\"
Amortized constant.
"},{"location":"api/basic_json/emplace_back/#examples","title":"Examples","text":"ExampleThe 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":"bool empty() const noexcept;\n Checks if a JSON value has no elements (i.e. whether its size() is 0).
The return value depends on the different types and is defined as follows:
Value type return value nulltrue 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.
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.
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":"false for binary types in version 3.8.0.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":"ExampleThe 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":"// (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 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.
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.
Removes an element from a JSON object by key.
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.
Removes an element from a JSON array by index.
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":"pos refers to the last element, the end() iterator is returned.last refers to the last element, the end() iterator is returned.ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/erase/#exceptions","title":"Exceptions","text":"type_error.307 if called on a null value; example: \"cannot use erase() with null\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: \"iterator out of range\"type_error.307 if called on a null value; example: \"cannot use erase() with null\"invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: \"iterators do not fit current value\"invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: \"iterators out of range\"type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"out_of_range.401 when idx >= size(); example: \"array index 17 is out of range\"pos and the end of the containerlog(size()) + std::distance(first, last)first and last, plus linear in the distance between last and end of the containerlog(size()) + count(key)log(size()) + count(key)idx and the end of the container.erase, including the end() iterator.The example shows the effect of erase() for different JSON types using an iterator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call erase()\n j_boolean.erase(j_boolean.begin());\n j_number_integer.erase(j_number_integer.begin());\n j_number_float.erase(j_number_float.begin());\n j_object.erase(j_object.find(\"two\"));\n j_array.erase(j_array.begin() + 2);\n j_string.erase(j_string.begin());\n\n // print values\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n Output:
null\nnull\nnull\n{\"one\":1}\n[1,2,8,16]\nnull\n Example: (2) remove elements given an iterator range The example shows the effect of erase() for different JSON types using an iterator range.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call erase()\n j_boolean.erase(j_boolean.begin(), j_boolean.end());\n j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());\n j_number_float.erase(j_number_float.begin(), j_number_float.end());\n j_object.erase(j_object.find(\"two\"), j_object.end());\n j_array.erase(j_array.begin() + 1, j_array.begin() + 3);\n j_string.erase(j_string.begin(), j_string.end());\n\n // print values\n std::cout << j_boolean << '\\n';\n std::cout << j_number_integer << '\\n';\n std::cout << j_number_float << '\\n';\n std::cout << j_object << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_string << '\\n';\n}\n Output:
null\nnull\nnull\n{\"one\":1}\n[1,8,16]\nnull\n Example: (3) remove element from a JSON object given a key The example shows the effect of erase() for different JSON types using an object key.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call erase()\n auto count_one = j_object.erase(\"one\");\n auto count_three = j_object.erase(\"three\");\n\n // print values\n std::cout << j_object << '\\n';\n std::cout << count_one << \" \" << count_three << '\\n';\n}\n Output:
{\"two\":2}\n1 0\n Example: (4) remove element from a JSON object given a key using string_view The example shows the effect of erase() for different JSON types using an object key.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n // call erase()\n auto count_one = j_object.erase(\"one\"sv);\n auto count_three = j_object.erase(\"three\"sv);\n\n // print values\n std::cout << j_object << '\\n';\n std::cout << count_one << \" \" << count_three << '\\n';\n}\n Output:
{\"two\":2}\n1 0\n Example: (5) remove element from a JSON array given an index The example shows the effect of erase() using an array index.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j_array = {0, 1, 2, 3, 4, 5};\n\n // call erase()\n j_array.erase(2);\n\n // print values\n std::cout << j_array << '\\n';\n}\n Output:
[0,1,3,4,5]\n"},{"location":"api/basic_json/erase/#version-history","title":"Version history","text":"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:
type_error exception in case of invalid UTF-8 replace replace invalid UTF-8 sequences with U+FFFD (\ufffd REPLACEMENT CHARACTER) ignore ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged"},{"location":"api/basic_json/error_handler_t/#examples","title":"Examples","text":"Example The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"\u00e4\\xA9\u00fc\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}\n Output:
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n"},{"location":"api/basic_json/error_handler_t/#version-history","title":"Version history","text":"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:
parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsTo 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.
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":"// (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 key. If the element is not found or the JSON value is not an object, end() is returned.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.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.
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.
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":"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.
an object that maps JSON pointers to primitive values
"},{"location":"api/basic_json/flatten/#exception-safety","title":"Exception safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/flatten/#complexity","title":"Complexity","text":"Linear in the size the JSON value.
"},{"location":"api/basic_json/flatten/#notes","title":"Notes","text":"Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.
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":"// (1)\ntemplate<typename InputType>\nstatic basic_json from_bjdata(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_bjdata(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_bjdata/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bjdata/#parameters","title":"Parameters","text":"i (in) an input in BJData format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bjdata/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_bjdata/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_bjdata/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in BJData format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with BJData\n json j = json::from_bjdata(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_bjdata/#version-history","title":"Version history","text":"// (1)\ntemplate<typename InputType>\nstatic basic_json from_bson(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_bson(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_bson/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_bson/#parameters","title":"Parameters","text":"i (in) an input in BSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_bson/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_bson/#exceptions","title":"Exceptions","text":"Throws parse_error.114 if an unsupported BSON record type is encountered.
Linear in the size of the input.
"},{"location":"api/basic_json/from_bson/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in BSON format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d,\n 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73,\n 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00\n };\n\n // deserialize it with BSON\n json j = json::from_bson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_bson/#see-also","title":"See also","text":"Deprecation
from_bson with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_bson(ptr, len, ...); with from_bson(ptr, ptr+len, ...);.from_bson 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 from_bson({ptr, ptr+len}, ...); with from_bson(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)\ntemplate<typename InputType>\nstatic basic_json from_cbor(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);\n\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_cbor(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error);\n Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_cbor/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_cbor/#parameters","title":"Parameters","text":"i (in) an input in CBOR format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) tag_handler (in) how to treat CBOR tags (optional, error by default); see cbor_tag_handler_t for more information"},{"location":"api/basic_json/from_cbor/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_cbor/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_cbor/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in CBOR format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with CBOR\n json j = json::from_cbor(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_cbor/#version-history","title":"Version history","text":"start_index since version 2.1.1.start_index parameter, and added strict parameter in version 3.0.0.allow_exceptions parameter in version 3.2.0.tag_handler parameter in version 3.9.0.Deprecation
from_cbor with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_cbor(ptr, len, ...); with from_cbor(ptr, ptr+len, ...);.from_cbor 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 from_cbor({ptr, ptr+len}, ...); with from_cbor(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)\ntemplate<typename InputType>\nstatic basic_json from_msgpack(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_msgpack(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the MessagePack serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_msgpack/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_msgpack/#parameters","title":"Parameters","text":"i (in) an input in MessagePack format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_msgpack/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_msgpack/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_msgpack/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in MessagePack format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_msgpack/#version-history","title":"Version history","text":"start_index since version 2.1.1.start_index parameter, and added strict parameter in version 3.0.0.allow_exceptions parameter in version 3.2.0.Deprecation
from_msgpack with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_msgpack(ptr, len, ...); with from_msgpack(ptr, ptr+len, ...);.from_cbor 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 from_msgpack({ptr, ptr+len}, ...); with from_msgpack(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
// (1)\ntemplate<typename InputType>\nstatic basic_json from_ubjson(InputType&& i,\n const bool strict = true,\n const bool allow_exceptions = true);\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json from_ubjson(IteratorType first, IteratorType last,\n const bool strict = true,\n const bool allow_exceptions = true);\n Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/from_ubjson/#template-parameters","title":"Template parameters","text":"InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type"},{"location":"api/basic_json/from_ubjson/#parameters","title":"Parameters","text":"i (in) an input in UBJSON format convertible to an input adapter first (in) iterator to start of the input last (in) iterator to end of the input strict (in) whether to expect the input to be consumed until EOF (true by default) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default)"},{"location":"api/basic_json/from_ubjson/#return-value","title":"Return value","text":"deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/from_ubjson/#exceptions","title":"Exceptions","text":"strict was set to trueLinear in the size of the input.
"},{"location":"api/basic_json/from_ubjson/#examples","title":"Examples","text":"ExampleThe example shows the deserialization of a byte vector in UBJSON format to a JSON value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with UBJSON\n json j = json::from_ubjson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"api/basic_json/from_ubjson/#version-history","title":"Version history","text":"allow_exceptions parameter in version 3.2.0.Deprecation
from_ubjson with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like from_ubjson(ptr, len, ...); with from_ubjson(ptr, ptr+len, ...);.from_ubjson 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 from_ubjson({ptr, ptr+len}, ...); with from_ubjson(ptr, ptr+len, ...);.You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
reference front();\nconst_reference front() const;\n Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().
In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.
"},{"location":"api/basic_json/front/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/front/#exceptions","title":"Exceptions","text":"If the JSON value is null, exception invalid_iterator.214 is thrown.
Constant.
"},{"location":"api/basic_json/front/#notes","title":"Notes","text":"Precondition
The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.
The following code shows an example for front().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call front()\n //std::cout << j_null.front() << '\\n'; // would throw\n std::cout << j_boolean.front() << '\\n';\n std::cout << j_number_integer.front() << '\\n';\n std::cout << j_number_float.front() << '\\n';\n std::cout << j_object.front() << '\\n';\n //std::cout << j_object_empty.front() << '\\n'; // undefined behavior\n std::cout << j_array.front() << '\\n';\n //std::cout << j_array_empty.front() << '\\n'; // undefined behavior\n std::cout << j_string.front() << '\\n';\n}\n Output:
true\n17\n23.42\n1\n1\n\"Hello, world\"\n"},{"location":"api/basic_json/front/#see-also","title":"See also","text":"// (1)\ntemplate<typename ValueType>\nValueType get() const noexcept(\n noexcept(JSONSerializer<ValueType>::from_json(\n std::declval<const basic_json_t&>(), std::declval<ValueType&>())));\n\n// (2)\ntemplate<typename BasicJsonType>\nBasicJsonType get() const;\n\n// (3)\ntemplate<typename PointerType>\nPointerType get_ptr();\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing
ValueType ret;\nJSONSerializer<ValueType>::from_json(*this, ret);\nreturn ret;\n This overload is chosen if:
ValueType is not basic_json,json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&), andjson_serializer<ValueType> does not have a from_json() method of the form ValueType from_json(const basic_json&)If the type is not CopyConstructible and not DefaultConstructible, the value is converted by calling the json_serializer<ValueType> from_json() method.
The function is then equivalent to executing
return JSONSerializer<ValueTypeCV>::from_json(*this);\n This overload is chosen if:
ValueType is not basic_json andjson_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.
Overload for basic_json specializations. The function is equivalent to executing
return *this;\n Explicit pointer access to the internally stored JSON value. No copies are made.
ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get/#return-value","title":"Return value","text":"ValueType*this, converted into BasicJsonTypenullptr otherwiseDepends on what json_serializer<ValueType> from_json() method throws
Undefined behavior
Writing data to the pointee (overload 3) of the result yields an undefined state.
"},{"location":"api/basic_json/get/#examples","title":"Examples","text":"ExampleThe example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use explicit conversions\n auto v1 = json_types[\"boolean\"].template get<bool>();\n auto v2 = json_types[\"number\"][\"integer\"].template get<int>();\n auto v3 = json_types[\"number\"][\"integer\"].template get<short>();\n auto v4 = json_types[\"number\"][\"floating-point\"].template get<float>();\n auto v5 = json_types[\"number\"][\"floating-point\"].template get<int>();\n auto v6 = json_types[\"string\"].template get<std::string>();\n auto v7 = json_types[\"array\"].template get<std::vector<short>>();\n auto v8 = json_types.template get<std::unordered_map<std::string, json>>();\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n Output:
1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting pointers\n auto p1 = value.template get<const json::number_integer_t*>();\n auto p2 = value.template get<json::number_integer_t*>();\n auto p3 = value.template get<json::number_integer_t* const>();\n auto p4 = value.template get<const json::number_integer_t* const>();\n auto p5 = value.template get<json::number_float_t*>();\n\n // print the pointees\n std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\\n';\n std::cout << std::boolalpha << (p5 == nullptr) << '\\n';\n}\n Output:
17 17 17 17\ntrue\n"},{"location":"api/basic_json/get/#version-history","title":"Version history","text":"basic_json in version 3.2.0.static allocator_type get_allocator();\n Returns the allocator associated with the container.
"},{"location":"api/basic_json/get_allocator/#return-value","title":"Return value","text":"associated allocator
"},{"location":"api/basic_json/get_allocator/#examples","title":"Examples","text":"ExampleThe example shows how get_allocator() is used to created json values.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n auto alloc = json::get_allocator();\n using traits_t = std::allocator_traits<decltype(alloc)>;\n\n json* j = traits_t::allocate(alloc, 1);\n traits_t::construct(alloc, j, \"Hello, world!\");\n\n std::cout << *j << std::endl;\n\n traits_t::destroy(alloc, j);\n traits_t::deallocate(alloc, j, 1);\n}\n Output:
\"Hello, world!\"\n"},{"location":"api/basic_json/get_allocator/#version-history","title":"Version history","text":"binary_t& get_binary();\n\nconst binary_t& get_binary() const;\n Returns a reference to the stored binary value.
"},{"location":"api/basic_json/get_binary/#return-value","title":"Return value","text":"Reference to binary value.
"},{"location":"api/basic_json/get_binary/#exception-safety","title":"Exception safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/get_binary/#exceptions","title":"Exceptions","text":"Throws type_error.302 if the value is not binary
Constant.
"},{"location":"api/basic_json/get_binary/#examples","title":"Examples","text":"ExampleThe following code shows how to query a binary value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary vector\n std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};\n\n // create a binary JSON value with subtype 42\n json j = json::binary(vec, 42);\n\n // output type and subtype\n std::cout << \"type: \" << j.type_name() << \", subtype: \" << j.get_binary().subtype() << std::endl;\n}\n Output:
type: binary, subtype: 42\n"},{"location":"api/basic_json/get_binary/#version-history","title":"Version history","text":"template<typename PointerType>\nPointerType get_ptr() noexcept;\n\ntemplate<typename PointerType>\nconstexpr const PointerType get_ptr() const noexcept;\n Implicit pointer access to the internally stored JSON value. No copies are made.
"},{"location":"api/basic_json/get_ptr/#template-parameters","title":"Template parameters","text":"PointerType pointer type; must be a pointer to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Other types will not compile."},{"location":"api/basic_json/get_ptr/#return-value","title":"Return value","text":"pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/get_ptr/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/get_ptr/#notes","title":"Notes","text":"Undefined behavior
The pointer becomes invalid if the underlying JSON object changes.
Consider the following example code where the pointer ptr changes after the array is resized. As a result, reading or writing to ptr after the array change would be undefined behavior. The address of the first array element changes, because the underlying std::vector is resized after adding a fifth element.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j = {1, 2, 3, 4};\n auto* ptr = j[0].get_ptr<std::int64_t*>();\n std::cout << \"value at \" << ptr << \" is \" << *ptr << std::endl;\n\n j.push_back(5);\n\n ptr = j[0].get_ptr<std::int64_t*>();\n std::cout << \"value at \" << ptr << \" is \" << *ptr << std::endl;\n}\n Output:
value at 0x6000012fc1c8 is 1\nvalue at 0x6000029fc088 is 1\n"},{"location":"api/basic_json/get_ptr/#examples","title":"Examples","text":"Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting pointers\n auto p1 = value.get_ptr<const json::number_integer_t*>();\n auto p2 = value.get_ptr<json::number_integer_t*>();\n auto p3 = value.get_ptr<json::number_integer_t* const>();\n auto p4 = value.get_ptr<const json::number_integer_t* const>();\n auto p5 = value.get_ptr<json::number_float_t*>();\n\n // print the pointees\n std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\\n';\n std::cout << std::boolalpha << (p5 == nullptr) << '\\n';\n}\n Output:
17 17 17 17\ntrue\n"},{"location":"api/basic_json/get_ptr/#see-also","title":"See also","text":"template<typename ReferenceType>\nReferenceType get_ref();\n\ntemplate<typename ReferenceType>\nconst ReferenceType get_ref() const;\n Implicit reference access to the internally stored JSON value. No copies are made.
"},{"location":"api/basic_json/get_ref/#template-parameters","title":"Template parameters","text":"ReferenceType reference type; must be a reference to array_t, object_t, string_t, boolean_t, number_integer_t, or number_unsigned_t, number_float_t, or binary_t. Enforced by a static assertion."},{"location":"api/basic_json/get_ref/#return-value","title":"Return value","text":"reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise
Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/get_ref/#exceptions","title":"Exceptions","text":"Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: \"incompatible ReferenceType for get_ref, actual type is binary\".
Constant.
"},{"location":"api/basic_json/get_ref/#notes","title":"Notes","text":"Undefined behavior
The reference becomes invalid if the underlying JSON object changes.
"},{"location":"api/basic_json/get_ref/#examples","title":"Examples","text":"ExampleThe example shows several calls to get_ref().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON number\n json value = 17;\n\n // explicitly getting references\n auto r1 = value.get_ref<const json::number_integer_t&>();\n auto r2 = value.get_ref<json::number_integer_t&>();\n\n // print the values\n std::cout << r1 << ' ' << r2 << '\\n';\n\n // incompatible type throws exception\n try\n {\n auto r3 = value.get_ref<json::number_float_t&>();\n }\n catch (const json::type_error& ex)\n {\n std::cout << ex.what() << '\\n';\n }\n}\n Output:
17 17\n[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\n"},{"location":"api/basic_json/get_ref/#see-also","title":"See also","text":"template<typename ValueType>\nValueType& get_to(ValueType& v) const noexcept(\n noexcept(JSONSerializer<ValueType>::from_json(\n std::declval<const basic_json_t&>(), v)));\n Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer<ValueType> from_json() method.
The function is equivalent to executing
ValueType v;\nJSONSerializer<ValueType>::from_json(*this, v);\n This overload is chosen if:
ValueType is not basic_json,json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&)ValueType the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"the input parameter, allowing chaining calls
"},{"location":"api/basic_json/get_to/#exceptions","title":"Exceptions","text":"Depends on what json_serializer<ValueType> from_json() method throws
The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n bool v1;\n int v2;\n short v3;\n float v4;\n int v5;\n std::string v6;\n std::vector<short> v7;\n std::unordered_map<std::string, json> v8;\n\n // use explicit conversions\n json_types[\"boolean\"].get_to(v1);\n json_types[\"number\"][\"integer\"].get_to(v2);\n json_types[\"number\"][\"integer\"].get_to(v3);\n json_types[\"number\"][\"floating-point\"].get_to(v4);\n json_types[\"number\"][\"floating-point\"].get_to(v5);\n json_types[\"string\"].get_to(v6);\n json_types[\"array\"].get_to(v7);\n json_types.get_to(v8);\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n Output:
1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n"},{"location":"api/basic_json/get_to/#version-history","title":"Version history","text":"enum class input_format_t {\n json,\n cbor,\n msgpack,\n ubjson,\n bson,\n bjdata\n};\n This enumeration is used in the sax_parse function to choose the input format to parse:
The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // CBOR byte string\n std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse CBOR\n bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
binary(val=[...])\n\nresult: true\n"},{"location":"api/basic_json/input_format_t/#version-history","title":"Version history","text":"// (1)\niterator insert(const_iterator pos, const basic_json& val);\niterator insert(const_iterator pos, basic_json&& val);\n\n// (2)\niterator insert(const_iterator pos, size_type cnt, const basic_json& val);\n\n// (3)\niterator insert(const_iterator pos, const_iterator first, const_iterator last);\n\n// (4)\niterator insert(const_iterator pos, initializer_list_t ilist);\n\n// (5)\nvoid insert(const_iterator first, const_iterator last);\n val into array before iterator pos.cnt copies of val into array before iterator pos.[first, last) into array before iterator pos.ilist into array before iterator pos.[first, last) into object.For all cases where an element is added to an 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. Also, any iterator or reference after the insertion point will point to the same index which is now a different value.
For ordered_json, also adding an element to an object can yield a reallocation which again invalidates all iterators and all references. Also, any iterator or reference after the insertion point will point to the same index which is now a different value.
pos (in) iterator before which the content will be inserted; may be the end() iterator val (in) value to insert cnt (in) number of copies of val to insert first (in) begin of the range of elements to insert last (in) end of the range of elements to insert ilist (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"val.pos if cnt==0pos if first==lastpos if ilist is emptyStrong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/insert/#exceptions","title":"Exceptions","text":"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"invalid_iterator.211 if first or last are iterators into container for which insert is called; example: \"passed iterators may not belong to container\"type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"type_error.309 if called on JSON values other than objects; example: \"cannot use insert() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"pos and end of the container.cnt plus linear in the distance between pos and end of the container.std::distance(first, last) plus linear in the distance between pos and end of the container.ilist.size() plus linear in the distance between pos and end of the container.O(N*log(size() + N)), where N is the number of elements to insert.The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 10 before number 3\n auto new_pos = v.insert(v.begin() + 2, 10);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
10\n[1,2,10,3,4]\n Example (2): insert copies of element into array The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 7 copies of number 7 before number 3\n auto new_pos = v.insert(v.begin() + 2, 7, 7);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
7\n[1,2,7,7,7,7,7,7,7,3,4]\n Example (3): insert range of elements into array The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // create a JSON array to copy values from\n json v2 = {\"one\", \"two\", \"three\", \"four\"};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), v2.begin(), v2.end());\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
\"one\"\n[1,2,3,4,\"one\",\"two\",\"three\",\"four\"]\n Example (4): insert elements from initializer list into array The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), {7, 8, 9});\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n Output:
7\n[1,2,3,4,7,8,9]\n Example (5): insert range of elements into object The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create two JSON objects\n json j1 = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n json j2 = {{\"eleven\", \"elf\"}, {\"seventeen\", \"siebzehn\"}};\n\n // output objects\n std::cout << j1 << '\\n';\n std::cout << j2 << '\\n';\n\n // insert range from j2 to j1\n j1.insert(j2.begin(), j2.end());\n\n // output result of insert call\n std::cout << j1 << '\\n';\n}\n Output:
{\"one\":\"eins\",\"two\":\"zwei\"}\n{\"eleven\":\"elf\",\"seventeen\":\"siebzehn\"}\n{\"eleven\":\"elf\",\"one\":\"eins\",\"seventeen\":\"siebzehn\",\"two\":\"zwei\"}\n"},{"location":"api/basic_json/insert/#version-history","title":"Version history","text":"class invalid_iterator : public exception;\n This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx (see list of iterator errors).
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_invalid_iterator fill:#CCCCFF"},{"location":"api/basic_json/invalid_iterator/#member-functions","title":"Member functions","text":"The following code shows how a invalid_iterator exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling iterator::key() on non-object iterator\n json j = \"string\";\n json::iterator it = j.begin();\n auto k = it.key();\n }\n catch (const json::invalid_iterator& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n"},{"location":"api/basic_json/invalid_iterator/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errortype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsconstexpr bool is_array() const noexcept;\n This function returns true if and only if the JSON value is an array.
true if type is an array, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_array/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_array/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_array() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_array()\n std::cout << std::boolalpha;\n std::cout << j_null.is_array() << '\\n';\n std::cout << j_boolean.is_array() << '\\n';\n std::cout << j_number_integer.is_array() << '\\n';\n std::cout << j_number_unsigned_integer.is_array() << '\\n';\n std::cout << j_number_float.is_array() << '\\n';\n std::cout << j_object.is_array() << '\\n';\n std::cout << j_array.is_array() << '\\n';\n std::cout << j_string.is_array() << '\\n';\n std::cout << j_binary.is_array() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\n"},{"location":"api/basic_json/is_array/#version-history","title":"Version history","text":"constexpr bool is_binary() const noexcept;\n This function returns true if and only if the JSON value is binary array.
true if type is binary, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_binary/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_binary/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_binary() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_binary()\n std::cout << std::boolalpha;\n std::cout << j_null.is_binary() << '\\n';\n std::cout << j_boolean.is_binary() << '\\n';\n std::cout << j_number_integer.is_binary() << '\\n';\n std::cout << j_number_unsigned_integer.is_binary() << '\\n';\n std::cout << j_number_float.is_binary() << '\\n';\n std::cout << j_object.is_binary() << '\\n';\n std::cout << j_array.is_binary() << '\\n';\n std::cout << j_string.is_binary() << '\\n';\n std::cout << j_binary.is_binary() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\n"},{"location":"api/basic_json/is_binary/#version-history","title":"Version history","text":"constexpr bool is_boolean() const noexcept;\n This function returns true if and only if the JSON value is true or false.
true if type is boolean, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_boolean/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_boolean/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_boolean() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_boolean()\n std::cout << std::boolalpha;\n std::cout << j_null.is_boolean() << '\\n';\n std::cout << j_boolean.is_boolean() << '\\n';\n std::cout << j_number_integer.is_boolean() << '\\n';\n std::cout << j_number_unsigned_integer.is_boolean() << '\\n';\n std::cout << j_number_float.is_boolean() << '\\n';\n std::cout << j_object.is_boolean() << '\\n';\n std::cout << j_array.is_boolean() << '\\n';\n std::cout << j_string.is_boolean() << '\\n';\n std::cout << j_binary.is_boolean() << '\\n';\n}\n Output:
false\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_boolean/#version-history","title":"Version history","text":"constexpr bool is_discarded() const noexcept;\n This function returns true for a JSON value if either:
parser_callback_t), orallow_exceptions set to false; see parse for more information.true if type is discarded, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_discarded/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_discarded/#notes","title":"Notes","text":"Comparisons
Discarded values are never compared equal with operator==. That is, checking whether a JSON value j is discarded will only work via:
j.is_discarded()\n because
j == json::value_t::discarded\n will always be false.
Removal during parsing with callback functions
When a value is discarded by a callback function (see parser_callback_t) during parsing, then it is removed when it is part of a structured value. For instance, if the second value of an array is discarded, instead of [null, discarded, false], the array [null, false] is returned. Only if the top-level value is discarded, the return value of the parse call is discarded.
This function will always be false for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases.
The following code exemplifies is_discarded() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_discarded()\n std::cout << std::boolalpha;\n std::cout << j_null.is_discarded() << '\\n';\n std::cout << j_boolean.is_discarded() << '\\n';\n std::cout << j_number_integer.is_discarded() << '\\n';\n std::cout << j_number_unsigned_integer.is_discarded() << '\\n';\n std::cout << j_number_float.is_discarded() << '\\n';\n std::cout << j_object.is_discarded() << '\\n';\n std::cout << j_array.is_discarded() << '\\n';\n std::cout << j_string.is_discarded() << '\\n';\n std::cout << j_binary.is_discarded() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_discarded/#version-history","title":"Version history","text":"constexpr bool is_null() const noexcept;\n This function returns true if and only if the JSON value is null.
true if type is null, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_null/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_null/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_null() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_null()\n std::cout << std::boolalpha;\n std::cout << j_null.is_null() << '\\n';\n std::cout << j_boolean.is_null() << '\\n';\n std::cout << j_number_integer.is_null() << '\\n';\n std::cout << j_number_unsigned_integer.is_null() << '\\n';\n std::cout << j_number_float.is_null() << '\\n';\n std::cout << j_object.is_null() << '\\n';\n std::cout << j_array.is_null() << '\\n';\n std::cout << j_string.is_null() << '\\n';\n std::cout << j_binary.is_null() << '\\n';\n}\n Output:
true\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_null/#version-history","title":"Version history","text":"constexpr bool is_number() const noexcept;\n This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.
true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number/#possible-implementation","title":"Possible implementation","text":"constexpr bool is_number() const noexcept\n{\n return is_number_integer() || is_number_float();\n}\n"},{"location":"api/basic_json/is_number/#examples","title":"Examples","text":"Example The following code exemplifies is_number() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number() << '\\n';\n std::cout << j_boolean.is_number() << '\\n';\n std::cout << j_number_integer.is_number() << '\\n';\n std::cout << j_number_unsigned_integer.is_number() << '\\n';\n std::cout << j_number_float.is_number() << '\\n';\n std::cout << j_object.is_number() << '\\n';\n std::cout << j_array.is_number() << '\\n';\n std::cout << j_string.is_number() << '\\n';\n std::cout << j_binary.is_number() << '\\n';\n}\n Output:
false\nfalse\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number/#see-also","title":"See also","text":"true for unsigned integers in 2.0.0.constexpr bool is_number_float() const noexcept;\n This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.
true if type is a floating-point number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number_float/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number_float/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_number_float() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_float()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_float() << '\\n';\n std::cout << j_boolean.is_number_float() << '\\n';\n std::cout << j_number_integer.is_number_float() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_float() << '\\n';\n std::cout << j_number_float.is_number_float() << '\\n';\n std::cout << j_object.is_number_float() << '\\n';\n std::cout << j_array.is_number_float() << '\\n';\n std::cout << j_string.is_number_float() << '\\n';\n std::cout << j_binary.is_number_float() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number_float/#see-also","title":"See also","text":"constexpr bool is_number_integer() const noexcept;\n This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.
true if type is an integer or unsigned integer number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number_integer/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number_integer/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_number_integer() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_integer()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_integer() << '\\n';\n std::cout << j_boolean.is_number_integer() << '\\n';\n std::cout << j_number_integer.is_number_integer() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_integer() << '\\n';\n std::cout << j_number_float.is_number_integer() << '\\n';\n std::cout << j_object.is_number_integer() << '\\n';\n std::cout << j_array.is_number_integer() << '\\n';\n std::cout << j_string.is_number_integer() << '\\n';\n std::cout << j_binary.is_number_integer() << '\\n';\n}\n Output:
false\nfalse\ntrue\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number_integer/#see-also","title":"See also","text":"true for unsigned integers in 2.0.0.constexpr bool is_number_unsigned() const noexcept;\n This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.
true if type is an unsigned integer number, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_number_unsigned/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_number_unsigned/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_number_unsigned() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_unsigned()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_unsigned() << '\\n';\n std::cout << j_boolean.is_number_unsigned() << '\\n';\n std::cout << j_number_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_float.is_number_unsigned() << '\\n';\n std::cout << j_object.is_number_unsigned() << '\\n';\n std::cout << j_array.is_number_unsigned() << '\\n';\n std::cout << j_string.is_number_unsigned() << '\\n';\n std::cout << j_binary.is_number_unsigned() << '\\n';\n}\n Output:
false\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_number_unsigned/#see-also","title":"See also","text":"constexpr bool is_object() const noexcept;\n This function returns true if and only if the JSON value is an object.
true if type is an object, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_object/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_object/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_object() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_object()\n std::cout << std::boolalpha;\n std::cout << j_null.is_object() << '\\n';\n std::cout << j_boolean.is_object() << '\\n';\n std::cout << j_number_integer.is_object() << '\\n';\n std::cout << j_number_unsigned_integer.is_object() << '\\n';\n std::cout << j_number_float.is_object() << '\\n';\n std::cout << j_object.is_object() << '\\n';\n std::cout << j_array.is_object() << '\\n';\n std::cout << j_string.is_object() << '\\n';\n std::cout << j_binary.is_object() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\nfalse\nfalse\n"},{"location":"api/basic_json/is_object/#version-history","title":"Version history","text":"constexpr bool is_primitive() const noexcept;\n This function returns true if and only if the JSON type is primitive (string, number, boolean, null, binary).
true if type is primitive (string, number, boolean, null, or binary), false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_primitive/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_primitive/#possible-implementation","title":"Possible implementation","text":"constexpr bool is_primitive() const noexcept\n{\n return is_null() || is_string() || is_boolean() || is_number() || is_binary();\n}\n"},{"location":"api/basic_json/is_primitive/#notes","title":"Notes","text":"The term primitive stems from RFC 8259:
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.
The following code exemplifies is_primitive() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_primitive()\n std::cout << std::boolalpha;\n std::cout << j_null.is_primitive() << '\\n';\n std::cout << j_boolean.is_primitive() << '\\n';\n std::cout << j_number_integer.is_primitive() << '\\n';\n std::cout << j_number_unsigned_integer.is_primitive() << '\\n';\n std::cout << j_number_float.is_primitive() << '\\n';\n std::cout << j_object.is_primitive() << '\\n';\n std::cout << j_array.is_primitive() << '\\n';\n std::cout << j_string.is_primitive() << '\\n';\n std::cout << j_binary.is_primitive() << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\nfalse\nfalse\ntrue\ntrue\n"},{"location":"api/basic_json/is_primitive/#see-also","title":"See also","text":"nulltrue for binary types in version 3.8.0.constexpr bool is_string() const noexcept;\n This function returns true if and only if the JSON value is a string.
true if type is a string, false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_string/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_string/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_string() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_string()\n std::cout << std::boolalpha;\n std::cout << j_null.is_string() << '\\n';\n std::cout << j_boolean.is_string() << '\\n';\n std::cout << j_number_integer.is_string() << '\\n';\n std::cout << j_number_unsigned_integer.is_string() << '\\n';\n std::cout << j_number_float.is_string() << '\\n';\n std::cout << j_object.is_string() << '\\n';\n std::cout << j_array.is_string() << '\\n';\n std::cout << j_string.is_string() << '\\n';\n std::cout << j_binary.is_string() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\ntrue\nfalse\n"},{"location":"api/basic_json/is_string/#version-history","title":"Version history","text":"constexpr bool is_structured() const noexcept;\n This function returns true if and only if the JSON type is structured (array or object).
true if type is structured (array or object), false otherwise.
No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/is_structured/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/is_structured/#possible-implementation","title":"Possible implementation","text":"constexpr bool is_structured() const noexcept\n{\n return is_array() || is_object();\n}\n"},{"location":"api/basic_json/is_structured/#notes","title":"Notes","text":"The term structured stems from RFC 8259:
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
Note that though strings are containers in C++, they are treated as primitive values in JSON.
"},{"location":"api/basic_json/is_structured/#examples","title":"Examples","text":"ExampleThe following code exemplifies is_structured() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_structured()\n std::cout << std::boolalpha;\n std::cout << j_null.is_structured() << '\\n';\n std::cout << j_boolean.is_structured() << '\\n';\n std::cout << j_number_integer.is_structured() << '\\n';\n std::cout << j_number_unsigned_integer.is_structured() << '\\n';\n std::cout << j_number_float.is_structured() << '\\n';\n std::cout << j_object.is_structured() << '\\n';\n std::cout << j_array.is_structured() << '\\n';\n std::cout << j_string.is_structured() << '\\n';\n std::cout << j_binary.is_structured() << '\\n';\n}\n Output:
false\nfalse\nfalse\nfalse\nfalse\ntrue\ntrue\nfalse\nfalse\n"},{"location":"api/basic_json/is_structured/#see-also","title":"See also","text":"iteration_proxy<iterator> items() noexcept;\niteration_proxy<const_iterator> items() const noexcept;\n This function allows accessing iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.
For loop without items() function:
for (auto it = j_object.begin(); it != j_object.end(); ++it)\n{\n std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n}\n Range-based for loop without items() function:
for (auto it : j_object)\n{\n // \"it\" is of type json::reference and has no key() member\n std::cout << \"value: \" << it << '\\n';\n}\n Range-based for loop with items() function:
for (auto& el : j_object.items())\n{\n std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n The items() function also allows using structured bindings (C++17):
for (auto& [key, val] : j_object.items())\n{\n std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n"},{"location":"api/basic_json/items/#return-value","title":"Return value","text":"iteration proxy object wrapping the current value with an interface to use in range-based for loops
"},{"location":"api/basic_json/items/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/items/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/items/#notes","title":"Notes","text":"When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string.
Lifetime issues
Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See #2040 for more information.
The following code shows an example for items().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // example for an object\n for (auto& x : j_object.items())\n {\n std::cout << \"key: \" << x.key() << \", value: \" << x.value() << '\\n';\n }\n\n // example for an array\n for (auto& x : j_array.items())\n {\n std::cout << \"key: \" << x.key() << \", value: \" << x.value() << '\\n';\n }\n}\n Output:
key: one, value: 1\nkey: two, value: 2\nkey: 0, value: 1\nkey: 1, value: 2\nkey: 2, value: 4\nkey: 3, value: 8\nkey: 4, value: 16\n"},{"location":"api/basic_json/items/#version-history","title":"Version history","text":"iterator_wrapper in version 3.0.0.items and deprecated iterator_wrapper in version 3.1.0.Deprecation
This function replaces the static function iterator_wrapper which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function iterator_wrapper will be removed in version 4.0.0. Please replace all occurrences of iterator_wrapper(j) with j.items().
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
using json_base_class_t = detail::json_base_class<CustomBaseClass>;\n The base class used to inject custom functionality into each instance of basic_json. Examples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.
CustomBaseClass the base class to be added to basic_json"},{"location":"api/basic_json/json_base_class_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_base_class_t/#default-type","title":"Default type","text":"The default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.
The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.
The following code shows how to inject custom data and methods for each node.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nclass visitor_adaptor_with_metadata\n{\n public:\n template <class Fnc>\n void visit(const Fnc& fnc) const;\n\n int metadata = 42;\n private:\n template <class Ptr, class Fnc>\n void do_visit(const Ptr& ptr, const Fnc& fnc) const;\n};\n\nusing json = nlohmann::basic_json <\n std::map,\n std::vector,\n std::string,\n bool,\n std::int64_t,\n std::uint64_t,\n double,\n std::allocator,\n nlohmann::adl_serializer,\n std::vector<std::uint8_t>,\n visitor_adaptor_with_metadata\n >;\n\ntemplate <class Fnc>\nvoid visitor_adaptor_with_metadata::visit(const Fnc& fnc) const\n{\n do_visit(json::json_pointer{}, fnc);\n}\n\ntemplate <class Ptr, class Fnc>\nvoid visitor_adaptor_with_metadata::do_visit(const Ptr& ptr, const Fnc& fnc) const\n{\n using value_t = nlohmann::detail::value_t;\n const json& j = *static_cast<const json*>(this);\n switch (j.type())\n {\n case value_t::object:\n fnc(ptr, j);\n for (const auto& entry : j.items())\n {\n entry.value().do_visit(ptr / entry.key(), fnc);\n }\n break;\n case value_t::array:\n fnc(ptr, j);\n for (std::size_t i = 0; i < j.size(); ++i)\n {\n j.at(i).do_visit(ptr / std::to_string(i), fnc);\n }\n break;\n case value_t::null:\n case value_t::string:\n case value_t::boolean:\n case value_t::number_integer:\n case value_t::number_unsigned:\n case value_t::number_float:\n case value_t::binary:\n fnc(ptr, j);\n break;\n case value_t::discarded:\n default:\n break;\n }\n}\n\nint main()\n{\n // create a json object\n json j;\n j[\"null\"];\n j[\"object\"][\"uint\"] = 1U;\n j[\"object\"].metadata = 21;\n\n // visit and output\n j.visit(\n [&](const json::json_pointer & p,\n const json & j)\n {\n std::cout << (p.empty() ? std::string{\"/\"} : p.to_string())\n << \" - metadata = \" << j.metadata << \" -> \" << j.dump() << '\\n';\n });\n}\n Output:
/ - metadata = 42 -> {\"null\":null,\"object\":{\"uint\":1}}\n/null - metadata = 42 -> null\n/object - metadata = 21 -> {\"uint\":1}\n/object/uint - metadata = 42 -> 1\n"},{"location":"api/basic_json/json_base_class_t/#version-history","title":"Version history","text":"template<typename T, typename SFINAE>\nusing json_serializer = JSONSerializer<T, SFINAE>;\n"},{"location":"api/basic_json/json_serializer/#template-parameters","title":"Template parameters","text":"T type to convert; will be used in the to_json/from_json functions SFINAE type to add compile type checks via SFINAE; usually void"},{"location":"api/basic_json/json_serializer/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_serializer/#default-type","title":"Default type","text":"The default values for json_serializer is adl_serializer.
The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n"},{"location":"api/basic_json/json_serializer/#version-history","title":"Version history","text":"size_type max_size() const noexcept;\n Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the JSON value.
The return value depends on the different types and is defined as follows:
Value type return value null0 (same as size()) boolean 1 (same as size()) string 1 (same as size()) number 1 (same as size()) binary 1 (same as size()) object result of function object_t::max_size() array result of function array_t::max_size()"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/max_size/#complexity","title":"Complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.
This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of string elements the JSON value can store which is 1.
The following code calls max_size() on the different value types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call max_size()\n std::cout << j_null.max_size() << '\\n';\n std::cout << j_boolean.max_size() << '\\n';\n std::cout << j_number_integer.max_size() << '\\n';\n std::cout << j_number_float.max_size() << '\\n';\n std::cout << j_object.max_size() << '\\n';\n std::cout << j_array.max_size() << '\\n';\n std::cout << j_string.max_size() << '\\n';\n}\n Output:
0\n1\n1\n1\n115292150460684697\n576460752303423487\n1\n Note the output is platform-dependent.
"},{"location":"api/basic_json/max_size/#version-history","title":"Version history","text":"1 for binary types in version 3.8.0.void merge_patch(const basic_json& apply_patch);\n The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):
define MergePatch(Target, Patch):\n if Patch is an Object:\n if Target is not an Object:\n Target = {} // Ignore the contents and set it to an empty Object\n for each Name/Value pair in Patch:\n if Value is null:\n if Name exists in Target:\n remove the Name/Value pair from Target\n else:\n Target[Name] = MergePatch(Target[Name], Value)\n return Target\n else:\n return Patch\n Thereby, Target is the current object; that is, the patch is applied to the current value.
apply_patch (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"Linear in the lengths of apply_patch.
The following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n Output:
{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n"},{"location":"api/basic_json/merge_patch/#see-also","title":"See also","text":"static basic_json meta();\n This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.
"},{"location":"api/basic_json/meta/#return-value","title":"Return value","text":"JSON object holding version information
key descriptioncompiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown. url The URL of the project as string. version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/meta/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/meta/#examples","title":"Examples","text":"ExampleThe following code shows an example output of the meta() function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // call meta()\n std::cout << std::setw(4) << json::meta() << '\\n';\n}\n Output:
{\n \"compiler\": {\n \"c++\": \"201103\",\n \"family\": \"gcc\",\n \"version\": \"12.3.0\"\n },\n \"copyright\": \"(C) 2013-2022 Niels Lohmann\",\n \"name\": \"JSON for Modern C++\",\n \"platform\": \"apple\",\n \"url\": \"https://github.com/nlohmann/json\",\n \"version\": {\n \"major\": 3,\n \"minor\": 11,\n \"patch\": 3,\n \"string\": \"3.11.3\"\n }\n}\n Note the output is platform-dependent.
"},{"location":"api/basic_json/meta/#see-also","title":"See also","text":"using number_float_t = NumberFloatType;\n The type used to store JSON numbers (floating-point).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store floating-point numbers in C++, a type is defined by the template parameter NumberFloatType which chooses the type to use.
With the default values for NumberFloatType (double), the default value for number_float_t is double.
01.2 will be serialized to 1.2. During deserialization, leading zeros yield an error.null.RFC 8259 states:
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.
This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.
Floating-point number values are stored directly inside a basic_json type.
The following code shows that number_float_t is by default, a typedef to double.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<double, json::number_float_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/number_float_t/#version-history","title":"Version history","text":"using number_integer_t = NumberIntegerType;\n The type used to store JSON numbers (integers).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.
With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.
"},{"location":"api/basic_json/number_integer_t/#storage","title":"Storage","text":"Integer number values are stored directly inside a basic_json type.
The following code shows that number_integer_t is by default, a typedef to std::int64_t.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::int64_t, json::number_integer_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/number_integer_t/#version-history","title":"Version history","text":"using number_unsigned_t = NumberUnsignedType;\n The type used to store JSON numbers (unsigned).
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.
To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.
With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range \\f[-2^{53}+1, 2^{53}-1]\\f are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.
Integer number values are stored directly inside a basic_json type.
The following code shows that number_unsigned_t is by default, a typedef to std::uint64_t.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::uint64_t, json::number_unsigned_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/number_unsigned_t/#version-history","title":"Version history","text":"static basic_json object(initializer_list_t init = {});\n Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.
init (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"JSON object value
"},{"location":"api/basic_json/object/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/object/#exceptions","title":"Exceptions","text":"Throws type_error.301 if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list init. See example below.
Linear in the size of init.
This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t).
The following code shows an example for the object function.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON objects\n json j_no_init_list = json::object();\n json j_empty_init_list = json::object({});\n json j_list_of_pairs = json::object({ {\"one\", 1}, {\"two\", 2} });\n\n // serialize the JSON objects\n std::cout << j_no_init_list << '\\n';\n std::cout << j_empty_init_list << '\\n';\n std::cout << j_list_of_pairs << '\\n';\n\n // example for an exception\n try\n {\n // can only create an object from a list of pairs\n json j_invalid_object = json::object({{ \"one\", 1, 2 }});\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
{}\n{}\n{\"one\":1,\"two\":2}\n[json.exception.type_error.301] cannot create object from initializer list\n"},{"location":"api/basic_json/object/#see-also","title":"See also","text":"basic_json(initializer_list_t) - create a JSON value from an initializer listarray - create a JSON array value from an initializer listusing object_comparator_t = typename object_t::key_compare;\n// or\nusing object_comparator_t = default_object_comparator_t;\n The comparator used by object_t. Defined as typename object_t::key_compare if available, and default_object_comparator_t otherwise.
The example below demonstrates the used object comparator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha\n << \"json::object_comparator_t(\\\"one\\\", \\\"two\\\") = \" << json::object_comparator_t{}(\"one\", \"two\") << \"\\n\"\n << \"json::object_comparator_t(\\\"three\\\", \\\"four\\\") = \" << json::object_comparator_t{}(\"three\", \"four\") << std::endl;\n}\n Output:
json::object_comparator_t(\"one\", \"two\") = true\njson::object_comparator_t(\"three\", \"four\") = false\n"},{"location":"api/basic_json/object_comparator_t/#version-history","title":"Version history","text":"typename object_t::key_compare or default_object_comparator_t in version 3.11.0.using object_t = ObjectType<StringType,\n basic_json,\n default_object_comparator_t,\n AllocatorType<std::pair<const StringType, basic_json>>>;\n The type used to store JSON objects.
RFC 8259 describes JSON objects as follows:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
To store objects in C++, a type is defined by the template parameters described below.
"},{"location":"api/basic_json/object_t/#template-parameters","title":"Template parameters","text":"ObjectType the container to store objects (e.g., std::map or std::unordered_map) StringType the type of the keys or names (e.g., std::string). The comparison function std::less<StringType> is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/object_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/object_t/#default-type","title":"Default type","text":"With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:
// until C++14\nstd::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<std::string>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n\n// since C++14\nstd::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n See default_object_comparator_t for more information.
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
{\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.dump) in this order. For instance, {\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be stored and serialized as {\"a\": 2, \"b\": 1}.{\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be treated as equal.RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.
Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.
The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.
The following code shows that object_t is by default, a typedef to std::map<json::string_t, json>.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::map<json::string_t, json>, json::object_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/object_t/#version-history","title":"Version history","text":"// (1)\nreference operator+=(basic_json&& val);\nreference operator+=(const basic_json& val);\n\n// (2)\nreference operator+=(const typename object_t::value_type& val);\n\n// (3)\nreference operator+=(initializer_list_t init);\n Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.
Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.
This function allows using operator+= with an initializer list. In case
init contains only two elements, andinit is a string,init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).
For all cases where an element is added to an 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.
For ordered_json, also adding an element to an object can yield a reallocation which again invalidates all iterators and all references.
val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"*this
All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use operator+=() with number\"
size())).init.(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n Output:
[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n object.push_back(json::object_t::value_type(\"three\", 3));\n object += json::object_t::value_type(\"four\", 4);\n null += json::object_t::value_type(\"A\", \"a\");\n null += json::object_t::value_type(\"B\", \"b\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values:\n object.push_back({\"three\", 3}); // object is extended\n object += {\"four\", 4}; // object is extended\n null.push_back({\"five\", 5}); // null is converted to array\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // would throw:\n //object.push_back({1, 2, 3});\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n"},{"location":"api/basic_json/operator%2B%3D/#see-also","title":"See also","text":"basic_json& operator=(basic_json other) noexcept (\n std::is_nothrow_move_constructible<value_t>::value &&\n std::is_nothrow_move_assignable<value_t>::value &&\n std::is_nothrow_move_constructible<json_value>::value &&\n std::is_nothrow_move_assignable<json_value>::value\n);\n Copy assignment operator. Copies a JSON value via the \"copy and swap\" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function.
other (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator%3D/#examples","title":"Examples","text":"ExampleThe code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json a = 23;\n json b = 42;\n\n // copy-assign a to b\n b = a;\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n Output:
23\n23\n"},{"location":"api/basic_json/operator%3D/#version-history","title":"Version history","text":"// (1)\nreference operator[](size_type idx);\nconst_reference operator[](size_type idx) const;\n\n// (2)\nreference operator[](typename object_t::key_type key);\nconst_reference operator[](const typename object_t::key_type& key) const;\n\n// (3)\ntemplate<typename KeyType>\nreference operator[](KeyType&& key);\ntemplate<typename KeyType>\nconst_reference operator[](KeyType&& key) const;\n\n// (4)\nreference operator[](const json_pointer& ptr);\nconst_reference operator[](const json_pointer& ptr) const;\n idx.key. The non-const qualified overload takes the key by value.KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.ptr.KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#iterator-invalidation","title":"Iterator invalidation","text":"For the non-const versions 1. and 4., when passing an array index that does not exist, it is created and filled with a null value before a reference to it is returned. For this, a reallocation can happen, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
For ordered_json, also passing an object key to the non-const versions 2., 3., and 4., a reallocation can happen which again invalidates all iterators and all references.
idx (in) index of the element to access key (in) object key of the element to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"idxkeykeyptrStrong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/operator%5B%5D/#exceptions","title":"Exceptions","text":"type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense.type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense.parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'.parse_error.109 if an array index in the passed JSON pointer ptr is not a number.out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version.out_of_range.404 if the JSON pointer ptr can not be resolved.idx is in the range of the array. Otherwise, linear in idx - size().Undefined behavior and runtime assertions
idx does not exist, the behavior is undefined.key does not exist, the behavior is undefined and is guarded by a runtime assertion!The non-const version may add values: If idx is beyond the range of the array (i.e., idx >= size()), then the array is silently filled up with null values to make idx a valid reference to the last stored element. In case the value was null before, it is converted to an array.
If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.
See 2.
null values are created in arrays and objects if necessary.
In particular:
null value before a reference to it is returned.null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.- is treated as a synonym for the index past the end.The example below shows how array elements can be read and written using [] operator. Note the addition of null values.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json array = {1, 2, 3, 4, 5};\n\n // output element at index 3 (fourth element)\n std::cout << array[3] << '\\n';\n\n // change last element to 6\n array[array.size() - 1] = 6;\n\n // output changed array\n std::cout << array << '\\n';\n\n // write beyond array limit\n array[10] = 11;\n\n // output changed array\n std::cout << array << '\\n';\n}\n Output:
4\n[1,2,3,4,6]\n[1,2,3,4,6,null,null,null,null,null,11]\n Example: (1) access specified array element (const) The example below shows how array elements can be read using the [] operator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n}\n Output:
\"third\"\n Example: (2) access specified object element The example below shows how object elements can be read and written using the [] operator.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"] << \"\\n\\n\";\n\n // change element with key \"three\"\n object[\"three\"] = 3;\n\n // output changed array\n std::cout << std::setw(4) << object << \"\\n\\n\";\n\n // mention nonexisting key\n object[\"four\"];\n\n // write to nonexisting key\n object[\"five\"][\"really\"][\"nested\"] = true;\n\n // output changed object\n std::cout << std::setw(4) << object << '\\n';\n}\n Output:
2\n\n{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n\n{\n \"five\": {\n \"really\": {\n \"nested\": true\n }\n },\n \"four\": null,\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n Example: (2) access specified object element (const) The example below shows how object elements can be read using the [] operator.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n const json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"] << '\\n';\n}\n Output:
2\n Example: (3) access specified object element using string_view The example below shows how object elements can be read using the [] operator.
#include <iostream>\n#include <iomanip>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"sv] << \"\\n\\n\";\n\n // change element with key \"three\"\n object[\"three\"sv] = 3;\n\n // output changed array\n std::cout << std::setw(4) << object << \"\\n\\n\";\n\n // mention nonexisting key\n object[\"four\"sv];\n\n // write to nonexisting key\n object[\"five\"sv][\"really\"sv][\"nested\"sv] = true;\n\n // output changed object\n std::cout << std::setw(4) << object << '\\n';\n}\n Output:
2\n\n{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n\n{\n \"five\": {\n \"really\": {\n \"nested\": true\n }\n },\n \"four\": null,\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n Example: (3) access specified object element using string_view (const) The example below shows how object elements can be read using the [] operator.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object\n const json object =\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 2.9}\n };\n\n // output element with key \"two\"\n std::cout << object[\"two\"sv] << '\\n';\n}\n Output:
2\n Example: (4) access specified element via JSON Pointer The example below shows how values can be read and written using JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j[\"/number\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j[\"/string\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j[\"/array\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j[\"/array/1\"_json_pointer] << '\\n';\n\n // writing access\n\n // change the string\n j[\"/string\"_json_pointer] = \"bar\";\n // output the changed string\n std::cout << j[\"string\"] << '\\n';\n\n // \"change\" a nonexisting object entry\n j[\"/boolean\"_json_pointer] = true;\n // output the changed object\n std::cout << j << '\\n';\n\n // change an array element\n j[\"/array/1\"_json_pointer] = 21;\n // \"change\" an array element with nonexisting index\n j[\"/array/4\"_json_pointer] = 44;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n\n // \"change\" the array element past the end\n j[\"/array/-\"_json_pointer] = 55;\n // output the changed array\n std::cout << j[\"array\"] << '\\n';\n}\n Output:
1\n\"foo\"\n[1,2]\n2\n\"bar\"\n{\"array\":[1,2],\"boolean\":true,\"number\":1,\"string\":\"bar\"}\n[1,21,null,null,44]\n[1,21,null,null,44,55]\n Example: (4) access specified element via JSON Pointer (const) The example below shows how values can be read using JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n const json j =\n {\n {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n };\n\n // read-only access\n\n // output element with JSON pointer \"/number\"\n std::cout << j[\"/number\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/string\"\n std::cout << j[\"/string\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array\"\n std::cout << j[\"/array\"_json_pointer] << '\\n';\n // output element with JSON pointer \"/array/1\"\n std::cout << j[\"/array/1\"_json_pointer] << '\\n';\n}\n Output:
1\n\"foo\"\n[1,2]\n2\n"},{"location":"api/basic_json/operator%5B%5D/#see-also","title":"See also","text":"at for access by reference with range checkingvalue for access with default valueT* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0.template<typename ValueType>\nJSON_EXPLICIT operator ValueType() const;\n Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.
ValueType the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"copy of the JSON value, converted to ValueType
Depends on what json_serializer<ValueType> from_json() method throws
Linear in the size of the JSON value.
"},{"location":"api/basic_json/operator_ValueType/#notes","title":"Notes","text":"Definition of JSON_EXPLICIT
By default JSON_EXPLICIT is defined to the empty string, so the signature is:
template<typename ValueType>\noperator ValueType() const;\n If JSON_USE_IMPLICIT_CONVERSIONS is set to 0, JSON_EXPLICIT is defined to explicit:
template<typename ValueType>\nexplicit operator ValueType() const;\n That is, implicit conversions can be switched off by defining JSON_USE_IMPLICIT_CONVERSIONS to 0.
Future behavior change
Implicit conversions will be switched off by default in the next major release of the library. That is, JSON_EXPLICIT will be set to explicit by default.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use implicit conversions\n bool v1 = json_types[\"boolean\"];\n int v2 = json_types[\"number\"][\"integer\"];\n short v3 = json_types[\"number\"][\"integer\"];\n float v4 = json_types[\"number\"][\"floating-point\"];\n int v5 = json_types[\"number\"][\"floating-point\"];\n std::string v6 = json_types[\"string\"];\n std::vector<short> v7 = json_types[\"array\"];\n std::unordered_map<std::string, json> v8 = json_types;\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n\n // example for an exception\n try\n {\n bool v1 = json_types[\"string\"];\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
1\n42 42\n17.23 17\nHello, world!\n1 2 3 4 5 \n\nstring: \"Hello, world!\"\nnumber: {\"floating-point\":17.23,\"integer\":42}\nnull: null\nboolean: true\narray: [1,2,3,4,5]\n[json.exception.type_error.302] type must be boolean, but is string\n"},{"location":"api/basic_json/operator_ValueType/#version-history","title":"Version history","text":"JSON_EXPLICIT/JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.// until C++20\nbool operator==(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator==(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator==(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n\n// since C++20\nclass basic_json {\n bool operator==(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n bool operator==(ScalarType rhs) const noexcept; // (2)\n};\n Compares two JSON values for equality according to the following rules:
operator==.Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are equal
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_eq/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_eq/#notes","title":"Notes","text":"Comparing special values
NaN values are unordered within the domain of numbers. The following comparisons all yield false:NaN with itself.NaN with another NaN.NaN and any other number.null values are all equal.Comparing floating-point numbers
Floating-point numbers inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default. To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance
template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\ninline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n{\n return std::abs(a - b) <= epsilon;\n}\n Or you can self-defined operator equal function like this:
bool my_equal(const_reference lhs, const_reference rhs)\n{\n const auto lhs_type lhs.type();\n const auto rhs_type rhs.type();\n if (lhs_type == rhs_type)\n {\n switch(lhs_type)\n // self_defined case\n case value_t::number_float:\n return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();\n // other cases remain the same with the original\n ...\n }\n...\n}\n Comparing different basic_json specializations
Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects
{\n \"version\": 1,\n \"type\": \"integer\"\n}\n and
{\n \"type\": \"integer\",\n \"version\": 1\n}\n depends on whether nlohmann::json or nlohmann::ordered_json is used:
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n nlohmann::json uj1 = {{\"version\", 1}, {\"type\", \"integer\"}};\n nlohmann::json uj2 = {{\"type\", \"integer\"}, {\"version\", 1}};\n\n nlohmann::ordered_json oj1 = {{\"version\", 1}, {\"type\", \"integer\"}};\n nlohmann::ordered_json oj2 = {{\"type\", \"integer\"}, {\"version\", 1}};\n\n std::cout << std::boolalpha << (uj1 == uj2) << '\\n' << (oj1 == oj2) << std::endl;\n}\n Output:
true\nfalse\n"},{"location":"api/basic_json/operator_eq/#examples","title":"Examples","text":"Example The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.000000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 == array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 == object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 == number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 == string_2) << '\\n';\n}\n Output:
[1,2,3] == [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} == {\"A\":\"a\",\"B\":\"b\"} true\n17 == 17.0 true\n\"foo\" == \"bar\" false\n Example The example demonstrates comparing several JSON types against the null pointer (JSON null).
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array = {1, 2, 3};\n json object = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json number = 17;\n json string = \"foo\";\n json null;\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array << \" == nullptr \" << (array == nullptr) << '\\n';\n std::cout << object << \" == nullptr \" << (object == nullptr) << '\\n';\n std::cout << number << \" == nullptr \" << (number == nullptr) << '\\n';\n std::cout << string << \" == nullptr \" << (string == nullptr) << '\\n';\n std::cout << null << \" == nullptr \" << (null == nullptr) << '\\n';\n}\n Output:
[1,2,3] == nullptr false\n{\"A\":\"a\",\"B\":\"b\"} == nullptr false\n17 == nullptr false\n\"foo\" == nullptr false\nnull == nullptr true\n"},{"location":"api/basic_json/operator_eq/#version-history","title":"Version history","text":"// until C++20\nbool operator>=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator>=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator>=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs < rhs) (see operator<).Compares whether a JSON value is greater than or equal to a scalar or a scalar is greater than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"whether lhs is less than or equal to rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_ge/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_ge/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" >= \" << array_2 << \" \" << (array_1 >= array_2) << '\\n';\n std::cout << object_1 << \" >= \" << object_2 << \" \" << (object_1 >= object_2) << '\\n';\n std::cout << number_1 << \" >= \" << number_2 << \" \" << (number_1 >= number_2) << '\\n';\n std::cout << string_1 << \" >= \" << string_2 << \" \" << (string_1 >= string_2) << '\\n';\n}\n Output:
[1,2,3] >= [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} >= {\"A\":\"a\",\"B\":\"b\"} true\n17 >= 17.0000000000001 false\n\"foo\" >= \"bar\" true\n"},{"location":"api/basic_json/operator_ge/#see-also","title":"See also","text":"// until C++20\nbool operator>(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator>(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator>(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs <= rhs) (see operator<=).Compares whether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"whether lhs is greater than rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_gt/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_gt/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" > \" << array_2 << \" \" << (array_1 > array_2) << '\\n';\n std::cout << object_1 << \" > \" << object_2 << \" \" << (object_1 > object_2) << '\\n';\n std::cout << number_1 << \" > \" << number_2 << \" \" << (number_1 > number_2) << '\\n';\n std::cout << string_1 << \" > \" << string_2 << \" \" << (string_1 > string_2) << '\\n';\n}\n Output:
[1,2,3] > [1,2,4] false\n{\"A\":\"a\",\"B\":\"b\"} > {\"A\":\"a\",\"B\":\"b\"} false\n17 > 17.0000000000001 false\n\"foo\" > \"bar\" true\n"},{"location":"api/basic_json/operator_gt/#see-also","title":"See also","text":"// until C++20\nbool operator<=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator<=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator<=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(rhs < lhs) (see operator<).Compares whether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"whether lhs is less than or equal to rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_le/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_le/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" <= \" << array_2 << \" \" << (array_1 <= array_2) << '\\n';\n std::cout << object_1 << \" <= \" << object_2 << \" \" << (object_1 <= object_2) << '\\n';\n std::cout << number_1 << \" <= \" << number_2 << \" \" << (number_1 <= number_2) << '\\n';\n std::cout << string_1 << \" <= \" << string_2 << \" \" << (string_1 <= string_2) << '\\n';\n}\n Output:
[1,2,3] <= [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} <= {\"A\":\"a\",\"B\":\"b\"} true\n17 <= 17.0000000000001 true\n\"foo\" <= \"bar\" false\n"},{"location":"api/basic_json/operator_le/#see-also","title":"See also","text":"// until C++20\nbool operator<(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator<(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator<(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:
false.operator<.lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:Compares whether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"whether lhs is less than rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_lt/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_lt/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator<=>.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 < array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 < object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 < number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 < string_2) << '\\n';\n}\n Output:
[1,2,3] == [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} == {\"A\":\"a\",\"B\":\"b\"} false\n17 == 17.0000000000001 true\n\"foo\" == \"bar\" false\n"},{"location":"api/basic_json/operator_lt/#see-also","title":"See also","text":"// until C++20\nbool operator!=(const_reference lhs, const_reference rhs) noexcept; // (1)\n\ntemplate<typename ScalarType>\nbool operator!=(const_reference lhs, const ScalarType rhs) noexcept; // (2)\n\ntemplate<typename ScalarType>\nbool operator!=(ScalarType lhs, const const_reference rhs) noexcept; // (2)\n\n// since C++20\nclass basic_json {\n bool operator!=(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n bool operator!=(ScalarType rhs) const noexcept; // (2)\n};\n Compares two JSON values for inequality according to the following rules:
false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.!(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1.
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are not equal
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_ne/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_ne/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield false: 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN. 3. Comparing a NaN and any other number.
The example demonstrates comparing several JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.000000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" != \" << array_2 << \" \" << (array_1 != array_2) << '\\n';\n std::cout << object_1 << \" != \" << object_2 << \" \" << (object_1 != object_2) << '\\n';\n std::cout << number_1 << \" != \" << number_2 << \" \" << (number_1 != number_2) << '\\n';\n std::cout << string_1 << \" != \" << string_2 << \" \" << (string_1 != string_2) << '\\n';\n}\n Output:
[1,2,3] != [1,2,4] true\n{\"A\":\"a\",\"B\":\"b\"} != {\"A\":\"a\",\"B\":\"b\"} false\n17 != 17.0 false\n\"foo\" != \"bar\" true\n Example The example demonstrates comparing several JSON types against the null pointer (JSON null).
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array = {1, 2, 3};\n json object = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json number = 17;\n json string = \"foo\";\n json null;\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array << \" != nullptr \" << (array != nullptr) << '\\n';\n std::cout << object << \" != nullptr \" << (object != nullptr) << '\\n';\n std::cout << number << \" != nullptr \" << (number != nullptr) << '\\n';\n std::cout << string << \" != nullptr \" << (string != nullptr) << '\\n';\n std::cout << null << \" != nullptr \" << (null != nullptr) << '\\n';\n}\n Output:
[1,2,3] != nullptr true\n{\"A\":\"a\",\"B\":\"b\"} != nullptr true\n17 != nullptr true\n\"foo\" != nullptr true\nnull != nullptr false\n"},{"location":"api/basic_json/operator_ne/#version-history","title":"Version history","text":"// since C++20\nclass basic_json {\n std::partial_ordering operator<=>(const_reference rhs) const noexcept; // (1)\n\n template<typename ScalarType>\n std::partial_ordering operator<=>(const ScalarType rhs) const noexcept; // (2)\n};\n 3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:
std::partial_ordering::unordered if either value is discarded.operator<=>.operator<=>. For instance, comparing an integer and a floating-point value will 3-way compare the first value converted to floating-point with the second value.value_t).3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way comparing both JSON values (see 1).
ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"rhs (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"the std::partial_ordering of the 3-way comparison of *this and rhs
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/operator_spaceship/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/operator_spaceship/#notes","title":"Notes","text":"Comparing NaN
NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered:NaN with itself.NaN with another NaN.NaN and any other number.The example demonstrates comparing several JSON values.
#include <compare>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nconst char* to_string(const std::partial_ordering& po)\n{\n if (std::is_lt(po))\n {\n return \"less\";\n }\n else if (std::is_gt(po))\n {\n return \"greater\";\n }\n else if (std::is_eq(po))\n {\n return \"equivalent\";\n }\n return \"unordered\";\n}\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number = 17;\n json string = \"foo\";\n json discarded = json(json::value_t::discarded);\n\n // output values and comparisons\n std::cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string(array_1 <=> array_2) << '\\n'; // *NOPAD*\n std::cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string(object_1 <=> object_2) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << number << \" := \" << to_string(string <=> number) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << discarded << \" := \" << to_string(string <=> discarded) << '\\n'; // *NOPAD*\n}\n Output:
[1,2,3] <=> [1,2,4] := less\n{\"A\":\"a\",\"B\":\"b\"} <=> {\"A\":\"a\",\"B\":\"b\"} := equivalent\n\"foo\" <=> 17 := greater\n\"foo\" <=> <discarded> := unordered\n Example: (2) comparing JSON values and scalars The example demonstrates comparing several JSON values and scalars.
#include <compare>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nconst char* to_string(const std::partial_ordering& po)\n{\n if (std::is_lt(po))\n {\n return \"less\";\n }\n else if (std::is_gt(po))\n {\n return \"greater\";\n }\n else if (std::is_eq(po))\n {\n return \"equivalent\";\n }\n return \"unordered\";\n}\n\nint main()\n{\n using float_limits = std::numeric_limits<json::number_float_t>;\n constexpr auto nan = float_limits::quiet_NaN();\n\n // create several JSON values\n json boolean = false;\n json number = 17;\n json string = \"17\";\n\n // output values and comparisons\n std::cout << std::boolalpha << std::fixed;\n std::cout << boolean << \" <=> \" << true << \" := \" << to_string(boolean <=> true) << '\\n'; // *NOPAD*\n std::cout << number << \" <=> \" << 17.0 << \" := \" << to_string(number <=> 17.0) << '\\n'; // *NOPAD*\n std::cout << number << \" <=> \" << nan << \" := \" << to_string(number <=> nan) << '\\n'; // *NOPAD*\n std::cout << string << \" <=> \" << 17 << \" := \" << to_string(string <=> 17) << '\\n'; // *NOPAD*\n}\n Output:
false <=> true := less\n17 <=> 17.000000 := equivalent\n17 <=> nan := unordered\n\"17\" <=> 17 := greater\n"},{"location":"api/basic_json/operator_spaceship/#see-also","title":"See also","text":"constexpr operator value_t() const noexcept;\n Return the type of the JSON value as a value from the value_t enumeration.
the type of the JSON value
Value type return valuenull value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/operator_value_t/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/operator_value_t/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/operator_value_t/#examples","title":"Examples","text":"ExampleThe following code exemplifies operator value_t() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call operator value_t()\n json::value_t t_null = j_null;\n json::value_t t_boolean = j_boolean;\n json::value_t t_number_integer = j_number_integer;\n json::value_t t_number_unsigned = j_number_unsigned;\n json::value_t t_number_float = j_number_float;\n json::value_t t_object = j_object;\n json::value_t t_array = j_array;\n json::value_t t_string = j_string;\n\n // print types\n std::cout << std::boolalpha;\n std::cout << (t_null == json::value_t::null) << '\\n';\n std::cout << (t_boolean == json::value_t::boolean) << '\\n';\n std::cout << (t_number_integer == json::value_t::number_integer) << '\\n';\n std::cout << (t_number_unsigned == json::value_t::number_unsigned) << '\\n';\n std::cout << (t_number_float == json::value_t::number_float) << '\\n';\n std::cout << (t_object == json::value_t::object) << '\\n';\n std::cout << (t_array == json::value_t::array) << '\\n';\n std::cout << (t_string == json::value_t::string) << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n"},{"location":"api/basic_json/operator_value_t/#version-history","title":"Version history","text":"class other_error : public exception;\n This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx (see list of other errors).
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_other_error fill:#CCCCFF"},{"location":"api/basic_json/other_error/#member-functions","title":"Member functions","text":"The following code shows how a other_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n try\n {\n // executing a failing JSON Patch operation\n json value = R\"({\n \"best_biscuit\": {\n \"name\": \"Oreo\"\n }\n })\"_json;\n json patch = R\"([{\n \"op\": \"test\",\n \"path\": \"/best_biscuit/name\",\n \"value\": \"Choco Leibniz\"\n }])\"_json;\n value.patch(patch);\n }\n catch (const json::other_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n"},{"location":"api/basic_json/other_error/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeclass out_of_range : public exception;\n This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx (see list of out-of-range errors).
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_out_of_range fill:#CCCCFF"},{"location":"api/basic_json/out_of_range/#member-functions","title":"Member functions","text":"The following code shows how a out_of_range exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for an invalid index\n json j = {1, 2, 3, 4};\n j.at(4) = 10;\n }\n catch (const json::out_of_range& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n"},{"location":"api/basic_json/out_of_range/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeother_error for exceptions indicating other library errors// (1)\ntemplate<typename InputType>\nstatic basic_json parse(InputType&& i,\n const parser_callback_t cb = nullptr,\n const bool allow_exceptions = true,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<typename IteratorType>\nstatic basic_json parse(IteratorType first, IteratorType last,\n const parser_callback_t cb = nullptr,\n const bool allow_exceptions = true,\n const bool ignore_comments = false);\n Deserialize from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
InputType A compatible input, for instance:
std::istream objectFILE pointer (throws if null)std::stringobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType a compatible iterator type, for instance.
std::string::iterator or std::vector<std::uint8_t>::iteratorptr and ptr + leni (in) Input to parse from. cb (in) a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/parse/#exceptions","title":"Exceptions","text":"parse_error.101 in case of an unexpected token, or empty input like a null FILE* or char* pointer.parse_error.102 if to_unicode fails or surrogate error.parse_error.103 if to_unicode fails.Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb or reading from (1) the input i or (2) the iterator range [first, last] has a super-linear complexity.
A UTF-8 byte order mark is silently ignored.
"},{"location":"api/basic_json/parse/#examples","title":"Examples","text":"Parsing from a character arrayThe example below demonstrates the parse() function reading from an array.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n char text[] = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n Parsing from a string The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n Parsing from an input stream The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // fill a stream with JSON text\n std::stringstream ss;\n ss << text;\n\n // parse and serialize JSON\n json j_complete = json::parse(ss);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // fill a stream with JSON text\n ss.clear();\n ss << text;\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(ss, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n Parsing from a contiguous container The example below demonstrates the parse() function reading from a contiguous container.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given as std::vector\n std::vector<std::uint8_t> text = {'[', '1', ',', '2', ',', '3', ']', '\\0'};\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
[\n 1,\n 2,\n 3\n]\n Parsing from a non null-terminated string The example below demonstrates the parse() function reading from a string that is not null-terminated.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given as string that is not null-terminated\n const char* ptr = \"[1,2,3]another value\";\n\n // parse and serialize JSON\n json j_complete = json::parse(ptr, ptr + 7);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
[\n 1,\n 2,\n 3\n]\n Parsing from an iterator pair The example below demonstrates the parse() function reading from an iterator pair.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text given an input with other values\n std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'};\n\n // parse and serialize JSON\n json j_complete = json::parse(input.begin(), input.begin() + 7);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n}\n Output:
[\n 1,\n 2,\n 3\n]\n Effect of allow_exceptions parameter The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // an invalid JSON text\n std::string text = R\"(\n {\n \"key\": \"value without closing quotes\n }\n )\";\n\n // parse with exceptions\n try\n {\n json j = json::parse(text);\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n // parse without exceptions\n json j = json::parse(text, nullptr, false);\n\n if (j.is_discarded())\n {\n std::cout << \"the input is invalid JSON\" << std::endl;\n }\n else\n {\n std::cout << \"the input is valid JSON: \" << j << std::endl;\n }\n}\n Output:
[json.exception.parse_error.101] parse error at line 4, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n; last read: '\"value without closing quotes<U+000A>'\nthe input is invalid JSON\n"},{"location":"api/basic_json/parse/#see-also","title":"See also","text":"ignore_comments added in version 3.9.0.FILE* null pointers to exception in version 3.11.4.Deprecation
Overload (2) replaces calls to parse with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like parse({ptr, ptr+len}, ...); with parse(ptr, ptr+len, ...);.
You should be warned by your compiler with a -Wdeprecated-declarations warning if you are using a deprecated function.
class parse_error : public exception;\n This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, BSON, CBOR, MessagePack, UBJSON, as well as when using JSON Patch.
Member byte holds the byte index of the last read character in the input file (see note below).
Exceptions have ids 1xx (see list of parse errors).
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_parse_error fill:#CCCCFF"},{"location":"api/basic_json/parse_error/#member-functions","title":"Member functions","text":"For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector for binary formats.
"},{"location":"api/basic_json/parse_error/#examples","title":"Examples","text":"ExampleThe following code shows how a parse_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // parsing input with a syntax error\n json::parse(\"[1,2,3,]\");\n }\n catch (const json::parse_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << '\\n'\n << \"byte position of error: \" << e.byte << std::endl;\n }\n}\n Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nexception id: 101\nbyte position of error: 8\n"},{"location":"api/basic_json/parse_error/#see-also","title":"See also","text":"invalid_iterator for exceptions indicating errors with iteratorstype_error for exceptions indicating executing a member function with a wrong typeout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsenum class parse_event_t : std::uint8_t {\n object_start,\n object_end,\n array_start,\n array_end,\n key,\n value\n};\n The parser callback distinguishes the following events:
object_start: the parser read { and started to process a JSON objectkey: the parser read a key of a value in an objectobject_end: the parser read } and finished processing a JSON objectarray_start: the parser read [ and started to process a JSON arrayarray_end: the parser read ] and finished processing a JSON arrayvalue: the parser finished reading a JSON valuetemplate<typename BasicJsonType>\nusing parser_callback_t =\n std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Discarding a value (i.e., returning false) has different effects depending on the context in which function was called:
null. This case happens if the top-level element is skipped.depth (in) the depth of the recursion during parsing event (in) an event of type parse_event_t indicating the context in the callback function has been called parsed (in, out) the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.
The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n"},{"location":"api/basic_json/parser_callback_t/#version-history","title":"Version history","text":"basic_json patch(const basic_json& json_patch) const;\n JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
"},{"location":"api/basic_json/patch/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch/#return-value","title":"Return value","text":"patched document
"},{"location":"api/basic_json/patch/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/patch/#exceptions","title":"Exceptions","text":"parse_error.104 if the JSON patch does not consist of an array of objects.parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".out_of_range.401 if an array index is out of range.out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: \"key baz not found\".out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")out_of_range.501 if \"test\" operation was unsuccessful.Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.
"},{"location":"api/basic_json/patch/#notes","title":"Notes","text":"The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value.
"},{"location":"api/basic_json/patch/#examples","title":"Examples","text":"ExampleThe following code shows how a JSON patch is applied to a value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // apply the patch\n json patched_doc = doc.patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << doc << \"\\n\\n\"\n << std::setw(4) << patched_doc << std::endl;\n}\n Output:
{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"api/basic_json/patch/#see-also","title":"See also","text":"void patch_inplace(const basic_json& json_patch) const;\n JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. This function applies a JSON patch in place and returns void.
"},{"location":"api/basic_json/patch_inplace/#parameters","title":"Parameters","text":"json_patch (in) JSON patch document"},{"location":"api/basic_json/patch_inplace/#exception-safety","title":"Exception safety","text":"No guarantees, value may be corrupted by an unsuccessful patch operation.
"},{"location":"api/basic_json/patch_inplace/#exceptions","title":"Exceptions","text":"parse_error.104 if the JSON patch does not consist of an array of objects.parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".out_of_range.401 if an array index is out of range.out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: \"key baz not found\".out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")out_of_range.501 if \"test\" operation was unsuccessful.Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.
"},{"location":"api/basic_json/patch_inplace/#notes","title":"Notes","text":"Unlike patch, patch_inplace applies the operation \"in place\" and no copy of the JSON value is created. That makes it faster for large documents by avoiding the copy. However, the JSON value might be corrupted if the function throws an exception.
The following code shows how a JSON patch is applied to a value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // output original document\n std::cout << \"Before\\n\" << std::setw(4) << doc << std::endl;\n\n // apply the patch\n doc.patch_inplace(patch);\n\n // output patched document\n std::cout << \"\\nAfter\\n\" << std::setw(4) << doc << std::endl;\n}\n Output:
Before\n{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\nAfter\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"api/basic_json/patch_inplace/#see-also","title":"See also","text":"// (1)\nvoid push_back(basic_json&& val);\nvoid push_back(const basic_json& val);\n\n// (2)\nvoid push_back(const typename object_t::value_type& val);\n\n// (3)\nvoid push_back(initializer_list_t init);\n Appends the given element val to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending val.
Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.
This function allows using push_back with an initializer list. In case
init contains only two elements, andinit is a string,init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).
For all cases where an element is added to an 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.
For ordered_json, also adding an element to an object can yield a reallocation which again invalidates all iterators and all references.
val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use push_back() with number\"
size())).init.(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}\n Output:
[1,2,3,4,5]\nnull\n[1,2,3,4,5,6,7]\n[\"first\",\"second\"]\n Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values\n object.push_back(json::object_t::value_type(\"three\", 3));\n object += json::object_t::value_type(\"four\", 4);\n null += json::object_t::value_type(\"A\", \"a\");\n null += json::object_t::value_type(\"B\", \"b\");\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n{\"A\":\"a\",\"B\":\"b\"}\n Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json object = {{\"one\", 1}, {\"two\", 2}};\n json null;\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // add values:\n object.push_back({\"three\", 3}); // object is extended\n object += {\"four\", 4}; // object is extended\n null.push_back({\"five\", 5}); // null is converted to array\n\n // print values\n std::cout << object << '\\n';\n std::cout << null << '\\n';\n\n // would throw:\n //object.push_back({1, 2, 3});\n}\n Output:
{\"one\":1,\"two\":2}\nnull\n{\"four\":4,\"one\":1,\"three\":3,\"two\":2}\n[[\"five\",5]]\n"},{"location":"api/basic_json/push_back/#see-also","title":"See also","text":"reverse_iterator rbegin() noexcept;\nconst_reverse_iterator rbegin() const noexcept;\n Returns an iterator to the reverse-beginning; that is, the last element.
"},{"location":"api/basic_json/rbegin/#return-value","title":"Return value","text":"reverse iterator to the first element
"},{"location":"api/basic_json/rbegin/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/rbegin/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/rbegin/#examples","title":"Examples","text":"ExampleThe following code shows an example for rbegin().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-beginning\n json::reverse_iterator it = array.rbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n Output:
5\n"},{"location":"api/basic_json/rbegin/#version-history","title":"Version history","text":"reverse_iterator rend() noexcept;\nconst_reverse_iterator rend() const noexcept;\n Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.
"},{"location":"api/basic_json/rend/#return-value","title":"Return value","text":"reverse iterator to the element following the last element
"},{"location":"api/basic_json/rend/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/rend/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/rend/#examples","title":"Examples","text":"ExampleThe following code shows an example for eend().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-end\n json::reverse_iterator it = array.rend();\n\n // increment the iterator to point to the first element\n --it;\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n Output:
1\n"},{"location":"api/basic_json/rend/#version-history","title":"Version history","text":"// (1)\ntemplate <typename InputType, typename SAX>\nstatic bool sax_parse(InputType&& i,\n SAX* sax,\n input_format_t format = input_format_t::json,\n const bool strict = true,\n const bool ignore_comments = false);\n\n// (2)\ntemplate<class IteratorType, class SAX>\nstatic bool sax_parse(IteratorType first, IteratorType last,\n SAX* sax,\n input_format_t format = input_format_t::json,\n const bool strict = true,\n const bool ignore_comments = false);\n Read from input and generate SAX events
Read from a pair of character iterators
The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
The SAX event lister must follow the interface of json_sax.
InputType A compatible input, for instance:
std::istream objectFILE pointerobj for which begin(obj) and end(obj) produces a valid pair of iterators.IteratorType Description SAX Description"},{"location":"api/basic_json/sax_parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. sax (in) SAX event listener format (in) the format to parse (JSON, CBOR, MessagePack, or UBJSON) (optional, input_format_t::json by default), see input_format_t for more information strict (in) whether the input has to be consumed completely (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/sax_parse/#return-value","title":"Return value","text":"return value of the last processed SAX event
"},{"location":"api/basic_json/sax_parse/#exception-safety","title":"Exception safety","text":""},{"location":"api/basic_json/sax_parse/#complexity","title":"Complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.
A UTF-8 byte order mark is silently ignored.
"},{"location":"api/basic_json/sax_parse/#examples","title":"Examples","text":"ExampleThe example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/basic_json/sax_parse/#version-history","title":"Version history","text":"ignore_comments added in version 3.9.0.Deprecation
Overload (2) replaces calls to sax_parse with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like sax_parse({ptr, ptr+len}); with sax_parse(ptr, ptr+len);.
size_type size() const noexcept;\n Returns the number of elements in a JSON value.
"},{"location":"api/basic_json/size/#return-value","title":"Return value","text":"The return value depends on the different types and is defined as follows:
Value type return value null0 boolean 1 string 1 number 1 binary 1 object result of function object_t::size() array result of function array_t::size()"},{"location":"api/basic_json/size/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/basic_json/size/#complexity","title":"Complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.
This function does not return the length of a string stored as JSON value -- it returns the number of elements in the JSON value which is 1 in the case of a string.
The following code calls size() on the different value types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_object_empty(json::value_t::object);\n json j_array = {1, 2, 4, 8, 16};\n json j_array_empty(json::value_t::array);\n json j_string = \"Hello, world\";\n\n // call size()\n std::cout << j_null.size() << '\\n';\n std::cout << j_boolean.size() << '\\n';\n std::cout << j_number_integer.size() << '\\n';\n std::cout << j_number_float.size() << '\\n';\n std::cout << j_object.size() << '\\n';\n std::cout << j_object_empty.size() << '\\n';\n std::cout << j_array.size() << '\\n';\n std::cout << j_array_empty.size() << '\\n';\n std::cout << j_string.size() << '\\n';\n}\n Output:
0\n1\n1\n1\n2\n0\n5\n0\n1\n"},{"location":"api/basic_json/size/#version-history","title":"Version history","text":"1 for binary types in version 3.8.0.namespace std {\n struct hash<nlohmann::basic_json>;\n}\n Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.
The example shows how to calculate hash values for different JSON values.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n std::cout << \"hash(null) = \" << std::hash<json> {}(json(nullptr)) << '\\n'\n << \"hash(false) = \" << std::hash<json> {}(json(false)) << '\\n'\n << \"hash(0) = \" << std::hash<json> {}(json(0)) << '\\n'\n << \"hash(0U) = \" << std::hash<json> {}(json(0U)) << '\\n'\n << \"hash(\\\"\\\") = \" << std::hash<json> {}(json(\"\")) << '\\n'\n << \"hash({}) = \" << std::hash<json> {}(json::object()) << '\\n'\n << \"hash([]) = \" << std::hash<json> {}(json::array()) << '\\n'\n << \"hash({\\\"hello\\\": \\\"world\\\"}) = \" << std::hash<json> {}(\"{\\\"hello\\\": \\\"world\\\"}\"_json)\n << std::endl;\n}\n Output:
hash(null) = 2654435769\nhash(false) = 2654436030\nhash(0) = 2654436095\nhash(0U) = 2654436156\nhash(\"\") = 6142509191626859748\nhash({}) = 2654435832\nhash([]) = 2654435899\nhash({\"hello\": \"world\"}) = 4469488738203676328\n Note the output is platform-dependent.
"},{"location":"api/basic_json/std_hash/#version-history","title":"Version history","text":"namespace std {\n void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2);\n}\n Exchanges the values of two JSON objects.
"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"void swap(nlohmann::basic_json& j1, nlohmann::basic_json& j2)\n{\n j1.swap(j2);\n}\n"},{"location":"api/basic_json/std_swap/#examples","title":"Examples","text":"Example The following code shows how two values are swapped with std::swap.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j1 = {{\"one\", 1}, {\"two\", 2}};\n json j2 = {1, 2, 4, 8, 16};\n\n std::cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n';\n\n // swap values\n std::swap(j1, j2);\n\n std::cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std::endl;\n}\n Output:
j1 = {\"one\":1,\"two\":2} | j2 = [1,2,4,8,16]\nj1 = [1,2,4,8,16] | j2 = {\"one\":1,\"two\":2}\n"},{"location":"api/basic_json/std_swap/#see-also","title":"See also","text":"using string_t = StringType;\n The type used to store JSON strings.
RFC 8259 describes JSON strings as follows:
A string is a sequence of zero or more Unicode characters.
To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.
"},{"location":"api/basic_json/string_t/#template-parameters","title":"Template parameters","text":"StringType the container to store strings (e.g., std::string). Note this container is used for keys/names in objects, see object_t."},{"location":"api/basic_json/string_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/string_t/#default-type","title":"Default type","text":"With the default values for StringType (std::string), the default value for string_t is std::string.
Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.
RFC 8259 states:
Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal.
This implementation is interoperable as it does compare strings code unit by code unit.
"},{"location":"api/basic_json/string_t/#storage","title":"Storage","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.
The following code shows that string_t is by default, a typedef to std::string.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::boolalpha << std::is_same<std::string, json::string_t>::value << std::endl;\n}\n Output:
true\n"},{"location":"api/basic_json/string_t/#version-history","title":"Version history","text":"// (1)\nvoid swap(reference other) noexcept;\n\n// (2)\nvoid swap(reference left, reference right) noexcept;\n\n// (3)\nvoid swap(array_t& other);\n\n// (4)\nvoid swap(object_t& other);\n\n// (5)\nvoid swap(string_t& other);\n\n// (6)\nvoid swap(binary_t& other);\n\n// (7)\nvoid swap(typename binary_t::container_type& other);\n other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. left with those of right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Implemented as a friend function callable via ADL.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike version (6), no binary subtype is involved.other (in, out) value to exchange the contents with left (in, out) value to exchange the contents with right (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"type_error.310 if called on JSON values other than arrays; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than objects; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than strings; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"Constant.
"},{"location":"api/basic_json/swap/#examples","title":"Examples","text":"Example: Swap JSON value (1, 2)The example below shows how JSON values can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create two JSON values\n json j1 = {1, 2, 3, 4, 5};\n json j2 = {{\"pi\", 3.141592653589793}, {\"e\", 2.718281828459045}};\n\n // swap the values\n j1.swap(j2);\n\n // output the values\n std::cout << \"j1 = \" << j1 << '\\n';\n std::cout << \"j2 = \" << j2 << '\\n';\n}\n Output:
j1 = {\"e\":2.718281828459045,\"pi\":3.141592653589793}\nj2 = [1,2,3,4,5]\n Example: Swap array (3) The example below shows how arrays can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = {{\"array\", {1, 2, 3, 4}}};\n\n // create an array_t\n json::array_t array = {\"Snap\", \"Crackle\", \"Pop\"};\n\n // swap the array stored in the JSON value\n value[\"array\"].swap(array);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"array = \" << array << '\\n';\n}\n Output:
value = {\"array\":[\"Snap\",\"Crackle\",\"Pop\"]}\narray = [1,2,3,4]\n Example: Swap object (4) The example below shows how objects can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { {\"translation\", {{\"one\", \"eins\"}, {\"two\", \"zwei\"}}} };\n\n // create an object_t\n json::object_t object = {{\"cow\", \"Kuh\"}, {\"dog\", \"Hund\"}};\n\n // swap the object stored in the JSON value\n value[\"translation\"].swap(object);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"object = \" << object << '\\n';\n}\n Output:
value = {\"translation\":{\"cow\":\"Kuh\",\"dog\":\"Hund\"}}\nobject = {\"one\":\"eins\",\"two\":\"zwei\"}\n Example: Swap string (5) The example below shows how strings can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { \"the good\", \"the bad\", \"the ugly\" };\n\n // create string_t\n json::string_t string = \"the fast\";\n\n // swap the object stored in the JSON value\n value[1].swap(string);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"string = \" << string << '\\n';\n}\n Output:
value = [\"the good\",\"the fast\",\"the ugly\"]\nstring = the bad\n Example: Swap string (6) The example below shows how binary values can be swapped with swap().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary value\n json value = json::binary({1, 2, 3});\n\n // create a binary_t\n json::binary_t binary = {{4, 5, 6}};\n\n // swap the object stored in the JSON value\n value.swap(binary);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"binary = \" << json(binary) << '\\n';\n}\n Output:
value = {\"bytes\":[4,5,6],\"subtype\":null}\nbinary = {\"bytes\":[1,2,3],\"subtype\":null}\n"},{"location":"api/basic_json/swap/#see-also","title":"See also","text":"// (1)\nstatic std::vector<std::uint8_t> to_bjdata(const basic_json& j,\n const bool use_size = false,\n const bool use_type = false);\n\n// (2)\nstatic void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,\n const bool use_size = false, const bool use_type = false);\nstatic void to_bjdata(const basic_json& j, detail::output_adapter<char> o,\n const bool use_size = false, const bool use_type = false);\n Serializes a given JSON value j to a byte vector using the BJData (Binary JData) serialization format. BJData aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_bjdata/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in BJData format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print BJData's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to BJData\n std::vector<std::uint8_t> v = json::to_bjdata(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to BJData using default representation\n std::vector<std::uint8_t> v_array = json::to_bjdata(array);\n // serialize it to BJData using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);\n // serialize it to BJData using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"api/basic_json/to_bjdata/#version-history","title":"Version history","text":"// (1)\nstatic std::vector<std::uint8_t> to_bson(const basic_json& j);\n\n// (2)\nstatic void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_bson(const basic_json& j, detail::output_adapter<char> o);\n BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document).
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_bson/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in BSON format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector<std::uint8_t> v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 \n"},{"location":"api/basic_json/to_bson/#version-history","title":"Version history","text":"// (1)\nstatic std::vector<std::uint8_t> to_cbor(const basic_json& j);\n\n// (2)\nstatic void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_cbor(const basic_json& j, detail::output_adapter<char> o);\n Serializes a given JSON value j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_cbor/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in CBOR format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to CBOR\n std::vector<std::uint8_t> v = json::to_cbor(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"api/basic_json/to_cbor/#version-history","title":"Version history","text":"// (1)\nstatic std::vector<std::uint8_t> to_msgpack(const basic_json& j);\n\n// (2)\nstatic void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o);\nstatic void to_msgpack(const basic_json& j, detail::output_adapter<char> o);\n Serializes a given JSON value j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_msgpack/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in MessagePack format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"api/basic_json/to_msgpack/#version-history","title":"Version history","text":"template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j);\n This function implements a user-defined to_string for JSON objects.
"},{"location":"api/basic_json/to_string/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/basic_json/to_string/#return-value","title":"Return value","text":"string containing the serialization of the JSON value
"},{"location":"api/basic_json/to_string/#exception-safety","title":"Exception safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/to_string/#exceptions","title":"Exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded
Linear.
"},{"location":"api/basic_json/to_string/#possible-implementation","title":"Possible implementation","text":"template <typename BasicJsonType>\nstd::string to_string(const BasicJsonType& j)\n{\n return j.dump();\n}\n"},{"location":"api/basic_json/to_string/#examples","title":"Examples","text":"Example The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing std::to_string;\n\nint main()\n{\n // create values\n json j = {{\"one\", 1}, {\"two\", 2}};\n int i = 42;\n\n // use ADL to select best to_string function\n auto j_str = to_string(j); // calling nlohmann::to_string\n auto i_str = to_string(i); // calling std::to_string\n\n // serialize without indentation\n std::cout << j_str << \"\\n\\n\"\n << i_str << std::endl;\n}\n Output:
{\"one\":1,\"two\":2}\n\n42\n"},{"location":"api/basic_json/to_string/#see-also","title":"See also","text":"Added in version 3.7.0.
"},{"location":"api/basic_json/to_ubjson/","title":"nlohmann::basic_json::to_ubjson","text":"// (1)\nstatic std::vector<std::uint8_t> to_ubjson(const basic_json& j,\n const bool use_size = false,\n const bool use_type = false);\n\n// (2)\nstatic void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,\n const bool use_size = false, const bool use_type = false);\nstatic void to_ubjson(const basic_json& j, detail::output_adapter<char> o,\n const bool use_size = false, const bool use_type = false);\n Serializes a given JSON value j to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
"},{"location":"api/basic_json/to_ubjson/#complexity","title":"Complexity","text":"Linear in the size of the JSON value j.
The example shows the serialization of a JSON value to a byte vector in UBJSON format.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print UBJSON's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to UBJSON\n std::vector<std::uint8_t> v = json::to_ubjson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to UBJSON using default representation\n std::vector<std::uint8_t> v_array = json::to_ubjson(array);\n // serialize it to UBJSON using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);\n // serialize it to UBJSON using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"api/basic_json/to_ubjson/#version-history","title":"Version history","text":"constexpr value_t type() const noexcept;\n Return the type of the JSON value as a value from the value_t enumeration.
the type of the JSON value
Value type return valuenull value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded"},{"location":"api/basic_json/type/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/type/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/type/#examples","title":"Examples","text":"ExampleThe following code exemplifies type() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type()\n std::cout << std::boolalpha;\n std::cout << (j_null.type() == json::value_t::null) << '\\n';\n std::cout << (j_boolean.type() == json::value_t::boolean) << '\\n';\n std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\\n';\n std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\\n';\n std::cout << (j_number_float.type() == json::value_t::number_float) << '\\n';\n std::cout << (j_object.type() == json::value_t::object) << '\\n';\n std::cout << (j_array.type() == json::value_t::array) << '\\n';\n std::cout << (j_string.type() == json::value_t::string) << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n"},{"location":"api/basic_json/type/#version-history","title":"Version history","text":"class type_error : public exception;\n This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx (see list of type errors).
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_type_error fill:#CCCCFF"},{"location":"api/basic_json/type_error/#member-functions","title":"Member functions","text":"The following code shows how a type_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling push_back() on a string value\n json j = \"string\";\n j.push_back(\"another string\");\n }\n catch (const json::type_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n"},{"location":"api/basic_json/type_error/#see-also","title":"See also","text":"parse_error for exceptions indicating a parse errorinvalid_iterator for exceptions indicating errors with iteratorsout_of_range for exceptions indicating access out of the defined rangeother_error for exceptions indicating other library errorsconst char* type_name() const noexcept;\n Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type.
"},{"location":"api/basic_json/type_name/#return-value","title":"Return value","text":"a string representation of the type (value_t):
null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\""},{"location":"api/basic_json/type_name/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/type_name/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/basic_json/type_name/#examples","title":"Examples","text":"ExampleThe following code exemplifies type_name() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type_name()\n std::cout << j_null << \" is a \" << j_null.type_name() << '\\n';\n std::cout << j_boolean << \" is a \" << j_boolean.type_name() << '\\n';\n std::cout << j_number_integer << \" is a \" << j_number_integer.type_name() << '\\n';\n std::cout << j_number_unsigned << \" is a \" << j_number_unsigned.type_name() << '\\n';\n std::cout << j_number_float << \" is a \" << j_number_float.type_name() << '\\n';\n std::cout << j_object << \" is an \" << j_object.type_name() << '\\n';\n std::cout << j_array << \" is an \" << j_array.type_name() << '\\n';\n std::cout << j_string << \" is a \" << j_string.type_name() << '\\n';\n}\n Output:
null is a null\ntrue is a boolean\n-17 is a number\n42 is a number\n23.42 is a number\n{\"one\":1,\"two\":2} is an object\n[1,2,4,8,16] is an array\n\"Hello, world\" is a string\n"},{"location":"api/basic_json/type_name/#version-history","title":"Version history","text":"const char* and added noexcept in version 3.0.0.basic_json unflatten() const;\n The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints:
the original JSON from a flattened version
"},{"location":"api/basic_json/unflatten/#exception-safety","title":"Exception safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.
"},{"location":"api/basic_json/unflatten/#exceptions","title":"Exceptions","text":"The function can throw the following exceptions:
type_error.314 if value is not an objecttype_error.315 if object values are not primitiveLinear in the size the JSON value.
"},{"location":"api/basic_json/unflatten/#notes","title":"Notes","text":"Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j, the following is always true: j == j.flatten().unflatten().
The following code shows how a flattened JSON object is unflattened into the original nested JSON object.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON value\n json j_flattened =\n {\n {\"/answer/everything\", 42},\n {\"/happy\", true},\n {\"/list/0\", 1},\n {\"/list/1\", 0},\n {\"/list/2\", 2},\n {\"/name\", \"Niels\"},\n {\"/nothing\", nullptr},\n {\"/object/currency\", \"USD\"},\n {\"/object/value\", 42.99},\n {\"/pi\", 3.141}\n };\n\n // call unflatten()\n std::cout << std::setw(4) << j_flattened.unflatten() << '\\n';\n}\n Output:
{\n \"answer\": {\n \"everything\": 42\n },\n \"happy\": true,\n \"list\": [\n 1,\n 0,\n 2\n ],\n \"name\": \"Niels\",\n \"nothing\": null,\n \"object\": {\n \"currency\": \"USD\",\n \"value\": 42.99\n },\n \"pi\": 3.141\n}\n"},{"location":"api/basic_json/unflatten/#see-also","title":"See also","text":"// (1)\nvoid update(const_reference j, bool merge_objects = false);\n\n// (2)\nvoid update(const_iterator first, const_iterator last, bool merge_objects = false);\n j.[first, last)When merge_objects is false (default), existing keys are overwritten. When merge_objects is true, recursively merges objects with common keys.
The function is motivated by Python's dict.update function.
"},{"location":"api/basic_json/update/#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.
j (in) JSON object to read values from merge_objects (in) when true, existing keys are not overwritten, but contents of objects are merged recursively (default: false) first (in) begin of the range of elements to insert last (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"The example shows how update() is used.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create two JSON objects\n json o1 = R\"( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} )\"_json;\n json o2 = R\"( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} )\"_json;\n json o3 = o1;\n\n // add all keys from o2 to o1 (updating \"color\", replacing \"names\")\n o1.update(o2);\n\n // add all keys from o2 to o1 (updating \"color\", merging \"names\")\n o3.update(o2, true);\n\n // output updated object o1 and o3\n std::cout << std::setw(2) << o1 << '\\n';\n std::cout << std::setw(2) << o3 << '\\n';\n}\n Output:
{\n \"color\": \"blue\",\n \"names\": {\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n{\n \"color\": \"blue\",\n \"names\": {\n \"de\": \"Flugzeug\",\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n Example The example shows how update() is used.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create two JSON objects\n json o1 = R\"( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} )\"_json;\n json o2 = R\"( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} )\"_json;\n json o3 = o1;\n\n // add all keys from o2 to o1 (updating \"color\", replacing \"names\")\n o1.update(o2.begin(), o2.end());\n\n // add all keys from o2 to o1 (updating \"color\", merging \"names\")\n o3.update(o2.begin(), o2.end(), true);\n\n // output updated object o1 and o3\n std::cout << std::setw(2) << o1 << '\\n';\n std::cout << std::setw(2) << o3 << '\\n';\n}\n Output:
{\n \"color\": \"blue\",\n \"names\": {\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n{\n \"color\": \"blue\",\n \"names\": {\n \"de\": \"Flugzeug\",\n \"en\": \"plane\"\n },\n \"price\": 17.99,\n \"speed\": 100\n}\n Example One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects:
{\n \"color\": \"red\",\n \"active\": true,\n \"name\": {\"de\": \"Maus\", \"en\": \"mouse\"}\n}\n The user may override the default settings selectively:
{\n \"color\": \"blue\",\n \"name\": {\"es\": \"rat\u00f3n\"},\n}\n Then update manages the merging of default settings and user settings:
auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings);\n Now effective_settings contains the default settings, but those keys set by the user are overwritten:
{\n \"color\": \"blue\",\n \"active\": true,\n \"name\": {\"es\": \"rat\u00f3n\"}\n}\n Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true:
auto user_settings = json::parse(\"config.json\");\nauto effective_settings = get_default_settings();\neffective_settings.update(user_settings, true);\n {\n \"color\": \"blue\",\n \"active\": true,\n \"name\": {\"de\": \"Maus\", \"en\": \"mouse\", \"es\": \"rat\u00f3n\"}\n}\n"},{"location":"api/basic_json/update/#version-history","title":"Version history","text":"merge_objects parameter in 3.10.5.// (1)\ntemplate<class ValueType>\nValueType value(const typename object_t::key_type& key,\n ValueType&& default_value) const;\n\n// (2)\ntemplate<class ValueType, class KeyType>\nValueType value(KeyType&& key,\n ValueType&& default_value) const;\n\n// (3)\ntemplate<class ValueType>\nValueType value(const json_pointer& ptr,\n const ValueType& default_value) const;\n Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.
The function is basically equivalent to executing
try {\n return at(key);\n} catch(out_of_range) {\n return default_value;\n}\n 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.
Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists.
The function is basically equivalent to executing
try {\n return at(ptr);\n} catch(out_of_range) {\n return default_value;\n}\n Differences to at and operator[]
at, this function does not throw if the given key/ptr was not found.operator[], this function does not implicitly add an element to the position defined by key/ptr key. This function is furthermore also applicable to const objects.KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17). ValueType type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"key (in) key of the element to access default_value (in) the value to return if key/ptr found no value ptr (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"key or default_value if key is not foundkey or default_value if key is not foundptr or default_value if no value for ptr is foundStrong guarantee: if an exception is thrown, there are no changes to any JSON value.
"},{"location":"api/basic_json/value/#exceptions","title":"Exceptions","text":"type_error.302 if default_value does not match the type of the value at keytype_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.type_error.302 if default_value does not match the type of the value at ptrtype_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.The example below shows how object elements can be queried with a default value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"integer\", 0);\n double v_floating = j.value(\"floating\", 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"nonexisting\", \"oops\");\n bool v_boolean = j.value(\"nonexisting\", false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n Output:
1 42.23 oops false\n Example: (2) access specified object element using string_view with default value The example below shows how object elements can be queried with a default value.
#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"integer\"sv, 0);\n double v_floating = j.value(\"floating\"sv, 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"nonexisting\"sv, \"oops\");\n bool v_boolean = j.value(\"nonexisting\"sv, false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n Output:
1 42.23 oops false\n Example: (3) access specified object element via JSON Pointer with default value The example below shows how object elements can be queried with a default value.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON object with different entry types\n json j =\n {\n {\"integer\", 1},\n {\"floating\", 42.23},\n {\"string\", \"hello world\"},\n {\"boolean\", true},\n {\"object\", {{\"key1\", 1}, {\"key2\", 2}}},\n {\"array\", {1, 2, 3}}\n };\n\n // access existing values\n int v_integer = j.value(\"/integer\"_json_pointer, 0);\n double v_floating = j.value(\"/floating\"_json_pointer, 47.11);\n\n // access nonexisting values and rely on default value\n std::string v_string = j.value(\"/nonexisting\"_json_pointer, \"oops\");\n bool v_boolean = j.value(\"/nonexisting\"_json_pointer, false);\n\n // output values\n std::cout << std::boolalpha << v_integer << \" \" << v_floating\n << \" \" << v_string << \" \" << v_boolean << \"\\n\";\n}\n Output:
1 42.23 oops false\n"},{"location":"api/basic_json/value/#see-also","title":"See also","text":"at for access by reference with range checkingoperator[] for unchecked access by referencedefault_value type from const ValueType& to ValueType&& in version 3.11.0.ValueType the first template parameter in version 3.11.2.enum class value_t : std::uint8_t {\n null,\n object,\n array,\n string,\n boolean,\n number_integer,\n number_unsigned,\n number_float,\n binary,\n discarded\n};\n This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions is_null, is_object, is_array, is_string, is_boolean, is_number (with is_number_integer, is_number_unsigned, and is_number_float), is_discarded, is_binary, is_primitive, and is_structured rely on it.
Ordering
The order of types is as follows:
nullbooleannumber_integer, number_unsigned, number_floatobjectarraystringbinarydiscarded is unordered.
Types of numbers
There are three enumerators for numbers (number_integer, number_unsigned, and number_float) to distinguish between different types of numbers:
number_unsigned_t for unsigned integersnumber_integer_t for signed integersnumber_float_t for floating-point numbers or to approximate integers which do not fit into the limits of their respective typeComparison operators
operator< and operator<=> (since C++20) are overloaded and compare according to the ordering described above. Until C++20 all other relational and equality operators yield results according to the integer value of each enumerator. Since C++20 some compilers consider the rewritten candidates generated from operator<=> during overload resolution, while others do not. For predictable and portable behavior use:
operator< or operator<=> when wanting to compare according to the order described aboveoperator== or operator!= when wanting to compare according to each enumerators integer valueThe following code how type() queries the value_t for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type()\n std::cout << std::boolalpha;\n std::cout << (j_null.type() == json::value_t::null) << '\\n';\n std::cout << (j_boolean.type() == json::value_t::boolean) << '\\n';\n std::cout << (j_number_integer.type() == json::value_t::number_integer) << '\\n';\n std::cout << (j_number_unsigned.type() == json::value_t::number_unsigned) << '\\n';\n std::cout << (j_number_float.type() == json::value_t::number_float) << '\\n';\n std::cout << (j_object.type() == json::value_t::object) << '\\n';\n std::cout << (j_array.type() == json::value_t::array) << '\\n';\n std::cout << (j_string.type() == json::value_t::string) << '\\n';\n}\n Output:
true\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\ntrue\n"},{"location":"api/basic_json/value_t/#version-history","title":"Version history","text":"~basic_json() noexcept;\n Destroys the JSON value and frees all allocated memory.
"},{"location":"api/basic_json/~basic_json/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this member function never throws exceptions.
"},{"location":"api/basic_json/~basic_json/#complexity","title":"Complexity","text":"Linear.
"},{"location":"api/basic_json/~basic_json/#version-history","title":"Version history","text":"template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n This type extends the template parameter BinaryType provided to basic_json with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type.
BinaryType container to store bytes (std::vector<std::uint8_t> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":"BinaryType)std::uint64_t)std::uint64_t in 3.10.0.// (1)\nbyte_container_with_subtype();\n\n// (2)\nbyte_container_with_subtype(const container_type& container);\nbyte_container_with_subtype(container_type&& container);\n\n// (3)\nbyte_container_with_subtype(const container_type& container, subtype_type subtype);\nbyte_container_with_subtype(container_type&& container, subtype_type subtype);\n container (in) binary container subtype (in) subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","title":"Examples","text":"Example The example below demonstrates how byte containers can be created.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n // (1) create empty container\n auto c1 = byte_container_with_subtype();\n\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // (2) create container\n auto c2 = byte_container_with_subtype(bytes);\n\n // (3) create container with subtype\n auto c3 = byte_container_with_subtype(bytes, 42);\n\n std::cout << json(c1) << \"\\n\" << json(c2) << \"\\n\" << json(c3) << std::endl;\n}\n Output:
{\"bytes\":[],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":42}\n"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/clear_subtype/","title":"nlohmann::byte_container_with_subtype::clear_subtype","text":"void clear_subtype() noexcept;\n Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for instance MessagePack will prefer the bin family over the ext family.
"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how clear_subtype can remove subtypes.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container with subtype\n auto c1 = byte_container_with_subtype(bytes, 42);\n\n std::cout << \"before calling clear_subtype(): \" << json(c1) << '\\n';\n\n c1.clear_subtype();\n\n std::cout << \"after calling clear_subtype(): \" << json(c1) << '\\n';\n}\n Output:
before calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":42}\nafter calling clear_subtype(): {\"bytes\":[202,254,186,190],\"subtype\":null}\n"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/has_subtype/","title":"nlohmann::byte_container_with_subtype::has_subtype","text":"constexpr bool has_subtype() const noexcept;\n Returns whether the value has a subtype.
"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","title":"Return value","text":"whether the value has a subtype
"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how has_subtype can check whether a subtype was set.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container\n auto c1 = byte_container_with_subtype(bytes);\n\n // create container with subtype\n auto c2 = byte_container_with_subtype(bytes, 42);\n\n std::cout << std::boolalpha << \"c1.has_subtype() = \" << c1.has_subtype()\n << \"\\nc2.has_subtype() = \" << c2.has_subtype() << std::endl;\n}\n Output:
c1.has_subtype() = false\nc2.has_subtype() = true\n"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/set_subtype/","title":"nlohmann::byte_container_with_subtype::set_subtype","text":"void set_subtype(subtype_type subtype) noexcept;\n Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.
"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","title":"Parameters","text":"subtype (in) subtype to set"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","title":"Exception safety","text":"No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how a subtype can be set with set_subtype.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container without subtype\n auto c = byte_container_with_subtype(bytes);\n\n std::cout << \"before calling set_subtype(42): \" << json(c) << '\\n';\n\n // set the subtype\n c.set_subtype(42);\n\n std::cout << \"after calling set_subtype(42): \" << json(c) << '\\n';\n}\n Output:
before calling set_subtype(42): {\"bytes\":[202,254,186,190],\"subtype\":null}\nafter calling set_subtype(42): {\"bytes\":[202,254,186,190],\"subtype\":42}\n"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","title":"Version history","text":"Since version 3.8.0.
"},{"location":"api/byte_container_with_subtype/subtype/","title":"nlohmann::byte_container_with_subtype::subtype","text":"constexpr subtype_type subtype() const noexcept;\n Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return subtype_type(-1) as a sentinel value.
the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/byte_container_with_subtype/subtype/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/byte_container_with_subtype/subtype/#examples","title":"Examples","text":"ExampleThe example below demonstrates how the subtype can be retrieved with subtype. Note how subtype_type(-1) is returned for container c1.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// define a byte container based on std::vector\nusing byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;\n\nint main()\n{\n std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};\n\n // create container\n auto c1 = byte_container_with_subtype(bytes);\n\n // create container with subtype\n auto c2 = byte_container_with_subtype(bytes, 42);\n\n std::cout << \"c1.subtype() = \" << c1.subtype()\n << \"\\nc2.subtype() = \" << c2.subtype() << std::endl;\n\n // in case no subtype is set, return special value\n assert(c1.subtype() == static_cast<byte_container_with_subtype::subtype_type>(-1));\n}\n Output:
c1.subtype() = 18446744073709551615\nc2.subtype() = 42\n"},{"location":"api/byte_container_with_subtype/subtype/#version-history","title":"Version history","text":"subtype_type(-1) as documented in version 3.10.0.template<typename RefStringType>\nclass json_pointer;\n A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.
RefStringType the string type used for the reference tokens making up the JSON pointer Deprecation
For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.
basic_json to string type in version 3.11.0.const string_t& back() const;\n Return last reference token.
"},{"location":"api/json_pointer/back/#return-value","title":"Return value","text":"Last reference token.
"},{"location":"api/json_pointer/back/#exceptions","title":"Exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.
"},{"location":"api/json_pointer/back/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/json_pointer/back/#examples","title":"Examples","text":"ExampleThe example shows the usage of back.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo\");\n json::json_pointer ptr2(\"/foo/0\");\n\n // call empty()\n std::cout << \"last reference token of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.back() << \"\\\"\\n\"\n << \"last reference token of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.back() << \"\\\"\" << std::endl;\n}\n Output:
last reference token of \"/foo\" is \"foo\"\nlast reference token of \"/foo/0\" is \"0\"\n"},{"location":"api/json_pointer/back/#version-history","title":"Version history","text":"string_t in version 3.11.0.bool empty() const noexcept;\n Return whether pointer points to the root document.
"},{"location":"api/json_pointer/empty/#return-value","title":"Return value","text":"true iff the JSON pointer points to the root document.
No-throw guarantee: this function never throws exceptions.
"},{"location":"api/json_pointer/empty/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/json_pointer/empty/#examples","title":"Examples","text":"ExampleThe example shows the result of empty for different JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n\n // call empty()\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\": \" << ptr0.empty() << '\\n'\n << \"\\\"\" << ptr1 << \"\\\": \" << ptr1.empty() << '\\n'\n << \"\\\"\" << ptr2 << \"\\\": \" << ptr2.empty() << '\\n'\n << \"\\\"\" << ptr3 << \"\\\": \" << ptr3.empty() << std::endl;\n}\n Output:
\"\": true\n\"\": true\n\"/foo\": false\n\"/foo/0\": false\n"},{"location":"api/json_pointer/empty/#version-history","title":"Version history","text":"Added in version 3.6.0.
"},{"location":"api/json_pointer/json_pointer/","title":"nlohmann::json_pointer::json_pointer","text":"explicit json_pointer(const string_t& s = \"\");\n Create a JSON pointer according to the syntax described in Section 3 of RFC6901.
"},{"location":"api/json_pointer/json_pointer/#parameters","title":"Parameters","text":"s (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value"},{"location":"api/json_pointer/json_pointer/#exceptions","title":"Exceptions","text":"s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.The example shows the construction several valid JSON pointers as well as the exceptional behavior.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // correct JSON pointers\n json::json_pointer p1;\n json::json_pointer p2(\"\");\n json::json_pointer p3(\"/\");\n json::json_pointer p4(\"//\");\n json::json_pointer p5(\"/foo/bar\");\n json::json_pointer p6(\"/foo/bar/-\");\n json::json_pointer p7(\"/foo/~0\");\n json::json_pointer p8(\"/foo/~1\");\n\n // error: JSON pointer does not begin with a slash\n try\n {\n json::json_pointer p9(\"foo\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // error: JSON pointer uses escape symbol ~ not followed by 0 or 1\n try\n {\n json::json_pointer p10(\"/foo/~\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // error: JSON pointer uses escape symbol ~ not followed by 0 or 1\n try\n {\n json::json_pointer p11(\"/foo/~3\");\n }\n catch (const json::parse_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n"},{"location":"api/json_pointer/json_pointer/#version-history","title":"Version history","text":"s to string_t in version 3.11.0.// until C++20\ntemplate<typename RefStringTypeLhs, typename RefStringTypeRhs>\nbool operator==(\n const json_pointer<RefStringTypeLhs>& lhs,\n const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)\n\ntemplate<typename RefStringTypeLhs, typename StringType>\nbool operator==(\n const json_pointer<RefStringTypeLhs>& lhs,\n const StringType& rhs); // (2)\n\ntemplate<typename RefStringTypeRhs, typename StringType>\nbool operator==(\n const StringType& lhs,\n const json_pointer<RefStringTypeRhs>& rhs); // (2)\n\n// since C++20\nclass json_pointer {\n template<typename RefStringTypeRhs>\n bool operator==(\n const json_pointer<RefStringTypeRhs>& rhs) const noexcept; // (1)\n\n bool operator==(const string_t& rhs) const; // (2)\n};\n Compares two JSON pointers for equality by comparing their reference tokens.
Compares a JSON pointer and a string or a string and a JSON pointer for equality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.
RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are equal
s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.
Deprecation
Overload 2 is deprecated and will be removed in a future major version release.
"},{"location":"api/json_pointer/operator_eq/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointersThe example demonstrates comparing JSON pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // compare JSON pointers\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << ptr0 << \"\\\": \" << (ptr0 == ptr0) << '\\n'\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << ptr1 << \"\\\": \" << (ptr0 == ptr1) << '\\n'\n << \"\\\"\" << ptr1 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (ptr1 == ptr2) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (ptr2 == ptr2) << std::endl;\n}\n Output:
\"\" == \"\": true\n\"\" == \"\": true\n\"\" == \"/foo\": false\n\"/foo\" == \"/foo\": true\n Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.
#include <exception>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // different strings\n std::string str0(\"\");\n std::string str1(\"/foo\");\n std::string str2(\"bar\");\n\n // compare JSON pointers and strings\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" == \\\"\" << str0 << \"\\\": \" << (ptr0 == str0) << '\\n'\n << \"\\\"\" << str0 << \"\\\" == \\\"\" << ptr1 << \"\\\": \" << (str0 == ptr1) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" == \\\"\" << str1 << \"\\\": \" << (ptr2 == str1) << std::endl;\n\n try\n {\n std::cout << \"\\\"\" << str2 << \"\\\" == \\\"\" << ptr2 << \"\\\": \" << (str2 == ptr2) << std::endl;\n }\n catch (const json::parse_error& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n}\n Output:
\"\" == \"\": true\n\"\" == \"\": true\n\"/foo\" == \"/foo\": true\n\"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'\n"},{"location":"api/json_pointer/operator_eq/#version-history","title":"Version history","text":"// until C++20\ntemplate<typename RefStringTypeLhs, typename RefStringTypeRhs>\nbool operator!=(\n const json_pointer<RefStringTypeLhs>& lhs,\n const json_pointer<RefStringTypeRhs>& rhs) noexcept; // (1)\n\ntemplate<typename RefStringTypeLhs, typename StringType>\nbool operator!=(\n const json_pointer<RefStringTypeLhs>& lhs,\n const StringType& rhs); // (2)\n\ntemplate<typename RefStringTypeRhs, typename StringType>\nbool operator!=(\n const StringType& lhs,\n const json_pointer<RefStringTypeRhs>& rhs); // (2)\n Compares two JSON pointers for inequality by comparing their reference tokens.
Compares a JSON pointer and a string or a string and a JSON pointer for inequality by converting the string to a JSON pointer and comparing the JSON pointers according to 1.
RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"whether the values lhs/*this and rhs are not equal
s is nonempty and does not begin with a slash (/); see example below.~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.
Operator overload resolution
Since C++20 overload resolution will consider the rewritten candidate generated from operator==.
Deprecation
Overload 2 is deprecated and will be removed in a future major version release.
"},{"location":"api/json_pointer/operator_ne/#examples","title":"Examples","text":"Example: (1) Comparing JSON pointersThe example demonstrates comparing JSON pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // compare JSON pointers\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << ptr0 << \"\\\": \" << (ptr0 != ptr0) << '\\n'\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << ptr1 << \"\\\": \" << (ptr0 != ptr1) << '\\n'\n << \"\\\"\" << ptr1 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (ptr1 != ptr2) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (ptr2 != ptr2) << std::endl;\n}\n Output:
\"\" != \"\": false\n\"\" != \"\": false\n\"\" != \"/foo\": true\n\"/foo\" != \"/foo\": false\n Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON pointers\n json::json_pointer ptr0;\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n\n // different strings\n std::string str0(\"\");\n std::string str1(\"/foo\");\n std::string str2(\"bar\");\n\n // compare JSON pointers and strings\n std::cout << std::boolalpha\n << \"\\\"\" << ptr0 << \"\\\" != \\\"\" << str0 << \"\\\": \" << (ptr0 != str0) << '\\n'\n << \"\\\"\" << str0 << \"\\\" != \\\"\" << ptr1 << \"\\\": \" << (str0 != ptr1) << '\\n'\n << \"\\\"\" << ptr2 << \"\\\" != \\\"\" << str1 << \"\\\": \" << (ptr2 != str1) << std::endl;\n\n try\n {\n std::cout << \"\\\"\" << str2 << \"\\\" != \\\"\" << ptr2 << \"\\\": \" << (str2 != ptr2) << std::endl;\n }\n catch (const json::parse_error& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n}\n Output:
\"\" != \"\": false\n\"\" != \"\": false\n\"/foo\" != \"/foo\": false\n\"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'\n"},{"location":"api/json_pointer/operator_ne/#version-history","title":"Version history","text":"// (1)\njson_pointer operator/(const json_pointer& lhs, const json_pointer& rhs);\n\n// (2)\njson_pointer operator/(const json_pointer& lhs, string_t token);\n\n// (3)\njson_pointer operator/(const json_pointer& lhs, std::size_t array_idx);\n lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slash/#return-value","title":"Return value","text":"rhs appended to lhstoken appended to lhsarray_idx appended to lhslhs and rhs.lhs.lhs.The example shows the usage of operator/.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON pointer\n json::json_pointer ptr(\"/foo\");\n\n // append a JSON Pointer\n std::cout << \"\\\"\" << ptr / json::json_pointer(\"/bar/baz\") << \"\\\"\\n\";\n\n // append a string\n std::cout << \"\\\"\" << ptr / \"fob\" << \"\\\"\\n\";\n\n // append an array index\n std::cout << \"\\\"\" << ptr / 42 << \"\\\"\" << std::endl;\n}\n Output:
\"/foo/bar/baz\"\n\"/foo/fob\"\n\"/foo/42\"\n"},{"location":"api/json_pointer/operator_slash/#version-history","title":"Version history","text":"token to string_t in version 3.11.0.// (1)\njson_pointer& operator/=(const json_pointer& ptr);\n\n// (2)\njson_pointer& operator/=(string_t token);\n\n// (3)\njson_pointer& operator/=(std::size_t array_idx)\n ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"ptr appendedtoken appended without escaping tokenarray_idx appendedptr.The example shows the usage of operator/=.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON pointer\n json::json_pointer ptr(\"/foo\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append a JSON Pointer\n ptr /= json::json_pointer(\"/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append a string\n ptr /= \"fob\";\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // append an array index\n ptr /= 42;\n std::cout << \"\\\"\" << ptr << \"\\\"\" << std::endl;\n}\n Output:
\"/foo\"\n\"/foo/bar/baz\"\n\"/foo/bar/baz/fob\"\n\"/foo/bar/baz/fob/42\"\n"},{"location":"api/json_pointer/operator_slasheq/#version-history","title":"Version history","text":"token to string_t in version 3.11.0.operator string_t() const\n Return a string representation of the JSON pointer.
"},{"location":"api/json_pointer/operator_string_t/#return-value","title":"Return value","text":"A string representation of the JSON pointer
"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","title":"Possible implementation","text":"operator string_t() const\n{\n return to_string();\n}\n"},{"location":"api/json_pointer/operator_string_t/#notes","title":"Notes","text":"Deprecation
This function is deprecated in favor of to_string and will be removed in a future major version release.
The example shows how JSON Pointers can be implicitly converted to strings.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo/0\");\n json::json_pointer ptr2(\"/a~1b\");\n\n // implicit conversion to string\n std::string s;\n s += ptr1;\n s += \"\\n\";\n s += ptr2;\n\n std::cout << s << std::endl;\n}\n Output:
/foo/0\n/a~1b\n"},{"location":"api/json_pointer/operator_string_t/#version-history","title":"Version history","text":"string_t and deprecated in version 3.11.0.json_pointer parent_pointer() const;\n Returns the parent of this JSON pointer.
"},{"location":"api/json_pointer/parent_pointer/#return-value","title":"Return value","text":"Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.
"},{"location":"api/json_pointer/parent_pointer/#complexity","title":"Complexity","text":"Linear in the length of the JSON pointer.
"},{"location":"api/json_pointer/parent_pointer/#examples","title":"Examples","text":"ExampleThe example shows the result of parent_pointer for different JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n\n // call parent_pointer()\n std::cout << std::boolalpha\n << \"parent of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.parent_pointer() << \"\\\"\\n\"\n << \"parent of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.parent_pointer() << \"\\\"\\n\"\n << \"parent of \\\"\" << ptr3 << \"\\\" is \\\"\" << ptr3.parent_pointer() << \"\\\"\" << std::endl;\n}\n Output:
parent of \"\" is \"\"\nparent of \"/foo\" is \"\"\nparent of \"/foo/0\" is \"/foo\"\n"},{"location":"api/json_pointer/parent_pointer/#version-history","title":"Version history","text":"Added in version 3.6.0.
"},{"location":"api/json_pointer/pop_back/","title":"nlohmann::json_pointer::pop_back","text":"void pop_back();\n Remove last reference token.
"},{"location":"api/json_pointer/pop_back/#exceptions","title":"Exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.
"},{"location":"api/json_pointer/pop_back/#complexity","title":"Complexity","text":"Constant.
"},{"location":"api/json_pointer/pop_back/#examples","title":"Examples","text":"ExampleThe example shows the usage of pop_back.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr(\"/foo/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call pop_back()\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_back();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}\n Output:
\"/foo/bar/baz\"\n\"/foo/bar\"\n\"/foo\"\n\"\"\n"},{"location":"api/json_pointer/pop_back/#version-history","title":"Version history","text":"Added in version 3.6.0.
"},{"location":"api/json_pointer/push_back/","title":"nlohmann::json_pointer::push_back","text":"void push_back(const string_t& token);\n\nvoid push_back(string_t&& token);\n Append an unescaped token at the end of the reference pointer.
"},{"location":"api/json_pointer/push_back/#parameters","title":"Parameters","text":"token (in) token to add"},{"location":"api/json_pointer/push_back/#complexity","title":"Complexity","text":"Amortized constant.
"},{"location":"api/json_pointer/push_back/#examples","title":"Examples","text":"ExampleThe example shows the result of push_back for different JSON Pointers.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr;\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call push_back()\n ptr.push_back(\"foo\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.push_back(\"0\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.push_back(\"bar\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}\n Output:
\"\"\n\"/foo\"\n\"/foo/0\"\n\"/foo/0/bar\"\n"},{"location":"api/json_pointer/push_back/#version-history","title":"Version history","text":"token to string_t in version 3.11.0.using string_t = RefStringType;\n The string type used for the reference tokens making up the JSON pointer.
See basic_json::string_t for more information.
The example shows the type string_t and its relation to basic_json::string_t.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::json_pointer::string_t s = \"This is a string.\";\n\n std::cout << s << std::endl;\n\n std::cout << std::boolalpha << std::is_same<json::json_pointer::string_t, json::string_t>::value << std::endl;\n}\n Output:
This is a string.\ntrue\n"},{"location":"api/json_pointer/string_t/#version-history","title":"Version history","text":"string_t to_string() const;\n Return a string representation of the JSON pointer.
"},{"location":"api/json_pointer/to_string/#return-value","title":"Return value","text":"A string representation of the JSON pointer
"},{"location":"api/json_pointer/to_string/#notes","title":"Notes","text":"For each JSON pointer ptr, it holds:
ptr == json_pointer(ptr.to_string());\n"},{"location":"api/json_pointer/to_string/#examples","title":"Examples","text":"Example The example shows the result of to_string.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"\");\n json::json_pointer ptr2(\"/foo\");\n json::json_pointer ptr3(\"/foo/0\");\n json::json_pointer ptr4(\"/\");\n json::json_pointer ptr5(\"/a~1b\");\n json::json_pointer ptr6(\"/c%d\");\n json::json_pointer ptr7(\"/e^f\");\n json::json_pointer ptr8(\"/g|h\");\n json::json_pointer ptr9(\"/i\\\\j\");\n json::json_pointer ptr10(\"/k\\\"l\");\n json::json_pointer ptr11(\"/ \");\n json::json_pointer ptr12(\"/m~0n\");\n\n std::cout << \"\\\"\" << ptr1.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr2.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr3.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr4.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr5.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr6.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr7.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr8.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr9.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr10.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr11.to_string() << \"\\\"\\n\"\n << \"\\\"\" << ptr12.to_string() << \"\\\"\" << std::endl;\n}\n Output:
\"\"\n\"/foo\"\n\"/foo/0\"\n\"/\"\n\"/a~1b\"\n\"/c%d\"\n\"/e^f\"\n\"/g|h\"\n\"/i\\j\"\n\"/k\"l\"\n\"/ \"\n\"/m~0n\"\n"},{"location":"api/json_pointer/to_string/#version-history","title":"Version history","text":"string_t in version 3.11.0.template<typename BasicJsonType>\nstruct json_sax;\n This class describes the SAX interface used by sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input.
"},{"location":"api/json_sax/#template-parameters","title":"Template parameters","text":"BasicJsonType a specialization of basic_json"},{"location":"api/json_sax/#member-types","title":"Member types","text":"BasicJsonType's type for numbers (integer)BasicJsonType's type for numbers (unsigned)BasicJsonType's type for numbers (floating-point)BasicJsonType's type for stringsBasicJsonType's type for binary arraysbinary_t, binary) added in version 3.8.0.virtual bool binary(binary_t& val) = 0;\n A binary value was read.
"},{"location":"api/json_sax/binary/#parameters","title":"Parameters","text":"val (in) binary value"},{"location":"api/json_sax/binary/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/binary/#notes","title":"Notes","text":"It is safe to move the passed binary value.
"},{"location":"api/json_sax/binary/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // CBOR byte string\n std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse CBOR\n bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
binary(val=[...])\n\nresult: true\n"},{"location":"api/json_sax/binary/#version-history","title":"Version history","text":"virtual bool boolean(bool val) = 0;\n A boolean value was read.
"},{"location":"api/json_sax/boolean/#parameters","title":"Parameters","text":"val (in) boolean value"},{"location":"api/json_sax/boolean/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/boolean/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/boolean/#version-history","title":"Version history","text":"virtual bool end_array() = 0;\n The end of an array was read.
"},{"location":"api/json_sax/end_array/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/end_array/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/end_array/#version-history","title":"Version history","text":"virtual bool end_object() = 0;\n The end of an object was read.
"},{"location":"api/json_sax/end_object/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/end_object/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/end_object/#version-history","title":"Version history","text":"virtual bool key(string_t& val) = 0;\n An object key was read.
"},{"location":"api/json_sax/key/#parameters","title":"Parameters","text":"val (in) object key"},{"location":"api/json_sax/key/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/key/#notes","title":"Notes","text":"It is safe to move the passed object key value.
"},{"location":"api/json_sax/key/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/key/#version-history","title":"Version history","text":"virtual bool null() = 0;\n A null value was read.
"},{"location":"api/json_sax/null/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/null/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/null/#version-history","title":"Version history","text":"virtual bool number_float(number_float_t val, const string_t& s) = 0;\n A floating-point number was read.
"},{"location":"api/json_sax/number_float/#parameters","title":"Parameters","text":"val (in) floating-point value s (in) string representation of the original input"},{"location":"api/json_sax/number_float/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/number_float/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/number_float/#version-history","title":"Version history","text":"virtual bool number_integer(number_integer_t val) = 0;\n An integer number was read.
"},{"location":"api/json_sax/number_integer/#parameters","title":"Parameters","text":"val (in) integer value"},{"location":"api/json_sax/number_integer/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/number_integer/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/number_integer/#version-history","title":"Version history","text":"virtual bool number_unsigned(number_unsigned_t val) = 0;\n An unsigned integer number was read.
"},{"location":"api/json_sax/number_unsigned/#parameters","title":"Parameters","text":"val (in) unsigned integer value"},{"location":"api/json_sax/number_unsigned/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/number_unsigned/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/number_unsigned/#version-history","title":"Version history","text":"virtual bool parse_error(std::size_t position,\n const std::string& last_token,\n const detail::exception& ex) = 0;\n A parse error occurred.
"},{"location":"api/json_sax/parse_error/#parameters","title":"Parameters","text":"position (in) the position in the input where the error occurs last_token (in) the last read token ex (in) an exception object describing the error"},{"location":"api/json_sax/parse_error/#return-value","title":"Return value","text":"Whether parsing should proceed (must return false).
The example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/parse_error/#version-history","title":"Version history","text":"virtual bool start_array(std::size_t elements) = 0;\n The beginning of an array was read.
"},{"location":"api/json_sax/start_array/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_array/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/start_array/#notes","title":"Notes","text":"Binary formats may report the number of elements.
"},{"location":"api/json_sax/start_array/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/start_array/#version-history","title":"Version history","text":"virtual bool start_object(std::size_t elements) = 0;\n The beginning of an object was read.
"},{"location":"api/json_sax/start_object/#parameters","title":"Parameters","text":"elements (in) number of object elements or -1 if unknown"},{"location":"api/json_sax/start_object/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/start_object/#notes","title":"Notes","text":"Binary formats may report the number of elements.
"},{"location":"api/json_sax/start_object/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/start_object/#version-history","title":"Version history","text":"virtual bool string(string_t& val) = 0;\n A string value was read.
"},{"location":"api/json_sax/string/#parameters","title":"Parameters","text":"val (in) string value"},{"location":"api/json_sax/string/#return-value","title":"Return value","text":"Whether parsing should proceed.
"},{"location":"api/json_sax/string/#notes","title":"Notes","text":"It is safe to move the passed string value.
"},{"location":"api/json_sax/string/#examples","title":"Examples","text":"ExampleThe example below shows how the SAX interface is used.
#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector<std::string> events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}\n Output:
start_object(elements=18446744073709551615)\nkey(val=Image)\nstart_object(elements=18446744073709551615)\nkey(val=Width)\nnumber_unsigned(val=800)\nkey(val=Height)\nnumber_unsigned(val=600)\nkey(val=Title)\nstring(val=View from 15th Floor)\nkey(val=Thumbnail)\nstart_object(elements=18446744073709551615)\nkey(val=Url)\nstring(val=http://www.example.com/image/481989943)\nkey(val=Height)\nnumber_unsigned(val=125)\nkey(val=Width)\nnumber_unsigned(val=100)\nend_object()\nkey(val=Animated)\nboolean(val=false)\nkey(val=IDs)\nstart_array(elements=18446744073709551615)\nnumber_unsigned(val=116)\nnumber_unsigned(val=943)\nnumber_unsigned(val=234)\nnumber_integer(val=-38793)\nend_array()\nkey(val=DeletionDate)\nnull()\nkey(val=Distance)\nnumber_float(val=12.723375, s=12.723374634)\nend_object()\nend_object()\nparse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],\n ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)\n\nresult: false\n"},{"location":"api/json_sax/string/#version-history","title":"Version history","text":"Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page.
std::filesystem supportstd::ranges supportnlohmann namespaceClass/struct:
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZENLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULTNLOHMANN_DEFINE_TYPE_INTRUSIVENLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZENLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULTNLOHMANN_DEFINE_TYPE_NON_INTRUSIVENLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) - serialization/deserialization of types with access to private variables
#define JSON_ASSERT(x) /* value */\n This macro controls which code is executed for runtime assertions of the library.
"},{"location":"api/macros/json_assert/#parameters","title":"Parameters","text":"x (in) expression of scalar type"},{"location":"api/macros/json_assert/#default-definition","title":"Default definition","text":"The default value is assert(x).
#define JSON_ASSERT(x) assert(x)\n Therefore, assertions can be switched off by defining NDEBUG.
const object). See page runtime assertions for more information.std::abort may leave the library in an undefined state.The following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n Example 2: user-defined behavior The assertion reporting can be changed by defining JSON_ASSERT(x) differently.
#include <cstdio>\n#include <cstdlib>\n#define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();}\n\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n Output:
assertion error in operator[]\n"},{"location":"api/macros/json_assert/#version-history","title":"Version history","text":"#define JSON_DIAGNOSTICS /* value */\n This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).
When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.
"},{"location":"api/macros/json_diagnostics/#default-definition","title":"Default definition","text":"The default value is 0 (extended diagnostics are switched off).
#define JSON_DIAGNOSTICS 0\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_diagnostics/#notes","title":"Notes","text":"ABI compatibility
As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names.
This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior.
Where possible, it is still recommended that all code define this the same way for maximum interoperability.
CMake option
Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which defines JSON_DIAGNOSTICS accordingly.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] type must be number, but is string\n This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.
#include <iostream>\n\n# define JSON_DIAGNOSTICS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.
#define JSON_DISABLE_ENUM_SERIALIZATION /* value */\n When defined to 1, default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details).
Parsing or serializing an enum will result in a compiler error.
This works for both unscoped and scoped enums.
"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","title":"Default definition","text":"The default value is 0.
#define JSON_DISABLE_ENUM_SERIALIZATION 0\n"},{"location":"api/macros/json_disable_enum_serialization/#notes","title":"Notes","text":"CMake option
Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization (OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.
The code below forces the library not to create default serialization/deserialization functions from_json and to_json, meaning the code below does not compile.
#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nint main()\n{\n // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not\n const json j = Choice::first; \n\n // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not\n Choice ch = j.template get<Choice>();\n}\n Example 2: Serialize enum macro The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses NLOHMANN_JSON_SERIALIZE_ENUM to parse and serialize the enum.
#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Choice,\n{\n { Choice::first, \"first\" },\n { Choice::second, \"second\" },\n})\n\nint main()\n{\n // uses user-defined to_json function defined by macro\n const json j = Choice::first; \n\n // uses user-defined from_json function defined by macro\n Choice ch = j.template get<Choice>();\n}\n Example 3: User-defined serialization/deserialization functions The code below forces the library not to create default serialization/deserialization functions from_json and to_json, but uses user-defined functions to parse and serialize the enum.
#define JSON_DISABLE_ENUM_SERIALIZATION 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nenum class Choice\n{\n first,\n second,\n};\n\nvoid from_json(const json& j, Choice& ch)\n{\n auto value = j.template get<std::string>();\n if (value == \"first\")\n {\n ch = Choice::first;\n }\n else if (value == \"second\")\n {\n ch = Choice::second;\n }\n}\n\nvoid to_json(json& j, const Choice& ch)\n{\n auto value = j.template get<std::string>();\n if (value == \"first\")\n {\n ch = Choice::first;\n }\n else if (value == \"second\")\n {\n ch = Choice::second;\n }\n}\n\nint main()\n{\n // uses user-defined to_json function\n const json j = Choice::first; \n\n // uses user-defined from_json function\n Choice ch = j.template get<Choice>();\n}\n"},{"location":"api/macros/json_disable_enum_serialization/#see-also","title":"See also","text":"NLOHMANN_JSON_SERIALIZE_ENUM#define JSON_HAS_CPP_11\n#define JSON_HAS_CPP_14\n#define JSON_HAS_CPP_17\n#define JSON_HAS_CPP_20\n The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.
The default value is detected based on preprocessor macros such as __cplusplus, _HAS_CXX17, or _MSVC_LANG.
JSON_HAS_CPP_11 is always defined.The code below forces the library to use the C++14 standard:
#define JSON_HAS_CPP_14 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_cpp_11/#version-history","title":"Version history","text":"#define JSON_HAS_FILESYSTEM /* value */\n#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */\n When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.
The default value is detected based on the preprocessor macros __cpp_lib_filesystem, __cpp_lib_experimental_filesystem, __has_include(<filesystem>), or __has_include(<experimental/filesystem>).
stdc++fs to be linked to for filesystem support.The code below forces the library to use the header <experimental/filesystem>.
#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_filesystem/#version-history","title":"Version history","text":"#define JSON_HAS_RANGES /* value */\n This macro indicates whether the standard library has any support for ranges. Implies support for concepts. Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macro __cpp_lib_ranges.
When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_has_ranges/#examples","title":"Examples","text":"ExampleThe code below forces the library to enable support for ranges:
#define JSON_HAS_RANGES 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_ranges/#version-history","title":"Version history","text":"#define JSON_HAS_STATIC_RTTI /* value */\n This macro indicates whether the standard library has any support for RTTI (run time type information). Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI.
When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_has_static_rtti/#examples","title":"Examples","text":"ExampleThe code below forces the library to enable support for libraries with RTTI dependence:
#define JSON_HAS_STATIC_RTTI 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_static_rtti/#version-history","title":"Version history","text":"#define JSON_HAS_THREE_WAY_COMPARISON /* value */\n This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.
The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison.
When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_has_three_way_comparison/#examples","title":"Examples","text":"ExampleThe code below forces the library to use 3-way comparison:
#define JSON_HAS_THREE_WAY_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_has_three_way_comparison/#version-history","title":"Version history","text":"#define JSON_NO_IO\n When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> are not included and parse functions relying on these headers are excluded. This is relevant for environments where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).
By default, JSON_NO_IO is not defined.
#undef JSON_NO_IO\n"},{"location":"api/macros/json_no_io/#examples","title":"Examples","text":"Example The code below forces the library not to use the headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream>.
#define JSON_NO_IO 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_no_io/#version-history","title":"Version history","text":"#define JSON_NOEXCEPTION\n Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION. When defining JSON_NOEXCEPTION, try is replaced by if (true), catch is replaced by if (false), and throw is replaced by std::abort().
The same effect is achieved by setting the compiler flag -fno-exceptions.
By default, the macro is not defined.
#undef JSON_NOEXCEPTION\n"},{"location":"api/macros/json_noexception/#notes","title":"Notes","text":"The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
The code below switches off exceptions in the library.
#define JSON_NOEXCEPTION 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_noexception/#see-also","title":"See also","text":"Added in version 2.1.0.
"},{"location":"api/macros/json_skip_library_version_check/","title":"JSON_SKIP_LIBRARY_VERSION_CHECK","text":"#define JSON_SKIP_LIBRARY_VERSION_CHECK\n When defined, the library will not create a compiler warning when a different version of the library was already included.
"},{"location":"api/macros/json_skip_library_version_check/#default-definition","title":"Default definition","text":"By default, the macro is not defined.
#undef JSON_SKIP_LIBRARY_VERSION_CHECK\n"},{"location":"api/macros/json_skip_library_version_check/#notes","title":"Notes","text":"ABI compatibility
Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.
"},{"location":"api/macros/json_skip_library_version_check/#examples","title":"Examples","text":"Example
The following warning will be shown in case a different version of the library was already included:
Already included a different version of the library!\n"},{"location":"api/macros/json_skip_library_version_check/#version-history","title":"Version history","text":"Added in version 3.11.0.
"},{"location":"api/macros/json_skip_unsupported_compiler_check/","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","title":"Default definition","text":"By default, the macro is not defined.
#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK\n"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","title":"Examples","text":"Example The code below switches off the check whether the compiler is supported.
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","title":"Version history","text":"Added in version 3.2.0.
"},{"location":"api/macros/json_throw_user/","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER","text":"// (1)\n#define JSON_CATCH_USER(exception) /* value */\n// (2)\n#define JSON_THROW_USER(exception) /* value */\n// (3)\n#define JSON_TRY_USER /* value */\n Controls how exceptions are handled by the library.
catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.try calls inside the library. It has no arguments and is always followed by a scope.exception (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"By default, the macros map to their respective C++ keywords:
#define JSON_CATCH_USER(exception) catch(exception)\n#define JSON_THROW_USER(exception) throw exception\n#define JSON_TRY_USER try\n When exceptions are switched off, the try block is executed unconditionally, and throwing exceptions is replaced by calling std::abort to make reaching the throw branch abort the process.
#define JSON_THROW_USER(exception) std::abort()\n#define JSON_TRY_USER if (true)\n#define JSON_CATCH_USER(exception) if (false)\n"},{"location":"api/macros/json_throw_user/#examples","title":"Examples","text":"Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>\n\n#define JSON_TRY_USER if(true)\n#define JSON_CATCH_USER(exception) if(false)\n#define JSON_THROW_USER(exception) \\\n {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\\n << \" (function \" << __FUNCTION__ << \") - \" \\\n << (exception).what() << std::endl; \\\n std::abort();}\n\n#include <nlohmann/json.hpp>\n"},{"location":"api/macros/json_throw_user/#see-also","title":"See also","text":"#define JSON_USE_GLOBAL_UDLS /* value */\n When defined to 1, the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals.
The default value is 1.
#define JSON_USE_GLOBAL_UDLS 1\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_use_global_udls/#notes","title":"Notes","text":"Future behavior change
The user-defined string literals will be removed from the global namespace in the next major release of the library.
To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details.
CMake option
The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs (ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.
The code below shows the default behavior using the _json UDL.
#include <nlohmann/json.hpp>\n\n#include <iostream>\n\nint main()\n{\n auto j = \"42\"_json;\n\n std::cout << j << std::endl;\n}\n Output:
42\n Example 2: Namespaced UDLs The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0.
#define JSON_USE_GLOBAL_UDLS 0\n#include <nlohmann/json.hpp>\n\n#include <iostream>\n\nint main()\n{\n // auto j = \"42\"_json; // This line would fail to compile,\n // because the UDLs are not in the global namespace\n\n // Bring the UDLs into scope\n using namespace nlohmann::json_literals;\n\n auto j = \"42\"_json;\n\n std::cout << j << std::endl;\n}\n Output:
42\n"},{"location":"api/macros/json_use_global_udls/#see-also","title":"See also","text":"operator\"\"_jsonoperator\"\"_json_pointer#define JSON_USE_IMPLICIT_CONVERSIONS /* value */\n When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType.
By default, implicit conversions are enabled.
#define JSON_USE_IMPLICIT_CONVERSIONS 1\n"},{"location":"api/macros/json_use_implicit_conversions/#notes","title":"Notes","text":"Future behavior change
Implicit conversions will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
CMake option
Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions (ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.
This is an example for an implicit conversion:
json j = \"Hello, world!\";\nstd::string s = j;\n When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0, the code above does no longer compile. Instead, it must be written like this:
json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n"},{"location":"api/macros/json_use_implicit_conversions/#see-also","title":"See also","text":"#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */\n This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default).
When enabled, comparisons involving at least one discarded JSON value yield results as follows:
Operator Result== false != true < false <= true >= true > false Otherwise, comparisons involving at least one discarded JSON value always yield false.
The default value is 0.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","title":"Notes","text":"Inconsistent behavior in C++20 and beyond
When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.
<=>) will always give the correct result (std::partial_ordering::unordered) regardless of the value of JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON.Code outside your control may use either 3-way comparison or the equality and relational operators, resulting in inconsistent and unpredictable behavior.
See operator<=> for more information on 3-way comparison.
Deprecation
The legacy comparison behavior is deprecated and may be removed in a future major version release.
New code should not depend on it and existing code should try to remove or rewrite expressions relying on it.
CMake option
Legacy comparison can also be controlled with the CMake option JSON_LegacyDiscardedValueComparison (OFF by default) which defines JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON accordingly.
The code below switches on the legacy discarded value comparison behavior in the library.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n\n...\n"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","title":"Version history","text":"#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(type, base_type, member...) // (1)\n#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(type, base_type, member...) // (2)\n\n#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(type, base_type, member...) // (3)\n#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, base_type, member...) // (4)\n These macros can be used to simplify the serialization/deserialization of derived types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object.
NLOHMANN_DEFINE_TYPE_INTRUSIVE, they can access private members.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, they cannot access private members.The first parameter is the name of the derived class/struct, the second parameter is the name of the base class/struct and all remaining parameters name the members. The base type must be already serializable/deserializable.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in) name of the type (class, struct) to serialize/deserialize base_type (in) name of the base type (class, struct) type is derived from member (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_derived_type/#default-definition","title":"Default definition","text":"Macros 1 and 2 add two friend functions to the class which take care of the serialization and deserialization:
friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&);\n Macros 3 and 4 add two functions to the namespace which take care of the serialization and deserialization:
void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&);\n In both cases they call the to_json/from_json functions of the base type before serializing/deserializing the members of the derived type:
class A { /* ... */ };\nclass B : public A { /* ... */ };\n\nvoid to_json(nlohmann::json& j, const B& b) {\n nlohmann::to_json(j, static_cast<const A&>(b));\n // ...\n}\n\nvoid from_json(const nlohmann::json& j, B& b) {\n nlohmann::from_json(j, static_cast<A&>(b));\n // ...\n}\n"},{"location":"api/macros/nlohmann_define_derived_type/#notes","title":"Notes","text":"Prerequisites
Implementation limits
Example of NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE usage:
class A {\n double Aa;\n double Ab;\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(A, Aa, Ab)\n};\n\nclass B : public A {\n int Ba;\n int Bb;\n NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(B, A, Ba, Bb)\n};\n"},{"location":"api/macros/nlohmann_define_derived_type/#see-also","title":"See also","text":"#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1)\n#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)\n#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)\n These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","title":"Default definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization:
friend void to_json(nlohmann::json&, const type&);\nfriend void from_json(const nlohmann::json&, type&); // except (3)\n See examples below for the concrete generated code.
"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","title":"Notes","text":"Prerequisites
type must be default constructible (except (3)). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.NLOHMANN_DEFINE_TYPE_INTRUSIVE is used inside the class.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT can be used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n\n friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n {\n nlohmann_json_t.name = nlohmann_json_j.at(\"name\");\n nlohmann_json_t.address = nlohmann_json_j.at(\"address\");\n nlohmann_json_t.age = nlohmann_json_j.at(\"age\");\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT is used inside the class.-1 is used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n\n friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n {\n person nlohmann_json_default_obj;\n nlohmann_json_t.name = nlohmann_json_j.value(\"name\", nlohmann_json_default_obj.name);\n nlohmann_json_t.address = nlohmann_json_j.value(\"address\", nlohmann_json_default_obj.address);\n nlohmann_json_t.age = nlohmann_json_j.value(\"age\", nlohmann_json_default_obj.age);\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Note how a default-initialized person object is used in the from_json to fill missing values.
Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n // No default constructor\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(person, name, address, age)\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n Notes:
ns::person is non-default-constructible. This allows this macro to be used instead of NLOHMANN_DEFINE_TYPE_INTRUSIVE and NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT.ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE.NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE is used inside the class.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nclass person\n{\n private:\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n public:\n // No default constructor\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n\n friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n {\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n }\n};\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","title":"See also","text":"#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1)\n#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)\n#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...) // (3)\n These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as serialization and want to use the member variable names as object keys in that object. The macro is to be defined outside the class/struct to create code for, but inside its namespace. Unlike NLOHMANN_DEFINE_TYPE_INTRUSIVE, it cannot access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the (public) member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","title":"Default definition","text":"The macros add two functions to the namespace which take care of the serialization and deserialization:
void to_json(nlohmann::json&, const type&);\nvoid from_json(const nlohmann::json&, type&); // except (3)\n See examples below for the concrete generated code.
"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","title":"Notes","text":"Prerequisites
type must be default constructible (except (3). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\ndeserialization failed: [json.exception.out_of_range.403] key 'age' not found\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE is used outside the class, but inside its namespace ns.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT can be used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n\nvoid from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n{\n nlohmann_json_t.name = nlohmann_json_j.at(\"name\");\n nlohmann_json_t.address = nlohmann_json_j.at(\"address\");\n nlohmann_json_t.age = nlohmann_json_j.at(\"age\");\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get<ns::person>();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}\n Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\nroundtrip: {\"address\":\"742 Evergreen Terrace\",\"age\":-1,\"name\":\"Maggie Simpson\"}\n Notes:
ns::person is default-constructible. This is a requirement for using the macro.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns.-1 is used.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name = \"John Doe\";\n std::string address = \"123 Fake St\";\n int age = -1;\n\n person() = default;\n person(std::string name_, std::string address_, int age_)\n : name(std::move(name_)), address(std::move(address_)), age(age_)\n {}\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n\nvoid from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t)\n{\n person nlohmann_json_default_obj;\n nlohmann_json_t.name = nlohmann_json_j.value(\"name\", nlohmann_json_default_obj.name);\n nlohmann_json_t.address = nlohmann_json_j.value(\"address\", nlohmann_json_default_obj.address);\n nlohmann_json_t.age = nlohmann_json_j.value(\"age\", nlohmann_json_default_obj.age);\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get<ns::person>();\n\n // incomplete deserialization:\n json j3 = R\"({\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"})\"_json;\n auto p3 = j3.template get<ns::person>();\n std::cout << \"roundtrip: \" << json(p3) << std::endl;\n}\n Note how a default-initialized person object is used in the from_json to fill missing values.
Consider the following complete example:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(person, name, address, age)\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n Output:
serialization: {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n Notes:
ns::person is non-default-constructible. This allows this macro to be used instead of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE and NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE applicable.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE is used outside the class, but inside its namespace ns.The macro is equivalent to:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\nvoid to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}\n"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","title":"See also","text":"#define NLOHMANN_JSON_NAMESPACE /* value */\n This macro evaluates to the full name of the nlohmann namespace.
The default value consists of the root namespace (nlohmann) and an inline ABI namespace. See nlohmann Namespace for details.
When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.
"},{"location":"api/macros/nlohmann_json_namespace/#examples","title":"Examples","text":"ExampleThe example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann\nusing json = NLOHMANN_JSON_NAMESPACE::json;\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n Output:
nlohmann::json_abi_v3_11_3\n"},{"location":"api/macros/nlohmann_json_namespace/#see-also","title":"See also","text":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_ENDNLOHMANN_JSON_NAMESPACE_NO_VERSION#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1)\n#define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2)\n These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details.
The default definitions open and close the nlohmann namespace. The precise definition of [NLOHMANN_JSON_NAMESPACE_BEGIN] varies as described here.
Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN:
namespace nlohmann\n{\ninline namespace json_abi_v3_11_2\n{\n Default definition of NLOHMANN_JSON_NAMESPACE_END:
} // namespace json_abi_v3_11_2\n} // namespace nlohmann\n When these macros are not defined, the library will define them to their default definitions.
"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","title":"Examples","text":"ExampleThe example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN/NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page.
#include <iostream>\n#include <optional>\n#include <nlohmann/json.hpp>\n\n// partial specialization (see https://json.nlohmann.me/features/arbitrary_types/)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<std::optional<T>>\n{\n static void to_json(json& j, const std::optional<T>& opt)\n {\n if (opt == std::nullopt)\n {\n j = nullptr;\n }\n else\n {\n j = *opt;\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n\nint main()\n{\n std::optional<int> o1 = 1;\n std::optional<int> o2 = std::nullopt;\n\n NLOHMANN_JSON_NAMESPACE::json j;\n j.push_back(o1);\n j.push_back(o2);\n std::cout << j << std::endl;\n}\n Output:
[1,null]\n"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","title":"See also","text":"nlohmann NamespaceNLOHMANN_JSON_NAMESPACE_NO_VERSION#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */\n If defined to 1, the version component is omitted from the inline namespace. See nlohmann Namespace for details.
The default value is 0.
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0\n When the macro is not defined, the library will define it to its default value.
"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","title":"Examples","text":"ExampleThe example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace.
#include <iostream>\n\n#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1\n#include <nlohmann/json.hpp>\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n Output:
nlohmann::json_abi\n"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","title":"See also","text":"nlohmann NamespaceNLOHMANN_JSON_NAMESPACENLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)\n By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.
type (in) name of the enum to serialize/deserialize conversion (in) a pair of an enumerator and a JSON serialization; arbitrary pairs can be given as a comma-separated list"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","title":"Default definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization:
template<typename BasicJsonType>\ninline void to_json(BasicJsonType& j, const type& e);\ntemplate<typename BasicJsonType>\ninline void from_json(const BasicJsonType& j, type& e);\n"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","title":"Notes","text":"Prerequisites
The macro must be used inside the namespace of the enum.
Important notes
template get<ENUM_TYPE>(), undefined JSON values will default to the first specified conversion. Select this default pair carefully. See example 1 below.The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum TaskState\n{\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID = -1\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(TaskState,\n{\n { TS_INVALID, nullptr },\n { TS_STOPPED, \"stopped\" },\n { TS_RUNNING, \"running\" },\n { TS_COMPLETED, \"completed\" }\n})\n\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" }\n})\n} // namespace ns\n\nint main()\n{\n // serialization\n json j_stopped = ns::TS_STOPPED;\n json j_red = ns::Color::red;\n std::cout << \"ns::TS_STOPPED -> \" << j_stopped\n << \", ns::Color::red -> \" << j_red << std::endl;\n\n // deserialization\n json j_running = \"running\";\n json j_blue = \"blue\";\n auto running = j_running.template get<ns::TaskState>();\n auto blue = j_blue.template get<ns::Color>();\n std::cout << j_running << \" -> \" << running\n << \", \" << j_blue << \" -> \" << static_cast<int>(blue) << std::endl;\n\n // deserializing undefined JSON value to enum\n // (where the first map entry above is the default)\n json j_pi = 3.14;\n auto invalid = j_pi.template get<ns::TaskState>();\n auto unknown = j_pi.template get<ns::Color>();\n std::cout << j_pi << \" -> \" << invalid << \", \"\n << j_pi << \" -> \" << static_cast<int>(unknown) << std::endl;\n}\n Output:
ns::TS_STOPPED -> \"stopped\", ns::Color::red -> \"red\"\n\"running\" -> 1, \"blue\" -> 2\n3.14 -> -1, 3.14 -> 3\n Example 2: Multiple conversions for one enumerator The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\", because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" },\n { Color::red, \"rot\" } // a second conversion for Color::red\n})\n}\n\nint main()\n{\n // serialization\n json j_red = ns::Color::red;\n std::cout << static_cast<int>(ns::Color::red) << \" -> \" << j_red << std::endl;\n\n // deserialization\n json j_rot = \"rot\";\n auto rot = j_rot.template get<ns::Color>();\n auto red = j_red.template get<ns::Color>();\n std::cout << j_rot << \" -> \" << static_cast<int>(rot) << std::endl;\n std::cout << j_red << \" -> \" << static_cast<int>(red) << std::endl;\n}\n Output:
0 -> \"red\"\n\"rot\" -> 0\n\"red\" -> 0\n"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","title":"See also","text":"JSON_DISABLE_ENUM_SERIALIZATIONAdded in version 3.4.0.
"},{"location":"api/macros/nlohmann_json_version_major/","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"#define NLOHMANN_JSON_VERSION_MAJOR /* value */\n#define NLOHMANN_JSON_VERSION_MINOR /* value */\n#define NLOHMANN_JSON_VERSION_PATCH /* value */\n These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.
"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","title":"Default definition","text":"The macros are defined according to the current library version.
"},{"location":"api/macros/nlohmann_json_version_major/#examples","title":"Examples","text":"ExampleThe example below shows how NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH are defined by the library.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << \"JSON for Modern C++ version \"\n << NLOHMANN_JSON_VERSION_MAJOR << \".\"\n << NLOHMANN_JSON_VERSION_MINOR << \".\"\n << NLOHMANN_JSON_VERSION_PATCH << std::endl;\n}\n Output:
JSON for Modern C++ version 3.11.3\n"},{"location":"api/macros/nlohmann_json_version_major/#see-also","title":"See also","text":"Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:
namespace ns {\n // a simple struct to model a person\n struct person {\n std::string name;\n std::string address;\n int age;\n };\n} // namespace ns\n\nns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// convert to JSON: copy each value into the JSON object\njson j;\nj[\"name\"] = p.name;\nj[\"address\"] = p.address;\nj[\"age\"] = p.age;\n\n// ...\n\n// convert from JSON: copy each value from the JSON object\nns::person p {\n j[\"name\"].template get<std::string>(),\n j[\"address\"].template get<std::string>(),\n j[\"age\"].template get<int>()\n};\n It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
// create a person\nns::person p {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// conversion: person -> json\njson j = p;\n\nstd::cout << j << std::endl;\n// {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"}\n\n// conversion: json -> person\nauto p2 = j.template get<ns::person>();\n\n// that's it\nassert(p == p2);\n"},{"location":"features/arbitrary_types/#basic-usage","title":"Basic usage","text":"To make this work with one of your types, you only need to provide two functions:
using json = nlohmann::json;\n\nnamespace ns {\n void to_json(json& j, const person& p) {\n j = json{ {\"name\", p.name}, {\"address\", p.address}, {\"age\", p.age} };\n }\n\n void from_json(const json& j, person& p) {\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n }\n} // namespace ns\n That's all! When calling the json constructor with your type, your custom to_json method will be automatically called. Likewise, when calling template get<your_type>() or get_to(your_type&), the from_json method will be called.
Some important things:
ns, where person is defined).template get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)from_json, use function at() to access the object values rather than operator[]. In case a key does not exist, at throws an exception that you can handle, whereas operator[] exhibits undefined behavior.std::vector: the library already implements these.If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate.
There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object:
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in from_json() due to a missing value in the JSON object.NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type.NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in from_json() due to a missing value in the JSON object.NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type.In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here.
Implementation limits
to_json/from_json functions manually.nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.The to_json/from_json functions for the person struct above can be created with:
namespace ns {\n NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)\n}\n Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed:
namespace ns {\n class address {\n private:\n std::string street;\n int housenumber;\n int postcode;\n\n public:\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)\n };\n}\n"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
The library uses JSON Serializers to convert types to json. The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).
It is implemented like this (simplified):
template <typename T>\nstruct adl_serializer {\n static void to_json(json& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n static void from_json(const json& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...
To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:
// partial specialization (full specialization works too)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<boost::optional<T>> {\n static void to_json(json& j, const boost::optional<T>& opt) {\n if (opt == boost::none) {\n j = nullptr;\n } else {\n j = *opt; // this will call adl_serializer<T>::to_json which will\n // find the free function to_json in T's namespace!\n }\n }\n\n static void from_json(const json& j, boost::optional<T>& opt) {\n if (j.is_null()) {\n opt = boost::none;\n } else {\n opt = j.template get<T>(); // same as above, but with\n // adl_serializer<T>::from_json\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n ABI compatibility
Use NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END instead of namespace nlohmann { } in code which may be linked with different versions of this library.
get() for non-default constructible/non-copyable types?","text":"There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:
struct move_only_type {\n move_only_type() = delete;\n move_only_type(int ii): i(ii) {}\n move_only_type(const move_only_type&) = delete;\n move_only_type(move_only_type&&) = default;\n\n int i;\n};\n\nnamespace nlohmann {\n template <>\n struct adl_serializer<move_only_type> {\n // note: the return type is no longer 'void', and the method only takes\n // one argument\n static move_only_type from_json(const json& j) {\n return {j.template get<int>()};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert move_only_type to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, move_only_type t) {\n j = t.i;\n }\n };\n}\n"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"Yes. You might want to take a look at unit-udt.cpp in the test suite, to see a few examples.
If you write your own serializer, you'll need to do a few things:
basic_json alias than nlohmann::json (the last template parameter of basic_json is the JSONSerializer)basic_json alias (or a template parameter) in all your to_json/from_json methodsnlohmann::to_json and nlohmann::from_json when you need ADLHere is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
// You should use void as a second template argument\n// if you don't need compile-time checks on T\ntemplate<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>\nstruct less_than_32_serializer {\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, T value) {\n // we want to use ADL, and call the correct to_json overload\n using nlohmann::to_json; // this method is called by adl_serializer,\n // this is where the magic happens\n to_json(j, value);\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing here\n using nlohmann::from_json;\n from_json(j, value);\n }\n};\n Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
template <typename T, void>\nstruct bad_serializer\n{\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, const T& value) {\n // this calls BasicJsonType::json_serializer<T>::to_json(j, value);\n // if BasicJsonType::json_serializer == bad_serializer ... oops!\n j = value;\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // this calls BasicJsonType::json_serializer<T>::from_json(j, value);\n // if BasicJsonType::json_serializer == bad_serializer ... oops!\n value = j.template template get<T>(); // oops!\n }\n};\n"},{"location":"features/assertions/","title":"Runtime Assertions","text":"The code contains numerous debug assertions to ensure class invariants are valid or to detect undefined behavior. Whereas the former class invariants are nothing to be concerned of, the latter checks for undefined behavior are to detect bugs in client code.
"},{"location":"features/assertions/#switch-off-runtime-assertions","title":"Switch off runtime assertions","text":"Runtime assertions can be switched off by defining the preprocessor macro NDEBUG (see the documentation of assert) which is the default for release builds.
The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header.
Function operator[] implements unchecked access for objects. Whereas a missing key is added in case of non-const objects, accessing a const object with a missing key is undefined behavior (think of a dereferenced null pointer) and yields a runtime assertion.
If you are not sure whether an element in an object exists, use checked access with the at function or call the contains function before.
See also the documentation on element access.
Example 1: Missing object keyThe following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.
Example 2: Uninitialized iterator rangeThe following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::iterator it1, it2;\n json j(it1, it2);\n}\n Output:
Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.
Example 3: Uninitialized iteratorThe following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json::iterator it;\n ++it;\n}\n Output:
Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n"},{"location":"features/assertions/#changes","title":"Changes","text":""},{"location":"features/assertions/#reading-from-a-null-file-or-char-pointer","title":"Reading from a null FILE or char pointer","text":"Reading from a null FILE or char pointer in C++ is undefined behavior. Until version 3.11.4, this library asserted that the pointer was not nullptr using a runtime assertion. If assertions were disabled, this would result in undefined behavior. Since version 3.11.4, this library checks for nullptr and throws a parse_error.101 to prevent the undefined behavior.
The following code will trigger an assertion at runtime:
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::FILE* f = std::fopen(\"nonexistent_file.json\", \"r\");\n try {\n json j = json::parse(f);\n } catch (std::exception& e) {\n std::cerr << e.what() << std::endl;\n }\n}\n Output:
[json.exception.parse_error.101] parse error: attempting to parse an empty input; check that your input string or stream contains the expected JSON\n"},{"location":"features/binary_values/","title":"Binary Values","text":"The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored.
JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.
"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"classDiagram\n\nclass binary_t [\"json::binary_t\"] {\n +void set_subtype(std::uint64_t subtype)\n +void clear_subtype()\n +std::uint64_t subtype() const\n +bool has_subtype() const\n}\n\nclass vector [\"std::vector<uint8_t>\"]\n\nvector <|-- binary_t By default, binary values are stored as std::vector<std::uint8_t>. This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t:
auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE});\nauto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n There are several convenience functions to check and set the subtype:
binary.has_subtype(); // returns false\nbinary_with_subtype.has_subtype(); // returns true\n\nbinary_with_subtype.clear_subtype();\nbinary_with_subtype.has_subtype(); // returns true\n\nbinary_with_subtype.set_subtype(42);\nbinary.set_subtype(23);\n\nbinary.subtype(); // returns 23\n As json::binary_t is subclassing std::vector<std::uint8_t>, all member functions are available:
binary.size(); // returns 4\nbinary[1]; // returns 0xFE\n JSON values can be constructed from json::binary_t:
json j = binary;\n Binary values are primitive values just like numbers or strings:
j.is_binary(); // returns true\nj.is_primitive(); // returns true\n Given a binary JSON value, the binary_t can be accessed by reference as via get_binary():
j.get_binary().has_subtype(); // returns true\nj.get_binary().size(); // returns 4\n For convenience, binary JSON values can be constructed via json::binary:
auto j2 = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 23);\nauto j3 = json::binary({0xCA, 0xFE, 0xBA, 0xBE});\n\nj2 == j; // returns true\nj3.get_binary().has_subtype(); // returns false\nj3.get_binary().subtype(); // returns std::uint64_t(-1) as j3 has no subtype\n"},{"location":"features/binary_values/#serialization","title":"Serialization","text":"Binary values are serialized differently according to the formats.
"},{"location":"features/binary_values/#json","title":"JSON","text":"JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: bytes holds an array of integers, and subtype is an integer or null.
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// serialize to standard output\nstd::cout << j.dump(2) << std::endl;\n Output:
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n No roundtrip for binary values
The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes.
"},{"location":"features/binary_values/#bjdata","title":"BJData","text":"BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
ExampleCode:
// create a binary value of subtype 42 (will be ignored in BJData)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BJData\nauto v = json::to_bjdata(j); \n v is a std::vector<std::uint8t> with the following 20 elements:
0x7B // '{'\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '['\n 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')\n 0x5D // ']'\n0x7D // '}'\n The following code uses the type and size optimization for UBJSON:
// convert to UBJSON using the size and type optimization\nauto v = json::to_bjdata(j, true, true);\n The resulting vector has 22 elements; the optimization is not effective for examples with few values:
0x7B // '{'\n 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '[' array\n 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers\n 0x23 0x69 0x04 // '#' i 4 number of array elements\n 0xCA 0xFE 0xBA 0xBE // content\n Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:
{\n \"binary\": [202, 254, 186, 190]\n}\n"},{"location":"features/binary_values/#bson","title":"BSON","text":"BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used.
ExampleCode:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BSON\nauto v = json::to_bson(j); \n v is a std::vector<std::uint8t> with the following 22 elements:
0x16 0x00 0x00 0x00 // number of bytes in the document\n 0x05 // binary value\n 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte\n 0x04 0x00 0x00 0x00 // number of bytes\n 0x2a // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n0x00 // end of the document\n Note that the serialization preserves the subtype, and deserializing v would yield the following value:
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n"},{"location":"features/binary_values/#cbor","title":"CBOR","text":"CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
ExampleCode:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to CBOR\nauto v = json::to_cbor(j); \n v is a std::vector<std::uint8t> with the following 15 elements:
0xA1 // map(1)\n 0x66 // text(6)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0xD8 0x2A // tag(42)\n 0x44 // bytes(4)\n 0xCA 0xFE 0xBA 0xBE // content\n Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless json::cbor_tag_handler_t::ignore or json::cbor_tag_handler_t::store is passed to json::from_cbor.
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": null\n }\n}\n"},{"location":"features/binary_values/#messagepack","title":"MessagePack","text":"MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
ExampleCode:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to MessagePack\nauto v = json::to_msgpack(j); \n v is a std::vector<std::uint8t> with the following 14 elements:
0x81 // fixmap1\n 0xA6 // fixstr6\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0xD6 // fixext4\n 0x2A // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n Note that the serialization preserves the subtype, and deserializing v would yield the following value:
{\n \"binary\": {\n \"bytes\": [202, 254, 186, 190],\n \"subtype\": 42\n }\n}\n"},{"location":"features/binary_values/#ubjson","title":"UBJSON","text":"UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
ExampleCode:
// create a binary value of subtype 42 (will be ignored in UBJSON)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to UBJSON\nauto v = json::to_ubjson(j); \n v is a std::vector<std::uint8t> with the following 20 elements:
0x7B // '{'\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x5B // '['\n 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')\n 0x5D // ']'\n0x7D // '}'\n The following code uses the type and size optimization for UBJSON:
// convert to UBJSON using the size and type optimization\nauto v = json::to_ubjson(j, true, true);\n The resulting vector has 23 elements; the optimization is not effective for examples with few values:
0x7B // '{'\n 0x24 // '$' type of the object elements\n 0x5B // '[' array\n 0x23 0x69 0x01 // '#' i 1 number of object elements\n 0x69 0x06 // i 6 (length of the key)\n 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\"\n 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers\n 0x23 0x69 0x04 // '#' i 4 number of array elements\n 0xCA 0xFE 0xBA 0xBE // content\n Note that subtype (42) is not serialized and that UBJSON has no binary type, and deserializing v would yield the following value:
{\n \"binary\": [202, 254, 186, 190]\n}\n"},{"location":"features/comments/","title":"Comments","text":"This library does not support comments by default. It does so for three reasons:
// or /* */ are allowed in JavaScript, but JSON is not JavaScript.This was not an oversight: Douglas Crockford wrote on this in May 2012:
I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
It is dangerous for interoperability if some libraries would add comment support while others don't. Please check The Harmful Consequences of the Robustness Principle on this.
However, you can pass set parameter ignore_comments to true in the parse function to ignore // or /* */ comments. Comments will then be treated as whitespace.
Example
Consider the following JSON with comments.
{\n // update in 2006: removed Pluto\n \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n}\n When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true, the comments are ignored during parsing:
#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::string s = R\"(\n {\n // update in 2006: removed Pluto\n \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\",\n \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */]\n }\n )\";\n\n try\n {\n json j = json::parse(s);\n }\n catch (json::exception &e)\n {\n std::cout << e.what() << std::endl;\n }\n\n json j = json::parse(s,\n /* callback */ nullptr,\n /* allow exceptions */ true,\n /* ignore_comments */ true);\n std::cout << j.dump(2) << '\\n';\n}\n Output:
[json.exception.parse_error.101] parse error at line 3, column 9:\nsyntax error while parsing object key - invalid literal;\nlast read: '<U+000A> {<U+000A> /'; expected string literal\n {\n \"planets\": [\n \"Mercury\",\n \"Venus\",\n \"Earth\",\n \"Mars\",\n \"Jupiter\",\n \"Uranus\",\n \"Neptune\"\n ]\n}\n"},{"location":"features/enum_conversion/","title":"Specializing enum conversion","text":"By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:
// example enum type declaration\nenum TaskState {\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID=-1,\n};\n\n// map TaskState values to JSON as strings\nNLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {\n {TS_INVALID, nullptr},\n {TS_STOPPED, \"stopped\"},\n {TS_RUNNING, \"running\"},\n {TS_COMPLETED, \"completed\"},\n})\n The NLOHMANN_JSON_SERIALIZE_ENUM() macro declares a set of to_json() / from_json() functions for type TaskState while avoiding repetition and boilerplate serialization code.
// enum to JSON as string\njson j = TS_STOPPED;\nassert(j == \"stopped\");\n\n// json string to enum\njson j3 = \"running\";\nassert(j3.template get<TaskState>() == TS_RUNNING);\n\n// undefined json value to enum (where the first map entry above is the default)\njson jPi = 3.14;\nassert(jPi.template get<TaskState>() == TS_INVALID );\n"},{"location":"features/enum_conversion/#notes","title":"Notes","text":"Just as in Arbitrary Type Conversions above,
NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization.Other Important points:
template get<ENUM_TYPE>(), undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.JSON_DISABLE_ENUM_SERIALIZATION.A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values.
As for other containers, begin() returns an iterator to the first value and end() returns an iterator to the value following the last value. The latter iterator is a placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, begin() will return end().
When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.
// create JSON object {\"one\": 1, \"two\": 2, \"three\": 3}\njson j;\nj[\"one\"] = 1;\nj[\"two\"] = 2;\nj[\"three\"] = 3;\n\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n Output:
1\n3\n2\n The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".
"},{"location":"features/iterators/#access-object-key-during-iteration","title":"Access object key during iteration","text":"The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown.
// create JSON object {\"one\": 1, \"two\": 2, \"three\": 3}\njson j;\nj[\"one\"] = 1;\nj[\"two\"] = 2;\nj[\"three\"] = 3;\n\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << it.key() << \" : \" << it.value() << std::endl;\n}\n Output:
one : 1\nthree : 3\ntwo : 2\n"},{"location":"features/iterators/#range-based-for-loops","title":"Range-based for loops","text":"C++11 allows using range-based for loops to iterate over a container.
for (auto it : j_object)\n{\n // \"it\" is of type json::reference and has no key() member\n std::cout << \"value: \" << it << '\\n';\n}\n For this reason, the items() function allows accessing iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.
for (auto& el : j_object.items())\n{\n std::cout << \"key: \" << el.key() << \", value:\" << el.value() << '\\n';\n}\n The items() function also allows using structured bindings (C++17):
for (auto& [key, val] : j_object.items())\n{\n std::cout << \"key: \" << key << \", value:\" << val << '\\n';\n}\n Note
When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string.
Warning
Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See #2040 for more information.
rbegin() and rend() return iterators in the reverse sequence.
json j = {1, 2, 3, 4};\n\nfor (auto it = j.rbegin(); it != j.rend(); ++it)\n{\n std::cout << *it << std::endl;\n}\n Output:
4\n3\n2\n1\n"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe the underlying string or binary array is empty.
json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n Output:
\"Hello, world\"\n"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators clear all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
The following code shows how a JSON patch is applied to a value.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the patch\n json patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // apply the patch\n json patched_doc = doc.patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << doc << \"\\n\\n\"\n << std::setw(4) << patched_doc << std::endl;\n}\n Output:
{\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n}\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"features/json_patch/#diff","title":"Diff","text":"The library can also calculate a JSON patch (i.e., a diff) given two JSON values.
Invariant
For two JSON values source and target, the following code yields always true:
source.patch(diff(source, target)) == target;\n Example The following code shows how a JSON patch is created as a diff for two JSON values.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the source document\n json source = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // the target document\n json target = R\"(\n {\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n }\n )\"_json;\n\n // create the patch\n json patch = json::diff(source, target);\n\n // roundtrip\n json patched_source = source.patch(patch);\n\n // output patch and roundtrip result\n std::cout << std::setw(4) << patch << \"\\n\\n\"\n << std::setw(4) << patched_source << std::endl;\n}\n Output:
[\n {\n \"op\": \"replace\",\n \"path\": \"/baz\",\n \"value\": \"boo\"\n },\n {\n \"op\": \"remove\",\n \"path\": \"/foo\"\n },\n {\n \"op\": \"add\",\n \"path\": \"/hello\",\n \"value\": [\n \"world\"\n ]\n }\n]\n\n{\n \"baz\": \"boo\",\n \"hello\": [\n \"world\"\n ]\n}\n"},{"location":"features/json_pointer/","title":"JSON Pointer","text":""},{"location":"features/json_pointer/#introduction","title":"Introduction","text":"The library supports JSON Pointer (RFC 6901) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document.
Consider the following JSON document
{\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n}\n Then every value inside the JSON document can be identified as follows:
JSON Pointer JSON value ``{\"array\":[\"A\",\"B\",\"C\"],\"nested\":{\"one\":1,\"two\":2,\"three\":[true,false]}} /array [\"A\",\"B\",\"C\"] /array/0 A /array/1 B /array/2 C /nested {\"one\":1,\"two\":2,\"three\":[true,false]} /nested/one 1 /nested/two 2 /nested/three [true,false] /nested/three/0 true /nested/three/1 false Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\". See RFC 6901 for more information.
JSON Pointers can be created from a string:
json::json_pointer p = \"/nested/one\";\n Furthermore, a user-defined string literal can be used to achieve the same result:
auto p = \"/nested/one\"_json_pointer;\n The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.
"},{"location":"features/json_pointer/#value-access","title":"Value access","text":"JSON Pointers can be used in the at, operator[], and value functions just like object keys or array indices.
// the JSON value from above\nauto j = json::parse(R\"({\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n})\");\n\n// access values\nauto val = j[\"\"_json_pointer]; // {\"array\":[\"A\",\"B\",\"C\"],...}\nauto val1 = j[\"/nested/one\"_json_pointer]; // 1\nauto val2 = j.at(json::json_pointer(\"/nested/three/1\")); // false\nauto val3 = j.value(json::json_pointer(\"/nested/four\"), 0); // 0\n"},{"location":"features/json_pointer/#flatten-unflatten","title":"Flatten / unflatten","text":"The library implements a function flatten to convert any JSON document into a JSON object where each key is a JSON Pointer and each value is a primitive JSON value (i.e., a string, boolean, number, or null).
// the JSON value from above\nauto j = json::parse(R\"({\n \"array\": [\"A\", \"B\", \"C\"],\n \"nested\": {\n \"one\": 1,\n \"two\": 2,\n \"three\": [true, false]\n }\n})\");\n\n// create flattened value\nauto j_flat = j.flatten();\n The resulting value j_flat is:
{\n \"/array/0\": \"A\",\n \"/array/1\": \"B\",\n \"/array/2\": \"C\",\n \"/nested/one\": 1,\n \"/nested/two\": 2,\n \"/nested/three/0\": true,\n \"/nested/three/1\": false\n}\n The reverse function, unflatten recreates the original value.
auto j_original = j_flat.unflatten();\n"},{"location":"features/json_pointer/#see-also","title":"See also","text":"json_pointerflattenunflattenSome aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.
JSON_ASSERT(x)","text":"This macro controls which code is executed for runtime assertions of the library.
See full documentation of JSON_ASSERT(x).
JSON_CATCH_USER(exception)","text":"This macro overrides catch calls inside the library.
See full documentation of JSON_CATCH_USER(exception).
JSON_DIAGNOSTICS","text":"This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default).
When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead.
The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics (OFF by default) which sets JSON_DIAGNOSTICS accordingly.
See full documentation of JSON_DIAGNOSTICS.
JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20","text":"The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly.
See full documentation of JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, and JSON_HAS_CPP_20.
JSON_HAS_FILESYSTEM, JSON_HAS_EXPERIMENTAL_FILESYSTEM","text":"When compiling with C++17, the library provides conversions from and to std::filesystem::path. As compiler support for filesystem is limited, the library tries to detect whether <filesystem>/std::filesystem (JSON_HAS_FILESYSTEM) or <experimental/filesystem>/std::experimental::filesystem (JSON_HAS_EXPERIMENTAL_FILESYSTEM) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1.
See full documentation of JSON_HAS_FILESYSTEM and JSON_HAS_EXPERIMENTAL_FILESYSTEM.
JSON_NOEXCEPTION","text":"Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION.
See full documentation of JSON_NOEXCEPTION.
JSON_DISABLE_ENUM_SERIALIZATION","text":"When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM.
See full documentation of JSON_DISABLE_ENUM_SERIALIZATION.
JSON_NO_IO","text":"When defined, headers <cstdio>, <ios>, <iosfwd>, <istream>, and <ostream> are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)).
See full documentation of JSON_NO_IO.
JSON_SKIP_LIBRARY_VERSION_CHECK","text":"When defined, the library will not create a compiler warning when a different version of the library was already included.
See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK.
JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","text":"When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK.
JSON_THROW_USER(exception)","text":"This macro overrides throw calls inside the library. The argument is the exception to be thrown.
See full documentation of JSON_THROW_USER(exception).
JSON_TRY_USER","text":"This macro overrides try calls inside the library.
See full documentation of JSON_TRY_USER.
JSON_USE_IMPLICIT_CONVERSIONS","text":"When defined to 0, implicit conversions are switched off. By default, implicit conversions are switched on.
See full documentation of JSON_USE_IMPLICIT_CONVERSIONS.
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_derived_type_intrusive_with_defaulttype-base_type-member","title":"NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_derived_type_non_intrusivetype-base_type-member","title":"NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_derived_type_non_intrusive_with_defaulttype-base_type-member","title":"NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, base_type, member...)","text":""},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members.
See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE.
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.
See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT.
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE except that it defines only the serialization code. This is useful when the user type does not have a default constructor and only the serialization is required.
See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members.
See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE. It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function.
See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(type, member...)","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE except that it defines only the serialization code. This is useful when the user type does not have a default constructor and only the serialization is required.
See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE.
NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)","text":"This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information.
See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM.
NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH","text":"These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0.
See full documentation of NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH.
The library supports JSON Merge Patch (RFC 7386) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.
ExampleThe following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n Output:
{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n"},{"location":"features/namespace/","title":"nlohmann Namespace","text":"The 3.11.0 release introduced an inline namespace to allow different parts of a codebase to safely use different versions of the JSON library as long as they never exchange instances of library types.
"},{"location":"features/namespace/#structure","title":"Structure","text":"The complete default namespace name is derived as follows:
nlohmann.json_abi and is followed by serveral optional ABI tags according to the value of these ABI-affecting macros, in order:JSON_DIAGNOSTICS defined non-zero appends _diag.JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON defined non-zero appends _ldvcmp._v followed by the 3 components of the version number separated by underscores. To omit the version component, see Disabling the version component below.For example, the namespace name for version 3.11.2 with JSON_DIAGNOSTICS defined to 1 is:
nlohmann::json_abi_diag_v3_11_2\n"},{"location":"features/namespace/#purpose","title":"Purpose","text":"Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS. This is illustrated in the diagram below.
graph\n json[\"<strong>nlohmann_json (v3.10.5)</strong><br>JSON_DIAGNOSTICS=0\"]\n json_diag[\"<strong>nlohmann_json (v3.10.5)</strong><br>JSON_DIAGNOSTICS=1\"]\n library[\"<strong>some library</strong>\"]\n app[\"<strong>application</strong>\"]\n\n library --> json\n app --> json_diag\n app --> library In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.
Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types.
There is an exception when forward declarations are used (i.e., when including json_fwd.hpp) in which case the linker may complain about undefined references.
Different versions are not necessarily ABI-incompatible, but the project does not actively track changes in the ABI and recommends that all parts of a codebase exchanging library types be built with the same version. Users can, at their own risk, disable the version component of the linline namespace, allowing different versions \u2013 but not configurations \u2013 to be used in cases where the linker would otherwise output undefined reference errors.
To do so, define NLOHMANN_JSON_NAMESPACE_NO_VERSION to 1.
This applies to version 3.11.2 and above only, versions 3.11.0 and 3.11.1 can apply the technique described in the next section to emulate the effect of the NLOHMANN_JSON_NAMESPACE_NO_VERSION macro.
Use at your own risk
Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!
"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows:
#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {\n#define NLOHMANN_JSON_NAMESPACE_END }\n Use at your own risk
Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!
"},{"location":"features/namespace/#version-history","title":"Version history","text":"json_v3_11_0[_abi-tag]*) in version 3.11.0.The JSON standard defines objects as \"an unordered collection of zero or more name/value pairs\". As such, an implementation does not need to preserve any specific order of object keys.
"},{"location":"features/object_order/#default-behavior-sort-keys","title":"Default behavior: sort keys","text":"The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.
#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n Output:
{\n \"one\": 1,\n \"three\": 3,\n \"two\": 2\n}\n"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","title":"Alternative behavior: preserve insertion order","text":"If you do want to preserve the insertion order, you can try the type nlohmann::ordered_json.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing ordered_json = nlohmann::ordered_json;\n\nint main()\n{\n ordered_json j;\n j[\"one\"] = 1;\n j[\"two\"] = 2;\n j[\"three\"] = 3;\n\n std::cout << j.dump(2) << '\\n';\n}\n Output:
{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map (integration) or nlohmann::fifo_map (integration).
Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above:
{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n Right way
The following code correctly calls the parse function from nlohmann::ordered_json:
std::ifstream i(\"input.json\");\nauto j = nlohmann::ordered_json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n The output will be:
{\n \"one\": 1,\n \"two\": 2,\n \"three\": 3\n}\n Wrong way The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file.
std::ifstream i(\"input.json\");\nnlohmann::ordered_json j = nlohmann::json::parse(i);\nstd::cout << j.dump(2) << std::endl;\n The output will be:
{\n \"one\": 1,\n \"three\": 3\n \"two\": 2,\n}\n"},{"location":"features/binary_formats/","title":"Binary Formats","text":"Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports
to efficiently encode JSON values to byte vectors and to decode such vectors.
"},{"location":"features/binary_formats/#comparison","title":"Comparison","text":""},{"location":"features/binary_formats/#completeness","title":"Completeness","text":"Format Serialization Deserialization BJData complete complete BSON incomplete: top-level value must be an object incomplete, but all JSON types are supported CBOR complete incomplete, but all JSON types are supported MessagePack complete complete UBJSON complete complete"},{"location":"features/binary_formats/#binary-values","title":"Binary values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supportedSee binary values for more information.
"},{"location":"features/binary_formats/#sizes","title":"Sizes","text":"Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 %Sizes compared to minified JSON value.
"},{"location":"features/binary_formats/bjdata/","title":"BJData","text":"The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays (ND-arrays); it also adds 4 new type markers - [u] - uint16, [m] - uint32, [M] - uint64 and [h] - float16 - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms.
Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable. This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing.
References
The library uses the following mapping from JSON values types to BJData types according to the BJData specification:
JSON value type value/range BJData type marker nullnull null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a BJData value.
Any BJData output created by to_bjdata can be successfully parsed by from_bjdata.
Size constraints
The following values can not be converted to a BJData value:
Unused BJData markers
The following markers are not used in the conversion:
Z: no-op values are not created.C: single-byte strings are serialized with S markers.NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.
Endianness
A breaking difference between BJData and UBJSON is the endianness of numerical values. In BJData, all numerical data types (integers UiuImlML and floating-point values hdD) are stored in the little-endian (LE) byte order as opposed to big-endian as used by UBJSON. Adopting LE to store numeric records avoids unnecessary byte swapping on most modern computers where LE is used as the default byte order.
Optimized formats
Optimized formats for containers are supported via two parameters of to_bjdata:
use_size adds size information to the beginning of a container and removes the closing marker.use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The use_type parameter must only be used together with use_size = true.Note that use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed of the number of elements in the container.
ND-array optimized format
BJData extends UBJSON's optimized array size marker to support ND-arrays of uniform numerical data types (referred to as packed arrays). For example, the 2-D uint8 integer array [[1,2],[3,4],[5,6]], stored as nested optimized array in UBJSON [ [$U#i2 1 2 [$U#i2 3 4 [$U#i2 5 6 ], can be further compressed in BJData to [$U#[$i#i2 2 3 1 2 3 4 5 6 or [$U#[i2 i3] 1 2 3 4 5 6.
To maintain type and size information, ND-arrays are converted to JSON objects following the annotated array format (defined in the JData specification (Draft 3)), when parsed using from_bjdata. For example, the above 2-D uint8 array can be parsed and accessed as
{\n \"_ArrayType_\": \"uint8\",\n \"_ArraySize_\": [2,3],\n \"_ArrayData_\": [1,2,3,4,5,6]\n}\n Likewise, when a JSON object in the above form is serialzed using to_bjdata, it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated.
The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array.
Restrictions in optimized data types for arrays and objects
Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of UiuImlMLhdDC. This also means other variable ([{SH) or zero-length types (TFN) can not be used in an optimized array or object in BJData.
Binary values
If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print BJData's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to BJData\n std::vector<std::uint8_t> v = json::to_bjdata(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to BJData using default representation\n std::vector<std::uint8_t> v_array = json::to_bjdata(array);\n // serialize it to BJData using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);\n // serialize it to BJData using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"features/binary_formats/bjdata/#deserialization","title":"Deserialization","text":"The library maps BJData types to JSON value types as follows:
BJData type JSON value type marker no-op no value, next value is readN null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) { Complete mapping
The mapping is complete in the sense that any BJData value can be converted to a JSON value.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with BJData\n json j = json::from_bjdata(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/bson/","title":"BSON","text":"BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type.
References
The library uses the following mapping from JSON values types to BSON types:
JSON value type value/range BSON type marker nullnull null 0x0A boolean true, false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 Incomplete mapping
The mapping is incomplete, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector<std::uint8_t> v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 \n"},{"location":"features/binary_formats/bson/#deserialization","title":"Deserialization","text":"The library maps BSON record types to JSON value types as follows:
BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupportedIncomplete mapping
The mapping is incomplete. The unsupported mappings are indicated in the table above.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d,\n 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73,\n 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00\n };\n\n // deserialize it with BSON\n json j = json::from_bson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/cbor/","title":"CBOR","text":"The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation.
References
The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049):
JSON value type value/range CBOR type first byte nullnull Null 0xF6 boolean true True 0xF5 boolean false False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length: 0..23 UTF-8 string 0x60..0x77 string length: 23..255 UTF-8 string (1 byte follow) 0x78 string length: 256..65535 UTF-8 string (2 bytes follow) 0x79 string length: 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length: 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size: 0..23 array 0x80..0x97 array size: 23..255 array (1 byte follow) 0x98 array size: 256..65535 array (2 bytes follow) 0x99 array size: 65536..4294967295 array (4 bytes follow) 0x9A array size: 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size: 0..23 map 0xA0..0xB7 object size: 23..255 map (1 byte follow) 0xB8 object size: 256..65535 map (2 bytes follow) 0xB9 object size: 65536..4294967295 map (4 bytes follow) 0xBA object size: 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size: 0..23 byte string 0x40..0x57 binary size: 23..255 byte string (1 byte follow) 0x58 binary size: 256..65535 byte string (2 bytes follow) 0x59 binary size: 65536..4294967295 byte string (4 bytes follow) 0x5A binary size: 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above.
Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a CBOR value.
NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to null.
Unused CBOR types
The following CBOR types are not used in the conversion:
Tagged items
Binary subtypes will be serialized as tagged items. See binary values for an example.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to CBOR\n std::vector<std::uint8_t> v = json::to_cbor(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"features/binary_formats/cbor/#deserialization","title":"Deserialization","text":"The library maps CBOR types to JSON value types as follows:
CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF Falsefalse 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB Incomplete mapping
The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors:
Object keys
CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected.
Tagged items
Tagged items will throw a parse error by default. They can be ignored by passing cbor_tag_handler_t::ignore to function from_cbor. They can be stored by passing cbor_tag_handler_t::store to function from_cbor.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0xa2, 0x67, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xf5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with CBOR\n json j = json::from_cbor(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/messagepack/","title":"MessagePack","text":"MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.
References
The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification:
JSON value type value/range MessagePack type first byte nullnull nil 0xC0 boolean true true 0xC3 boolean false false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length: 0..31 fixstr 0xA0..0xBF string length: 32..255 str 8 0xD9 string length: 256..65535 str 16 0xDA string length: 65536..4294967295 str 32 0xDB array size: 0..15 fixarray 0x90..0x9F array size: 16..65535 array 16 0xDC array size: 65536..4294967295 array 32 0xDD object size: 0..15 fix map 0x80..0x8F object size: 16..65535 map 16 0xDE object size: 65536..4294967295 map 32 0xDF binary size: 0..255 bin 8 0xC4 binary size: 256..65535 bin 16 0xC5 binary size: 65536..4294967295 bin 32 0xC6 Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value.
Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.
Size constraints
The following values can not be converted to a MessagePack value:
NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the dump function which serializes NaN or Infinity to null.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n Output:
0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 \n"},{"location":"features/binary_formats/messagepack/#deserialization","title":"Deserialization","text":"The library maps MessagePack types to JSON value types as follows:
MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nilnull 0xC0 false false 0xC2 true true 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF Info
Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/binary_formats/ubjson/","title":"UBJSON","text":"Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON.
References
The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:
JSON value type value/range UBJSON type marker nullnull null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map { Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.
Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson.
Size constraints
The following values can not be converted to a UBJSON value:
Unused UBJSON markers
The following markers are not used in the conversion:
Z: no-op values are not created.C: single-byte strings are serialized with S markers.NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.
Optimized formats
The optimized formats for containers are supported: Parameter use_size adds size information to the beginning of a container and removes the closing marker. Parameter use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The use_type parameter must only be used together with use_size = true.
Note that use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container.
Binary values
If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON documentation. In particular, this means that serialization and the deserialization of a JSON containing binary values into UBJSON and back will result in a different JSON object.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\n// function to print UBJSON's diagnostic format\nvoid print_byte(uint8_t byte)\n{\n if (32 < byte and byte < 128)\n {\n std::cout << (char)byte;\n }\n else\n {\n std::cout << (int)byte;\n }\n}\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": false})\"_json;\n\n // serialize it to UBJSON\n std::vector<std::uint8_t> v = json::to_ubjson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n // create an array of numbers\n json array = {1, 2, 3, 4, 5, 6, 7, 8};\n\n // serialize it to UBJSON using default representation\n std::vector<std::uint8_t> v_array = json::to_ubjson(array);\n // serialize it to UBJSON using size optimization\n std::vector<std::uint8_t> v_array_size = json::to_ubjson(array, true);\n // serialize it to UBJSON using type optimization\n std::vector<std::uint8_t> v_array_size_and_type = json::to_ubjson(array, true, true);\n\n // print the vector contents\n for (auto& byte : v_array)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n\n for (auto& byte : v_array_size_and_type)\n {\n print_byte(byte);\n }\n std::cout << std::endl;\n}\n Output:
{i7compactTi6schemaF}\n[i1i2i3i4i5i6i7i8]\n[#i8i1i2i3i4i5i6i7i8\n[$i#i812345678\n"},{"location":"features/binary_formats/ubjson/#deserialization","title":"Deserialization","text":"The library maps UBJSON types to JSON value types as follows:
UBJSON type JSON value type marker no-op no value, next value is readN null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) { Complete mapping
The mapping is complete in the sense that any UBJSON value can be converted to a JSON value.
Example#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,\n 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,\n 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D\n };\n\n // deserialize it with UBJSON\n json j = json::from_ubjson(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}\n Output:
{\n \"compact\": true,\n \"schema\": 0\n}\n"},{"location":"features/element_access/","title":"Element Access","text":"There are many ways elements in a JSON value can be accessed:
operator[]atvalueThe at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise.
Consider the following JSON value:
{\n \"name\": \"Mary Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n Assume the value is parsed to a json variable j.
j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j.at(\"name\") \"Mary Smith\" j.at(\"age\") 42 j.at(\"hobbies\") [\"hiking\", \"reading\"] j.at(\"hobbies\").at(0) \"hiking\" j.at(\"hobbies\").at(1) \"reading\" The return value is a reference, so it can be modified by the original value.
Write accessj.at(\"name\") = \"John Smith\";\n This code produces the following JSON value:
{\n \"name\": \"John Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n When accessing an invalid index (i.e., an index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown.
Accessing via invalid index or missing keyj.at(\"hobbies\").at(3) = \"cooking\";\n This code produces the following exception:
[json.exception.out_of_range.401] array index 3 is out of range\n When you extended diagnostic messages are enabled by defining JSON_DIAGNOSTICS, the exception further gives information where the key or index is missing or out of range.
[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n"},{"location":"features/element_access/checked_access/#notes","title":"Notes","text":"Exceptions
at can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown.basic_json::out_of_range exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid.basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown access to invalid array index basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown"},{"location":"features/element_access/default_value/","title":"Access with default value: value","text":""},{"location":"features/element_access/default_value/#overview","title":"Overview","text":"In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present.
ExampleConsider the following JSON value:
{\n \"logOutput\": \"result.log\",\n \"append\": true\n}\n Assume the value is parsed to a json variable j.
j {\"logOutput\": \"result.log\", \"append\": true} j.value(\"logOutput\", \"logfile.log\") \"result.log\" j.value(\"append\", true) true j.value(\"append\", false) true j.value(\"logLevel\", \"verbose\") \"verbose\""},{"location":"features/element_access/default_value/#note","title":"Note","text":"Exceptions
value can only be used with objects. For other types, a basic_json::type_error is thrown.Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std::map and a std::vector, respectively.
Consider the following JSON value:
{\n \"name\": \"Mary Smith\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n Assume the value is parsed to a json variable j.
j {\"name\": \"Mary Smith\", \"age\": 42, \"hobbies\": [\"hiking\", \"reading\"]} j[\"name\"] \"Mary Smith\" j[\"age\"] 42 j[\"hobbies\"] [\"hiking\", \"reading\"] j[\"hobbies\"][0] \"hiking\" j[\"hobbies\"][1] \"reading\" The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten.
j[\"name\"] = \"John Smith\";\nj[\"maidenName\"] = \"Jones\";\n This code produces the following JSON value:
{\n \"name\": \"John Smith\",\n \"maidenName\": \"Jones\",\n \"age\": 42,\n \"hobbies\": [\"hiking\", \"reading\"]\n}\n When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with null.
null values j[\"hobbies\"][0] = \"running\";\nj[\"hobbies\"][3] = \"cooking\";\n This code produces the following JSON value:
{\n \"name\": \"John Smith\",\n \"maidenName\": \"Jones\",\n \"age\": 42,\n \"hobbies\": [\"running\", \"reading\", null, \"cooking\"]\n}\n"},{"location":"features/element_access/unchecked_access/#notes","title":"Notes","text":"Design rationale
The library behaves differently to std::vector and std::map:
std::vector::operator[] never inserts a new element.std::map::operator[] is not available for const values.The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.
Info
The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.
Danger
NDEBUG or redefine the macro JSON_ASSERT(x). See the documentation on runtime assertions for more information.Exceptions
operator[] can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown.
null value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted null value is returned; any index between previous maximal index and passed index are filled with null undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"Note
This page is under construction.
"},{"location":"features/parsing/#input","title":"Input","text":""},{"location":"features/parsing/#sax-vs-dom-parsing","title":"SAX vs. DOM parsing","text":""},{"location":"features/parsing/#exceptions","title":"Exceptions","text":"See parsing and exceptions.
"},{"location":"features/parsing/json_lines/","title":"JSON Lines","text":"The JSON Lines format is a text format of newline-delimited JSON. In particular:
\\n. As \\r is silently ignored, \\r\\n is also supported.\\n, but is not required to be one.JSON Text example
{\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]}\n{\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]}\n{\"name\": \"May\", \"wins\": []}\n{\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]}\n JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used:
Example: Parse JSON Text input line by line
The example below demonstrates how JSON Lines can be processed.
#include <sstream>\n#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // JSON Lines (see https://jsonlines.org)\n std::stringstream input;\n input << R\"({\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]}\n{\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]}\n{\"name\": \"May\", \"wins\": []}\n{\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]}\n)\";\n\n std::string line;\n while (std::getline(input, line))\n {\n std::cout << json::parse(line) << std::endl;\n }\n}\n Output:
{\"name\":\"Gilbert\",\"wins\":[[\"straight\",\"7\u2663\"],[\"one pair\",\"10\u2665\"]]}\n{\"name\":\"Alexa\",\"wins\":[[\"two pair\",\"4\u2660\"],[\"two pair\",\"9\u2660\"]]}\n{\"name\":\"May\",\"wins\":[]}\n{\"name\":\"Deloise\",\"wins\":[[\"three of a kind\",\"5\u2663\"]]}\n Note
Using operator>> like
json j;\nwhile (input >> j)\n{\n std::cout << j << std::endl;\n}\n with a JSON Lines input does not work, because the parser will try to parse one value after the last one.
"},{"location":"features/parsing/parse_exceptions/","title":"Parsing and Exceptions","text":"When the input is not valid JSON, an exception of type parse_error is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions. In case you process untrusted input, always enclose your code with a try/catch block, like
json j;\ntry\n{\n j = json::parse(my_input);\n}\ncatch (json::parse_error& ex)\n{\n std::cerr << \"parse error at byte \" << ex.byte << std::endl;\n}\n In case exceptions are undesired or not supported by the environment, there are different ways to proceed:
"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs (true, default) or whether a discarded value should be returned (false).
json j = json::parse(my_input, nullptr, false);\nif (j.is_discarded())\n{\n std::cerr << \"parse error\" << std::endl;\n}\n Note there is no diagnostic information available in this scenario.
"},{"location":"features/parsing/parse_exceptions/#use-accept-function","title":"Use accept() function","text":"Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON.
if (!json::accept(my_input))\n{\n std::cerr << \"parse error\" << std::endl;\n}\n Again, there is no diagnostic information available.
"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","title":"User-defined SAX interface","text":"Finally, you can implement the SAX interface and decide what should happen in case of a parse error.
This function has the following interface:
bool parse_error(std::size_t position,\n const std::string& last_token,\n const json::exception& ex);\n The return value indicates whether the parsing should continue, so the function should usually return false.
#include <iostream>\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nclass sax_no_exception : public nlohmann::detail::json_sax_dom_parser<json>\n{\n public:\n sax_no_exception(json& j)\n : nlohmann::detail::json_sax_dom_parser<json>(j, false)\n {}\n\n bool parse_error(std::size_t position,\n const std::string& last_token,\n const json::exception& ex)\n {\n std::cerr << \"parse error at input byte \" << position << \"\\n\"\n << ex.what() << \"\\n\"\n << \"last read: \\\"\" << last_token << \"\\\"\"\n << std::endl;\n return false;\n }\n};\n\nint main()\n{\n std::string myinput = \"[1,2,3,]\";\n\n json result;\n sax_no_exception sax(result);\n\n bool parse_result = json::sax_parse(myinput, &sax);\n if (!parse_result)\n {\n std::cerr << \"parsing unsuccessful!\" << std::endl;\n }\n\n std::cout << \"parsed value: \" << result << std::endl;\n}\n Output:
parse error at input byte 8\n[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nlast read: \"3,]\"\nparsing unsuccessful!\nparsed value: [1,2,3]\n"},{"location":"features/parsing/parser_callbacks/","title":"Parser Callbacks","text":""},{"location":"features/parsing/parser_callbacks/#overview","title":"Overview","text":"With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
The type of the callback function is:
template<typename BasicJsonType>\nusing parser_callback_t =\n std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n"},{"location":"features/parsing/parser_callbacks/#callback-event-types","title":"Callback event types","text":"We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example When parsing the following JSON text,
{\n \"name\": \"Berlin\",\n \"location\": [\n 52.519444,\n 13.406667\n ]\n}\n these calls are made to the callback function:
event depth parsedobject_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [52.519444,13.406667] object_end 0 {\"location\":[52.519444,13.406667],\"name\":\"Berlin\"}"},{"location":"features/parsing/parser_callbacks/#return-value","title":"Return value","text":"Discarding a value (i.e., returning false) has different effects depending on the context in which the function was called:
null. This case happens if the top-level element is skipped.The example below demonstrates the parse() function with and without callback function.
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, 38793]\n }\n }\n )\";\n\n // parse and serialize JSON\n json j_complete = json::parse(text);\n std::cout << std::setw(4) << j_complete << \"\\n\\n\";\n\n // define parser callback\n json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)\n {\n // skip object elements with key \"Thumbnail\"\n if (event == json::parse_event_t::key and parsed == json(\"Thumbnail\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n };\n\n // parse (with callback) and serialize JSON\n json j_filtered = json::parse(text, cb);\n std::cout << std::setw(4) << j_filtered << '\\n';\n}\n Output:
{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Thumbnail\": {\n \"Height\": 125,\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Width\": 100\n },\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n\n{\n \"Image\": {\n \"Animated\": false,\n \"Height\": 600,\n \"IDs\": [\n 116,\n 943,\n 234,\n 38793\n ],\n \"Title\": \"View from 15th Floor\",\n \"Width\": 800\n }\n}\n"},{"location":"features/parsing/sax_interface/","title":"SAX Interface","text":"The library uses a SAX-like interface with the following functions:
classDiagram\n\nclass sax_t [\"json::sax_t\"] {\n <<interface>>\n +bool null()*\n\n +bool boolean(bool val)*\n\n +bool number_integer(number_integer_t val)*\n +bool number_unsigned(number_unsigned_t val)*\n\n +bool number_float(number_float_t val, const string_t& s)*\n\n +bool string(string_t& val)*\n +bool binary(binary_t& val)*\n\n +bool start_object(std::size_t elements)*\n +bool end_object()*\n +bool start_array(std::size_t elements)*\n +bool end_array()*\n +bool key(string_t& val)*\n\n +bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex)*\n} // called when null is parsed\nbool null();\n\n// called when a boolean is parsed; value is passed\nbool boolean(bool val);\n\n// called when a signed or unsigned integer number is parsed; value is passed\nbool number_integer(number_integer_t val);\nbool number_unsigned(number_unsigned_t val);\n\n// called when a floating-point number is parsed; value and original string is passed\nbool number_float(number_float_t val, const string_t& s);\n\n// called when a string is parsed; value is passed and can be safely moved away\nbool string(string_t& val);\n// called when a binary value is parsed; value is passed and can be safely moved away\nbool binary(binary& val);\n\n// called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)\nbool start_object(std::size_t elements);\nbool end_object();\nbool start_array(std::size_t elements);\nbool end_array();\n// called when an object key is parsed; value is passed and can be safely moved away\nbool key(string_t& val);\n\n// called when a parse error occurs; byte position, the last token, and an exception is passed\nbool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex);\n The return value of each function determines whether parsing should proceed.
To implement your own SAX handler, proceed as follows:
nlohmann::json_sax<json> as base class, but you can also use any class where the functions described above are implemented and public.my_sax.bool json::sax_parse(input, &my_sax); where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return json value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error - it is up to you what to do with the exception object passed to your parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file json_sax.hpp.
This page gives an overview how JSON values are stored and how this can be configured.
"},{"location":"features/types/#overview","title":"Overview","text":"By default, JSON values are stored as follows:
JSON type C++ type objectstd::map<std::string, basic_json> array std::vector<basic_json> null std::nullptr_t string std::string boolean bool number std::int64_t, std::uint64_t, and double Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.
"},{"location":"features/types/#storage","title":"Storage","text":"classDiagram\n\nclass value_t {\n <<enumeration>>\n null\n object\n array\n string\n boolean\n number_integer\n number_unsigned\n number_float\n binary\n discarded\n}\n\nclass json_value {\n <<union>>\n object_t* object\n array_t* array\n string_t* string\n binary_t* binary\n boolean_t boolean\n number_integer_t number_integer\n number_unsigned_t number_unsigned\n number_float_t number_float\n}\n\nclass basic_json {\n -value_t m_type\n -json_value m_value\n +typedef object_t\n +typedef array_t\n +typedef binary_t\n +typedef boolean_t\n +typedef number_integer_t\n +typedef number_unsigned_t\n +typedef number_float_t\n}\n\nbasic_json .. json_value\nbasic_json .. value_t"},{"location":"features/types/#template-arguments","title":"Template arguments","text":"The data types to store a JSON value are derived from the template arguments passed to class basic_json:
template<\n template<typename U, typename V, typename... Args> class ObjectType = std::map,\n template<typename U, typename... Args> class ArrayType = std::vector,\n class StringType = std::string,\n class BooleanType = bool,\n class NumberIntegerType = std::int64_t,\n class NumberUnsignedType = std::uint64_t,\n class NumberFloatType = double,\n template<typename U> class AllocatorType = std::allocator,\n template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,\n class BinaryType = std::vector<std::uint8_t>\n>\nclass basic_json;\n Type json is an alias for basic_json<> and uses the default types.
From the template arguments, the following types are derived:
using object_comparator_t = std::less<>;\nusing object_t = ObjectType<StringType, basic_json, object_comparator_t,\n AllocatorType<std::pair<const StringType, basic_json>>>;\n\nusing array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n\nusing string_t = StringType;\n\nusing boolean_t = BooleanType;\n\nusing number_integer_t = NumberIntegerType;\nusing number_unsigned_t = NumberUnsignedType;\nusing number_float_t = NumberFloatType;\n\nusing binary_t = nlohmann::byte_container_with_subtype<BinaryType>;\n"},{"location":"features/types/#objects","title":"Objects","text":"RFC 8259 describes JSON objects as follows:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
"},{"location":"features/types/#default-type","title":"Default type","text":"With the default values for ObjectType (std::map), StringType (std::string), and AllocatorType (std::allocator), the default value for object_t is:
std::map<\n std::string, // key_type\n basic_json, // value_type\n std::less<>, // key_compare\n std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n>\n"},{"location":"features/types/#behavior","title":"Behavior","text":"The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
{\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.dump) in this order. For instance, both {\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be stored and serialized as {\"a\": 2, \"b\": 1}.{\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be treated as equal.The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259, because any order implements the specified \"unordered\" nature of JSON objects.
RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.
Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.
RFC 8259 describes JSON arrays as follows:
An array is an ordered sequence of zero or more values.
"},{"location":"features/types/#default-type_1","title":"Default type","text":"With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:
std::vector<\n basic_json, // value_type\n std::allocator<basic_json> // allocator_type\n>\n"},{"location":"features/types/#limits_1","title":"Limits","text":"RFC 8259 specifies:
An implementation may set limits on the maximum depth of nesting.
In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.
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.
RFC 8259 describes JSON strings as follows:
A string is a sequence of zero or more Unicode characters.
Unicode values are split by the JSON class into byte-sized characters during deserialization.
"},{"location":"features/types/#default-type_2","title":"Default type","text":"With the default values for StringType (std::string), the default value for string_t is std::string.
Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.
RFC 8259 states:
Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal.
This implementation is interoperable as it does compare strings code unit by code unit.
"},{"location":"features/types/#storage_3","title":"Storage","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.
RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false.
With the default values for BooleanType (bool), the default value for boolean_t is bool.
Boolean values are stored directly inside a basic_json type.
See the number handling article for a detailed discussion on how numbers are handled by this library.
RFC 8259 describes numbers as follows:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t, and number_float_t are used.
With the default values for NumberIntegerType (std::int64_t), the default value for number_integer_t is std::int64_t. With the default values for NumberUnsignedType (std::uint64_t), the default value for number_unsigned_t is std::uint64_t. With the default values for NumberFloatType (double), the default value for number_float_t is double.
010 will be serialized to 8. During deserialization, leading zeros yield an error.null.RFC 8259 specifies:
An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t.
When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t.
RFC 8259 further states:
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.
RFC 8259 states:
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.
This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.
Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.
This document describes how the library is handling numbers.
"},{"location":"features/types/number_handling/#background","title":"Background","text":"This section briefly summarizes how the JSON specification describes how numbers should be handled.
"},{"location":"features/types/number_handling/#json-number-syntax","title":"JSON number syntax","text":"JSON defines the syntax of numbers as follows:
RFC 8259, Section 6
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed.
A fraction part is a decimal point followed by one or more digits.
An exponent part begins with the letter E in uppercase or lowercase, which may be followed by a plus or minus sign. The E and optional sign are followed by one or more digits.
The following railroad diagram from json.org visualizes the number syntax:
"},{"location":"features/types/number_handling/#number-interoperability","title":"Number interoperability","text":"On number interoperability, the following remarks are made:
RFC 8259, Section 6
This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available.
Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.
"},{"location":"features/types/number_handling/#library-implementation","title":"Library implementation","text":"This section describes how the above number specification is implemented by this library.
"},{"location":"features/types/number_handling/#number-storage","title":"Number storage","text":"In the default json type, numbers are stored as std::uint64_t, std::int64_t, and double, respectively. Thereby, std::uint64_t and std::int64_t are used only if they can store the number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as double.
Notes
double.std::strtoull, std::strtoll, and std::strtod, respectively.Examples
-12345678912345789123456789 is smaller than INT64_MIN and will be stored as floating-point number -1.2345678912345788e+25.1E3 will be stored as floating-point number 1000.0.double (i.e., numbers that after conversion via std::strtod are not satisfying std::isfinite such as 1E400) will throw exception json.exception.out_of_range.406 during parsing.double. For instance 3.141592653589793238462643383279 is stored as 0x400921fb54442d18. This is the same behavior as the code double x = 3.141592653589793238462643383279;.Interoperability
double. This also concurs with the specification above.The JSON number grammar allows for different ways to express zero, and this library will store zeros differently:
Literal Stored value and type Serialization0 std::uint64_t(0) 0 -0 std::int64_t(0) 0 0.0 double(0.0) 0.0 -0.0 double(-0.0) -0.0 0E0 double(0.0) 0.0 -0E0 double(-0.0) -0.0 That is, -0 is stored as a signed integer, but the serialization does not reproduce the -.
%g printf modifier with std::numeric_limits<double>::max_digits10 significant digits. The rationale is to use the shortest representation while still allow round-tripping.Notes regarding precision of floating-point numbers
As described above, floating-point numbers are rounded to the nearest double and serialized with the shortest representation to allow round-tripping. This can yield confusing examples:
2555.5599999999999 will be serialized as 2555.56. The reverse can also be true.0.0000972439793401814 will be serialized as 9.72439793401814e-05. The reverse can also be true: 12345E-5 will be serialized as 0.12345.float to double can also introduce rounding errors: float f = 0.3;\njson j = f;\nstd::cout << j << '\\n';\n yields 0.30000001192092896.All examples here can be reproduced by passing the original double value to
std::printf(\"%.*g\\n\", std::numeric_limits<double>::max_digits10, double_value);\n"},{"location":"features/types/number_handling/#nan-handling","title":"NaN handling","text":"NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded:
RFC 8259, Section 6
Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment.
This library serializes NaN values as null. This corresponds to the behavior of JavaScript's JSON.stringify function.
Example
The following example shows how a NaN value is stored in a json value.
int main()\n{\n double val = std::numeric_limits<double>::quiet_NaN();\n std::cout << \"val=\" << val << std::endl;\n json j = val;\n std::cout << \"j=\" << j.dump() << std::endl;\n val = j;\n std::cout << \"val=\" << val << std::endl;\n}\n output:
val=nan\nj=null\nval=nan\n"},{"location":"features/types/number_handling/#number-comparison","title":"Number comparison","text":"Floating-point inside JSON values numbers are compared with json::number_float_t::operator== which is double::operator== by default.
Alternative comparison functions
To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance
template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\ninline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n{\n return std::abs(a - b) <= epsilon;\n}\n Or you can self-define an operator equal function like this: bool my_equal(const_reference lhs, const_reference rhs)\n{\n const auto lhs_type lhs.type();\n const auto rhs_type rhs.type();\n if (lhs_type == rhs_type)\n {\n switch(lhs_type)\n {\n // self_defined case\n case value_t::number_float:\n return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();\n\n // other cases remain the same with the original\n ...\n }\n }\n ...\n}\n (see #703 for more information.)
Note
NaN values never compare equal to themselves or to other NaN values. See #514.
"},{"location":"features/types/number_handling/#number-conversion","title":"Number conversion","text":"Just like the C++ language itself, the get family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising.
Unconditional number conversions
double d = 42.3; // non-integer double value 42.3\njson jd = d; // stores double value 42.3\nstd::int64_t i = jd.template get<std::int64_t>(); // now i==42; no warning or error is produced\n Note the last line with throw a json.exception.type_error.302 exception if jd is not a numerical type, for instance a string.
The rationale is twofold:
Conditional number conversion
The code above can be solved by explicitly checking the nature of the value with members such as is_number_integer() or is_number_unsigned():
// check if jd is really integer-valued\nif (jd.is_number_integer())\n{\n // if so, do the conversion and use i\n std::int64_t i = jd.template get<std::int64_t>();\n // ...\n}\nelse\n{\n // otherwise, take appropriate action\n // ...\n}\n Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.
(Example taken from #777.)
"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"As the example in Number conversion shows, there are different functions to determine the type of the stored number:
is_number() returns true for any number typeis_number_integer() returns true for signed and unsigned integersis_number_unsigned() returns true for unsigned integers onlyis_number_float() returns true for floating-point numberstype_name() returns \"number\" for any number typetype() returns a different enumerator of value_t for all number typesis_number() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"The number types can be changed with template parameters.
position number type default type possible values 5 signed integersstd::int64_t std::int32_t, std::int16_t, etc. 6 unsigned integers std::uint64_t std::uint32_t, std::uint16_t, etc. 7 floating-point double float, long double Constraints on number types
long long. The type for floating-point numbers is used in case of overflow.unsigned long long. The type for floating-point numbers is used in case of overflow.double, float, and long double are supported for floating-point numbers.Example
A basic_json type that uses long double as floating-point type.
using json_ld = nlohmann::basic_json<std::map, std::vector, std::string, bool,\n std::int64_t, std::uint64_t, long double>;\n Note values should then be parsed with json_ld::parse rather than json::parse as the latter would parse floating-point values to double before then converting them to long double.
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
"},{"location":"home/code_of_conduct/#our-standards","title":"Our Standards","text":"Examples of behavior that contributes to creating a positive environment include:
Examples of unacceptable behavior by participants include:
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
"},{"location":"home/code_of_conduct/#scope","title":"Scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
"},{"location":"home/code_of_conduct/#enforcement","title":"Enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
"},{"location":"home/code_of_conduct/#attribution","title":"Attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4
"},{"location":"home/customers/","title":"Customers","text":"The library is used in multiple projects, applications, operating systems, etc. The list below is not exhaustive, but the result of an internet search. If you know further customers of the library, please let me know.
"},{"location":"home/customers/#space-exploration","title":"Space Exploration","text":"#include \"json.hpp\"#include <nlohmann/json.hpp>.There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:
Intuitive syntax. In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code.
Trivial integration. Our whole code consists of a single header file json.hpp. That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings.
Serious testing. Our class is heavily unit-tested and covers 100% of the code, including all exceptional behavior. Furthermore, we checked with Valgrind and the Clang Sanitizers that there are no memory leaks. Google OSS-Fuzz additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the Core Infrastructure Initiative (CII) best practices.
Other aspects were not so important to us:
Memory efficiency. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C++ data types: std::string for strings, int64_t, uint64_t or double for numbers, std::map for objects, std::vector for arrays, and bool for Booleans. However, you can template the generalized class basic_json to your needs.
Speed. There are certainly faster JSON libraries out there. However, if your goal is to speed up your development by adding JSON support with a single header, then this library is the way to go. If you know how to use a std::vector or std::map, you are already set.
See the contribution guidelines for more information.
"},{"location":"home/exceptions/","title":"Exceptions","text":""},{"location":"home/exceptions/#overview","title":"Overview","text":""},{"location":"home/exceptions/#base-type","title":"Base type","text":"All exceptions inherit from class json::exception (which in turn inherits from std::exception). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions.
classDiagram\n direction LR\n class `std::exception` {\n <<interface>>\n }\n\n class `json::exception` {\n +const int id\n +const char* what() const\n }\n\n class `json::parse_error` {\n +const std::size_t byte\n }\n\n class `json::invalid_iterator`\n class `json::type_error`\n class `json::out_of_range`\n class `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`"},{"location":"home/exceptions/#switch-off-exceptions","title":"Switch off exceptions","text":"Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION. In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw), JSON_TRY_USER (overriding try), and JSON_CATCH_USER (overriding catch).
Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>\n\n#define JSON_TRY_USER if(true)\n#define JSON_CATCH_USER(exception) if(false)\n#define JSON_THROW_USER(exception) \\\n {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\\n << \" (function \" << __FUNCTION__ << \") - \" \\\n << (exception).what() << std::endl; \\\n std::abort();}\n\n#include <nlohmann/json.hpp>\n Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
See documentation of JSON_TRY_USER, JSON_CATCH_USER and JSON_THROW_USER for more information.
Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult.
Example#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] type must be number, but is string\n This exception can be hard to debug if storing the value \"12\" and accessing it is further apart.
To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer.
As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp.
#include <iostream>\n\n# define JSON_DIAGNOSTICS 1\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n json j;\n j[\"address\"][\"street\"] = \"Fake Street\";\n j[\"address\"][\"housenumber\"] = \"12\";\n\n try\n {\n int housenumber = j[\"address\"][\"housenumber\"];\n }\n catch (const json::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string\n Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.
See documentation of JSON_DIAGNOSTICS for more information.
This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.
Exceptions have ids 1xx.
Byte index
Member byte holds the byte index of the last read character in the input file.
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).
ExampleThe following code shows how a parse_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // parsing input with a syntax error\n json::parse(\"[1,2,3,]\");\n }\n catch (const json::parse_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << '\\n'\n << \"byte position of error: \" << e.byte << std::endl;\n }\n}\n Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\nexception id: 101\nbyte position of error: 8\n"},{"location":"home/exceptions/#jsonexceptionparse_error101","title":"json.exception.parse_error.101","text":"This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte indicates the error position.
Example message
Input ended prematurely:
[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal\n No input:
[json.exception.parse_error.101] parse error at line 1, column 1: attempting to parse an empty input; check that your input string or stream contains the expected JSON\n Control character was not escaped:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\\\; last read: '\"<U+0009>'\"\n String was not closed:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '\"'\n Invalid number format:
[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'\n \\u was not be followed by four hex digits:
[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\\u' must be followed by 4 hex digits; last read: '\"\\u01\"'\n Invalid UTF-8 surrogate pair:
[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uD7FF\\uDC00'\"\n Invalid UTF-8 byte:
[json.exception.parse_error.101] parse error at line 3, column 24: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '\"vous \\352t'\n Tip
JSON uses the \\uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \\uxxxx entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
Example message
parse error at 14: missing or wrong low surrogate\n Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
"},{"location":"home/exceptions/#jsonexceptionparse_error103","title":"json.exception.parse_error.103","text":"Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
Example message
parse error: code points above 0x10FFFF are invalid\n Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
"},{"location":"home/exceptions/#jsonexceptionparse_error104","title":"json.exception.parse_error.104","text":"RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.
Example message
[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\n"},{"location":"home/exceptions/#jsonexceptionparse_error105","title":"json.exception.parse_error.105","text":"An operation of a JSON Patch document must contain exactly one \"op\" member, whose value indicates the operation to perform. Its value must be one of \"add\", \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are errors.
Example message
[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'\n [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'\n [json.exception.parse_error.105] parse error: operation value 'foo' is invalid\n"},{"location":"home/exceptions/#jsonexceptionparse_error106","title":"json.exception.parse_error.106","text":"An array index in a JSON Pointer (RFC 6901) may be 0 or any number without a leading 0.
Example message
[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n"},{"location":"home/exceptions/#jsonexceptionparse_error107","title":"json.exception.parse_error.107","text":"A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character.
Example message
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'\n"},{"location":"home/exceptions/#jsonexceptionparse_error108","title":"json.exception.parse_error.108","text":"In a JSON Pointer, only ~0 and ~1 are valid escape sequences.
Example message
[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'\n"},{"location":"home/exceptions/#jsonexceptionparse_error109","title":"json.exception.parse_error.109","text":"A JSON Pointer array index must be a number.
Example messages
[json.exception.parse_error.109] parse error: array index 'one' is not a number\n [json.exception.parse_error.109] parse error: array index '+1' is not a number\n"},{"location":"home/exceptions/#jsonexceptionparse_error110","title":"json.exception.parse_error.110","text":"When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
Example message
[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input\n [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A\n"},{"location":"home/exceptions/#jsonexceptionparse_error112","title":"json.exception.parse_error.112","text":"An unexpected byte was read in a binary format or length information is invalid (BSON).
Example messages
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C\n [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1\n [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02\n [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02\n [json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648\n [json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1\n"},{"location":"home/exceptions/#jsonexceptionparse_error113","title":"json.exception.parse_error.113","text":"While parsing a map key, a value that is not a string has been read.
Example messages
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF\n [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack string: expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0xFF\n [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing UBJSON char: byte after 'C' must be in range 0x00..0x7F; last byte: 0x82\n"},{"location":"home/exceptions/#jsonexceptionparse_error114","title":"json.exception.parse_error.114","text":"The parsing of the corresponding BSON record type is not implemented (yet).
Example message
[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF\n"},{"location":"home/exceptions/#jsonexceptionparse_error115","title":"json.exception.parse_error.115","text":"A UBJSON high-precision number could not be parsed.
Example message
[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A\n"},{"location":"home/exceptions/#iterator-errors","title":"Iterator errors","text":"This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx.
ExampleThe following code shows how an invalid_iterator exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling iterator::key() on non-object iterator\n json j = \"string\";\n json::iterator it = j.begin();\n auto k = it.key();\n }\n catch (const json::invalid_iterator& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators\nexception id: 207\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","title":"json.exception.invalid_iterator.201","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.
Example message
[json.exception.invalid_iterator.201] iterators are not compatible\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","title":"json.exception.invalid_iterator.202","text":"In the erase or insert function, the passed iterator pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
Example messages
[json.exception.invalid_iterator.202] iterator does not fit current value\n [json.exception.invalid_iterator.202] iterators first and last must point to objects\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","title":"json.exception.invalid_iterator.203","text":"Either iterator passed to function erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
Example message
[json.exception.invalid_iterator.203] iterators do not fit current value\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","title":"json.exception.invalid_iterator.204","text":"When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
Example message
[json.exception.invalid_iterator.204] iterators out of range\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","title":"json.exception.invalid_iterator.205","text":"When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
Example message
[json.exception.invalid_iterator.205] iterator out of range\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","title":"json.exception.invalid_iterator.206","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
Example message
[json.exception.invalid_iterator.206] cannot construct with iterators from null\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","title":"json.exception.invalid_iterator.207","text":"The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
Example message
[json.exception.invalid_iterator.207] cannot use key() for non-object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","title":"json.exception.invalid_iterator.208","text":"The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.208] cannot use operator[] for object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","title":"json.exception.invalid_iterator.209","text":"The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.209] cannot use offsets with object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","title":"json.exception.invalid_iterator.210","text":"The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.
Example message
[json.exception.invalid_iterator.210] iterators do not fit\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","title":"json.exception.invalid_iterator.211","text":"The iterator range passed to the insert function must not be a subrange of the container to insert to.
Example message
[json.exception.invalid_iterator.211] passed iterators may not belong to container\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","title":"json.exception.invalid_iterator.212","text":"When two iterators are compared, they must belong to the same container.
Example message
[json.exception.invalid_iterator.212] cannot compare iterators of different containers\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","title":"json.exception.invalid_iterator.213","text":"The order of object iterators cannot be compared, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.213] cannot compare order of object iterators\n"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","title":"json.exception.invalid_iterator.214","text":"Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin().
Example message
[json.exception.invalid_iterator.214] cannot get value\n"},{"location":"home/exceptions/#type-errors","title":"Type errors","text":"This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx.
ExampleThe following code shows how a type_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling push_back() on a string value\n json j = \"string\";\n j.push_back(\"another string\");\n }\n catch (const json::type_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.type_error.308] cannot use push_back() with string\nexception id: 308\n"},{"location":"home/exceptions/#jsonexceptiontype_error301","title":"json.exception.type_error.301","text":"To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
Example message
[json.exception.type_error.301] cannot create object from initializer list\n"},{"location":"home/exceptions/#jsonexceptiontype_error302","title":"json.exception.type_error.302","text":"During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
Example messages
[json.exception.type_error.302] type must be object, but is null\n [json.exception.type_error.302] type must be string, but is object\n"},{"location":"home/exceptions/#jsonexceptiontype_error303","title":"json.exception.type_error.303","text":"To retrieve a reference to a value stored in a basic_json object with get_ref, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t &.
Example messages
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object\n [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"\n"},{"location":"home/exceptions/#jsonexceptiontype_error304","title":"json.exception.type_error.304","text":"The at() member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.304] cannot use at() with string\n [json.exception.type_error.304] cannot use at() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error305","title":"json.exception.type_error.305","text":"The operator[] member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.305] cannot use operator[] with a string argument with array\n [json.exception.type_error.305] cannot use operator[] with a numeric argument with object\n"},{"location":"home/exceptions/#jsonexceptiontype_error306","title":"json.exception.type_error.306","text":"The value() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.306] cannot use value() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error307","title":"json.exception.type_error.307","text":"The erase() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.307] cannot use erase() with string\n"},{"location":"home/exceptions/#jsonexceptiontype_error308","title":"json.exception.type_error.308","text":"The push_back() and operator+= member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.308] cannot use push_back() with string\n"},{"location":"home/exceptions/#jsonexceptiontype_error309","title":"json.exception.type_error.309","text":"The insert() member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.309] cannot use insert() with array\n [json.exception.type_error.309] cannot use insert() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error310","title":"json.exception.type_error.310","text":"The swap() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.310] cannot use swap() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error311","title":"json.exception.type_error.311","text":"The emplace() and emplace_back() member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.311] cannot use emplace() with number\n [json.exception.type_error.311] cannot use emplace_back() with number\n"},{"location":"home/exceptions/#jsonexceptiontype_error312","title":"json.exception.type_error.312","text":"The update() member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.312] cannot use update() with array\n"},{"location":"home/exceptions/#jsonexceptiontype_error313","title":"json.exception.type_error.313","text":"The unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined.
Example message
[json.exception.type_error.313] invalid value to unflatten\n"},{"location":"home/exceptions/#jsonexceptiontype_error314","title":"json.exception.type_error.314","text":"The unflatten function only works for an object whose keys are JSON Pointers.
Example message
Calling unflatten() on an array [1,2,3]:
[json.exception.type_error.314] only objects can be unflattened\n"},{"location":"home/exceptions/#jsonexceptiontype_error315","title":"json.exception.type_error.315","text":"The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive.
Example message
Calling unflatten() on an object {\"/1\", [1,2,3]}:
[json.exception.type_error.315] values in object must be primitive\n"},{"location":"home/exceptions/#jsonexceptiontype_error316","title":"json.exception.type_error.316","text":"The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded.
Example message
Calling dump() on a JSON value containing an ISO 8859-1 encoded string:
[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F\n Tip
dump() function to avoid this exception:json::error_handler_t::replace will replace invalid bytes sequences with U+FFFD json::error_handler_t::ignore will silently ignore invalid byte sequencesThe dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON)
Example messages
Serializing null to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n Serializing [1,2,3] to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n Tip
Encapsulate the JSON value in an object. That is, instead of serializing true, serialize {\"value\": true}
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx.
ExampleThe following code shows how an out_of_range exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n try\n {\n // calling at() for an invalid index\n json j = {1, 2, 3, 4};\n j.at(4) = 10;\n }\n catch (const json::out_of_range& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.out_of_range.401] array index 4 is out of range\nexception id: 401\n"},{"location":"home/exceptions/#jsonexceptionout_of_range401","title":"json.exception.out_of_range.401","text":"The provided array index i is larger than size-1.
Example message
array index 3 is out of range\n"},{"location":"home/exceptions/#jsonexceptionout_of_range402","title":"json.exception.out_of_range.402","text":"The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
Example message
array index '-' (3) is out of range\n"},{"location":"home/exceptions/#jsonexceptionout_of_range403","title":"json.exception.out_of_range.403","text":"The provided key was not found in the JSON object.
Example message
key 'foo' not found\n"},{"location":"home/exceptions/#jsonexceptionout_of_range404","title":"json.exception.out_of_range.404","text":"A reference token in a JSON Pointer could not be resolved.
Example message
unresolved reference token 'foo'\n"},{"location":"home/exceptions/#jsonexceptionout_of_range405","title":"json.exception.out_of_range.405","text":"The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
Example message
JSON pointer has no parent\n"},{"location":"home/exceptions/#jsonexceptionout_of_range406","title":"json.exception.out_of_range.406","text":"A parsed number could not be stored as without changing it to NaN or INF.
Example message
number overflow parsing '10E1000'\n"},{"location":"home/exceptions/#jsonexceptionout_of_range407","title":"json.exception.out_of_range.407","text":"UBJSON and BSON only support integer numbers up to 9223372036854775807.
Example message
number overflow serializing '9223372036854775808'\n Note
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.
"},{"location":"home/exceptions/#jsonexceptionout_of_range408","title":"json.exception.out_of_range.408","text":"The size (following #) of an UBJSON array or object exceeds the maximal capacity.
Example message
excessive array size: 8658170730974374167\n"},{"location":"home/exceptions/#jsonexceptionout_of_range409","title":"json.exception.out_of_range.409","text":"Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.
Example message
BSON key cannot contain code point U+0000 (at byte 2)\n"},{"location":"home/exceptions/#further-exceptions","title":"Further exceptions","text":"This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx.
ExampleThe following code shows how an other_error exception can be caught.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n try\n {\n // executing a failing JSON Patch operation\n json value = R\"({\n \"best_biscuit\": {\n \"name\": \"Oreo\"\n }\n })\"_json;\n json patch = R\"([{\n \"op\": \"test\",\n \"path\": \"/best_biscuit/name\",\n \"value\": \"Choco Leibniz\"\n }])\"_json;\n value.patch(patch);\n }\n catch (const json::other_error& e)\n {\n // output exception information\n std::cout << \"message: \" << e.what() << '\\n'\n << \"exception id: \" << e.id << std::endl;\n }\n}\n Output:
message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"}\nexception id: 501\n"},{"location":"home/exceptions/#jsonexceptionother_error501","title":"json.exception.other_error.501","text":"A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
Example message
Executing {\"op\":\"test\", \"path\":\"/baz\", \"value\":\"bar\"} on {\"baz\": \"qux\"}:
[json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}\n"},{"location":"home/faq/","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"home/faq/#known-bugs","title":"Known bugs","text":""},{"location":"home/faq/#brace-initialization-yields-arrays","title":"Brace initialization yields arrays","text":"Question
Why does
json j{true};\n and
json j(true);\n yield different results ([true] vs. true)?
This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like
json array = {1, 2, 3, 4};\n for arrays and
json object = {{\"one\", 1}, {\"two\", 2}}; \n for objects.
Tip
To avoid any confusion and ensure portable code, do not use brace initialization with the types basic_json, json, or ordered_json unless you want to create an object or array as shown in the examples above.
Question
Can you add an option to ignore trailing commas?
This library does not support any feature which would jeopardize interoperability.
"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","title":"Parse errors reading non-ASCII characters","text":"Questions
[json.exception.parse_error.101] parse error at line 1, column 53: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '\"Test\u00e9$')\"The library supports Unicode input as follows:
std::u16string and std::u32string can be parsed, assuming UTF-16 and UTF-32 encoding, respectively. These encodings are not supported when reading from files or other input containers.\\uDEAD) will yield parse errors.std::string), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.dump() may throw an exception unless json::error_handler_t::replace or json::error_handler_t::ignore are used as error handlers.In most cases, the parser is right to complain, because the input is not UTF-8 encoded. This is especially true for Microsoft Windows where Latin-1 or ISO 8859-1 is often the standard encoding.
"},{"location":"home/faq/#wide-string-handling","title":"Wide string handling","text":"Question
Why are wide strings (e.g., std::wstring) dumped as arrays of numbers?
As described above, the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding.
Example
#include <codecvt> // codecvt_utf8\n#include <locale> // wstring_convert\n\n// encoding function\nstd::string to_utf8(std::wstring& wide_string)\n{\n static std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;\n return utf8_conv.to_bytes(wide_string);\n}\n\njson j;\nstd::wstring ws = L\"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\";\n\nj[\"original\"] = ws;\nj[\"encoded\"] = to_utf8(ws);\n\nstd::cout << j << std::endl;\n The result is:
{\n \"encoded\": \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\",\n \"original\": [36554, 66, 49, 50, 51, 52, 32, 12371, 12435, 12395, 12385, 12399]\n}\n"},{"location":"home/faq/#exceptions","title":"Exceptions","text":""},{"location":"home/faq/#parsing-without-exceptions","title":"Parsing without exceptions","text":"Question
Is it possible to indicate a parse error without throwing an exception?
Yes, see Parsing and exceptions.
"},{"location":"home/faq/#key-name-in-exceptions","title":"Key name in exceptions","text":"Question
Can I get the key of the object item that caused an exception?
Yes, you can. Please define the symbol JSON_DIAGNOSTICS to get extended diagnostics messages.
Question
The library uses std::numeric_limits<number_float_t>::digits10 (15 for IEEE doubles) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip.
cppreference.com
The value of std::numeric_limits<T>::digits10 is the number of base-10 digits that can be represented by the type T without change, that is, any number with this many significant decimal digits can be converted to a value of type T and back to decimal form, without change due to rounding or overflow.
Tip
The website https://float.exposed gives a good insight into the internal storage of floating-point numbers.
See this section on the library's number handling for more information.
"},{"location":"home/faq/#compilation-issues","title":"Compilation issues","text":""},{"location":"home/faq/#android-sdk","title":"Android SDK","text":"Question
Why does the code not compile with Android SDK?
Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.
APP_STL := c++_shared\nNDK_TOOLCHAIN_VERSION := clang3.6\nAPP_CPPFLAGS += -frtti -fexceptions\n The code compiles successfully with Android NDK, Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.
"},{"location":"home/faq/#missing-stl-function","title":"Missing STL function","text":"Questions
'to_string' is not a member of 'std' (or similarly, for strtod or strtof)?This is not an issue with the code, but rather with the compiler itself. On Android, see above to build with a newer environment. For MinGW, please refer to this site and this discussion for information on how to fix this bug. For Android NDK using APP_STL := gnustl_static, please refer to this discussion.
The class is licensed under the MIT License:
Copyright \u00a9 2013-2024 Niels Lohmann
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de
The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch
The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0.
"},{"location":"home/releases/","title":"Releases","text":""},{"location":"home/releases/#v373","title":"v3.7.3","text":"Files
Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)
"},{"location":"home/releases/#summary","title":"Summary","text":"This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes","title":"Bug Fixes","text":"reserve() calls from the destructor which could lead to quadratic complexity. #1837 #1838This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)
"},{"location":"home/releases/#summary_1","title":"Summary","text":"Project bad_json_parsers tested how JSON parser libraries react on deeply nested inputs. It turns out that this library segfaulted at a certain nesting depth. This bug was fixed with this release. Now the parsing is only bounded by the available memory. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_1","title":"Bug Fixes","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)
"},{"location":"home/releases/#summary_2","title":"Summary","text":"This release fixes several small bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_2","title":"Bug Fixes","text":"std::int64_t minimum value. #1708 #1722contains() function for JSON Pointers. #1727 #1741std::pair and std::tuple to json. #1805 #1806 #1825 #1826iteration_proxy. #1797json to std::valarray.items() function can now be used with a custom string type. #1765json_pointer::back const. #1764 #1769ubuntu-latest/GCC 7.4.0 as CI step.JSON_THROW_USER, JSON_TRY_USER, and JSON_CATCH_USER macros to control user-defined exception handling.GLOB from CMake files. #1779This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)
"},{"location":"home/releases/#summary_3","title":"Summary","text":"This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.
"},{"location":"home/releases/#new-features","title":"New Features","text":"contains function to check if a JSON pointer is valid without throwing exceptions, just like its counterpart for object keys. #1600to_string to allow for generic conversion to strings. #916 #1585emplace_back function, returning a reference to the added element just like C++17 is introducing this for std::vector. #1609std::string_view in the unit tests. #1634 #1639get_to method to clear existing content before writing. #1511 #1555-Wc++17-extensions warning. nodiscard attributes are now only used with Clang when -std=c++17 is used. #1535 #1551GNUInstallDirs to set library install directories. #1673json type on the documentation start page. #1616value() function with respect to type_error.302 exception. #1601JSON_BuildTests, JSON_Install, JSON_MultipleHeaders, JSON_Sanitizer, JSON_Valgrind, JSON_NoExceptions, JSON_Coverage).JSON_DEPRECATED, JSON_NODISCARD, JSON_LIKELY, JSON_UNLIKELY, JSON_HAS_CPP_14, or JSON_HAS_CPP_17. Functions taking or returning pointers are annotated accordingly when a pointer will not be null.This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)
"},{"location":"home/releases/#summary_4","title":"Summary","text":"This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_4","title":"Bug Fixes","text":"<Windows.h> was included. #1531This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip)
\u2139\ufe0f This release introduced a regression. Please update to version 3.6.1!
"},{"location":"home/releases/#summary_5","title":"Summary","text":"This release adds some convenience functions for JSON Pointers, introduces a contains function to check if a key is present in an object, and improves the performance of integer serialization. Furthermore, a lot of small bug fixes and improvements have been made. All changes are backward-compatible.
operator/ and operator/=. JSON Pointers can be inspected with empty, back, and parent_pointer, and manipulated with push_back and pop_back. #1434contains to check whether an element exists in a JSON object with a given key. Returns false when called on non-object types. #1471 #1474JSON_Install to control whether the library should be installed (default: on). #1330nodiscard attribute to meta(), array(), object(), from_cbor, from_msgpack, from_ubjson, from_bson, and parse. #1433This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)
"},{"location":"home/releases/#summary_6","title":"Summary","text":"This release introduces the support for structured bindings and reading from FILE*. Besides, a few bugs have been fixed. All changes are backward-compatible.
Structured bindings are now supported for JSON objects and arrays via the items() member function, so finally this code is possible:
for (auto& [key, val] : j.items()) {\n std::cout << key << ':' << val << '\\n';\n}\n #1388 #1391 Added support for reading from FILE* to support situations in which streams are nit available or would require too much RAM. #1370 #1392
eofbit was not set for input streams when the end of a stream was reached while parsing. #1340 #1343-Wshadow warning #1346std::snprintf calls to avoid error in MSVC. #1337This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)
"},{"location":"home/releases/#summary_7","title":"Summary","text":"This release introduces three new features:
Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_3","title":"New Features","text":"dump function for examples. #1198 #1314NLOHMANN_JSON_SERIALIZE_ENUM has been introduced. See the README section for more information. #1208 #1323parse error at 2: syntax error - invalid string: control character must be escaped; last read: '<U+0009>' is now reported as parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t; last read: '<U+0009>'. #1280 #1288 #1303This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)
"},{"location":"home/releases/#summary_8","title":"Summary","text":"This release adds support for GCC 4.8. Furthermore, it adds a function get_to to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented.
Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_4","title":"New Features","text":"get_to to write a JSON value to a passed reference. The destination type is automatically derived which allows more succinct code compared to the get function. #1227 #1231target_link_libraries to not properly include nlohmann_json. #1243 #1245 #1260-Wctor-dtor-privacy warning. #1224JSON_CATCH_USER led to duplicate macro definition of JSON_INTERNAL_CATCH. #1213 #1214find_package(nlohmann_json) without installing the library. #1202operator[] is used with the wrong combination (json.exception.type_error.305) of JSON container type and argument type. Example: \"cannot use operator[] with a string argument\". #1220 #1221to_json or from_json functions as such assertions do not play well with SFINAE. These assertions also led to problems with GMock. #960 #1212 #1228This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)
"},{"location":"home/releases/#summary_9","title":"Summary","text":"This release introduces a SAX interface to the library. While this may be a very special feature used by only few people, it allowed to unify all functions that consumed input and created some kind of JSON value. Internally, now all existing functions like parse, accept, from_cbor, from_msgpack, and from_ubjson use the SAX interface with different event processors. This allowed to separate the input processing from the value generation. Furthermore, throwing an exception in case of a parse error is now optional and up to the event processor. Finally, the JSON parser is now non-recursive (meaning it does not use the call stack, but std::vector<bool> to track the hierarchy of structured values) which allows to process nested input more efficiently.
Furthermore, the library finally is able to parse from wide string types. This is the first step toward opening the library from UTF-8 to UTF-16 and UTF-32.
This release further fixes several bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_5","title":"New Features","text":"std::wstring, std::u16string, and std::u32string; the input will be converted to UTF-8 (#1031)std::string_view when using C++17 (#1028)std::map and std::unordered_map from JSON if key type is not convertible to string; in these cases, values are serialized to arrays of pairs (#1079, #1089, #1133, #1138)nullptr_t from JSON allowing to properly roundtrip null values (#1169)items() (#1045, #1134)std::swap (#1168)key() function for iterators returns a const reference rather than a string copy (#1098)float as type for floating-point numbers (#1021)JSON_SKIP_UNSUPPORTED_COMPILER_CHECK can skip the rejection of unsupported compilers - use at your own risk! (#1128)JSON_INTERNAL_CATCH/JSON_INTERNAL_CATCH_USER allows to control the behavior of exception handling inside the library (#1187)char to JSON conversionstd::stringstream (#1117)This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)
"},{"location":"home/releases/#summary_10","title":"Summary","text":"This release fixes several bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_10","title":"Bug Fixes","text":"basic_json (e.g., using different template arguments for strings or objects) can now be used in assignments (#972, #977, #986).make clang_analyze.This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)
"},{"location":"home/releases/#summary_11","title":"Summary","text":"This release fixes several bugs in the library. All changes are backward-compatible.
"},{"location":"home/releases/#bug-fixes_11","title":"Bug Fixes","text":"0x7F start byte.null elements with a few bytes and the library did not check whether this size exceeded max_size().run_benchmarks was added to quickly build and run the benchmark suite.#include <nlohmann/json.hpp> to allow for selecting single_include or include or whatever installation folder as include directory.This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0):
iterator_wrapper are deprecated. Please use the member function items() instead.friend std::istream& operator<<(basic_json&, std::istream&) and friend std::ostream& operator>>(const basic_json&, std::ostream&) are deprecated. Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.Files
Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)
"},{"location":"home/releases/#summary_12","title":"Summary","text":"This release adds support for the UBJSON format and JSON Merge Patch. It also contains some minor changes and bug fixes. All changes are backward-compatible.
"},{"location":"home/releases/#new-features_6","title":"New features","text":"merge_patch for more information.json.hpp can be generated from these development sources. In the repository, folder include contains the development sources and single_include contains the single json.hpp header (#700, #906, #907, #910, #911, #915, #920, #924, #925, #928, #944).include/nlohmann/json_fwd.hpp to speed up compilation times (#314).benchmarks folder, #921).JSON_THROW_USER, JSON_TRY_USER, and JSON_CATCH_USER, defining the behavior of throw, try and catch, respectively. This allows to switch off C++'s exception mechanism yet still execute user-defined code in case an error condition occurs (#938).yytext any more as it could clash with macro definitions (#933).NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, and NLOHMANN_JSON_VERSION_PATCH to allow for conditional compilation based on the included library version (#943, #948).iterator_wrapper has been deprecated (#874). Since its introduction, the name was up for discussion, as it was too technical. We now introduced the member function items() with the same semantics. iterator_wrapper will be removed in the next major version (i.e., 4.0.0).Furthermore, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0):
friend std::istream& operator<<(basic_json&, std::istream&)friend std::ostream& operator>>(const basic_json&, std::ostream&)Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.
Files
Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c
"},{"location":"home/releases/#summary_13","title":"Summary","text":"This release fixes small issues in the implementation of JSON Pointer and JSON Patch. All changes are backward-compatible.
"},{"location":"home/releases/#changes","title":"Changes","text":"10e2 are used.at(ptr) function with JSON Pointers to list all possible exceptions (see #888).BUILD_TESTING option (see #846, #885)To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0):
friend std::istream& operator<<(basic_json&, std::istream&)friend std::ostream& operator>>(const basic_json&, std::ostream&)Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.
Files
Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462
"},{"location":"home/releases/#summary_14","title":"Summary","text":"After almost a year, here is finally a new release of JSON for Modern C++, and it is a major one! As we adhere to semantic versioning, this means the release includes some breaking changes, so please read the next section carefully before you update. But don't worry, we also added a few new features and put a lot of effort into fixing a lot of bugs and straighten out a few inconsistencies.
"},{"location":"home/releases/#breaking-changes","title":"Breaking changes","text":"This section describes changes that change the public API of the library and may require changes in code using a previous version of the library. In section \"Moving from 2.x.x to 3.0.0\" at the end of the release notes, we describe in detail how existing code needs to be changed.
<stdexcept> (#244). This not only allows to add more information to the exceptions (every exception now has an identifier, and parse errors contain the position of the error), but also to easily catch all library exceptions with a single catch(json::exception).json::type_error exception during serialization (#838). The check for valid UTF-8 is realized with code from Bj\u00f6rn Hoehrmann.null (#388).<iostream>, <ctype>, and <stdexcept> any more. You may need to add these headers to code relying on them.explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) which was deprecated in version 2.0.0 (#480).To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0):
friend std::istream& operator<<(basic_json&, std::istream&)friend std::ostream& operator>>(const basic_json&, std::ostream&)Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.
With all this breaking and deprecation out of the way, let's talk about features!
json::parse_error is thrown which contains a detailed message on the error, but also a member byte to indicate the byte offset in the input where the error occurred.accept function returns a Boolean indicating whether the input is proper JSON. We also added a Boolean parameter allow_exceptions to the existing parse functions to return a discarded value in case a syntax error occurs instead of throwing an exception.update function was added to merge two JSON objects (#428). In case you are wondering: the name was inspired by Python.insert function now also supports an iterator range to add elements to an object.dump now has two optional parameters ensure_ascii to escape all non-ASCII characters with \\uxxxx and an indent_char parameter to choose whether to indent with spaces or tabs (#654). std::pair and std::tuple (#563, #614), enum and enum class (#545), std::vector<bool> (#494). Fixed support for std::valarray (#702), std::array (#553), and std::map<std::string, std::string> (#600, #607).Furthermore, there have been a lot of changes under the hood:
__builtin_expect to optimize branch prediction as long as no error occurs.from_json or to_json function was not found for a user-defined type. We also added a debug visualizer nlohmann_json.natvis for better debugging in MSVC (#844).JSON_Coverage), compilation without exceptions (JSON_NoExceptions), LLVM sanitizers (JSON_Sanitizer), or execution with Valgrind (JSON_Valgrind).There are five different exceptions inheriting from json::exception:
json::parse_error for syntax errors (including the binary formats),json::invalid_iterator for errors related to iterators,json::type_error for errors where functions were called with the wrong JSON type,json::out_of_range for range errors, andjson::other_error for miscellaneous errors.To support these exception, the try/catch blocks of your code need to be adjusted:
If an overflow occurs during parsing a number from a JSON text, an exception json::out_of_range is thrown so that the overflow is detected early and roundtripping is guaranteed.
NaN and INF floating-point values can be stored in a JSON value and are not replaced by null. That is, the basic_json class behaves like double in this regard (no exception occurs). However, NaN and INF are serialized to null.
Function explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) should be replaced by the parse function: Let ss be a stream and cb be a parse callback function.
Old code:
json j(ss, cb);\n New code:
json j = json::parse(ss, cb);\n If no callback function is used, also the following code works:
json j;\nj << ss;\n or
json j;\nss >> j;\n"},{"location":"home/releases/#v211","title":"v2.1.1","text":"Files
Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57
"},{"location":"home/releases/#summary_15","title":"Summary","text":"This release fixes a locale-related bug in the parser. To do so, the whole number handling (lexer, parser, and also the serialization) have been overworked. Furthermore, a lot of small changes added up that were added to this release. All changes are backward-compatible.
"},{"location":"home/releases/#changes_1","title":"Changes","text":". as decimal separator (e.g., the Norwegian locale nb_NO.UTF-8) led to truncated number parsing or parse errors. The library now has been fixed to work with any locale. Note that . is still the only valid decimal separator for JSON input.1.0 were correctly parsed as floating-point number, but serialized as integer (1). Now, floating-point numbers correctly round trip.0123) could yield a buffer overflow. This is fixed now by detecting such errors directly by the lexer.0 led to a comparison with null. This is fixed now.-Weverything (well, it needs -Wno-documentation-unknown-command and -Wno-deprecated-declarations, but you get the point).UINT8_MAX which previously required defining a preprocessor macro for compilation.basic_json.Files
This release introduces a means to convert from/to user-defined types. The release is backwards compatible.
"},{"location":"home/releases/#changes_2","title":"Changes","text":"to_json and from_json. Then, a conversion is as simple as putting a = between variables. See the README for more information and examples.JSON_NOEXCEPTION or by passing -fno-exceptions to your compiler. In case the code would usually thrown an exception, abort() is now called.meta() which returns a JSON object with information on the version, compiler, and platform. See the documentation for an example.type_name() is now public. It allows to query the type of a JSON value as string.Files
This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_3","title":"Changes","text":"find() function to always return end() when called on non-object value types.test/thirdparty directory.Files
This release implements with CBOR and MessagePack two binary serialization/deserialization formats. It further contains some small fixes and improvements. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_4","title":"Changes","text":"-WdocumentationFiles
This release combines a lot of small fixes and improvements. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_5","title":"Changes","text":"std::invalid_argument is thrown)std::invalid_argument is thrown)emplace and emplace_back have been added to JSON values and work as expecteddump function)Files
This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible.
"},{"location":"home/releases/#changes_6","title":"Changes","text":"Files
This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible.
operator[] for JSON Pointers now behaves like the other versions of operator[] and transforms null values into objects or arrays if required. This allows to created nested structures like j[\"/foo/bar/2\"] = 17 (yielding {\"foo\": \"bar\": [null, null, 17]}) without problems.Files
This release fixes a regression bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.
Files
This release fixes a bug in the stream parser (function parse() and the <</>> operators). This fix is backwards compatible.
Files
This release combines a lot of small fixes and improvements. The release is backwards compatible.
"},{"location":"home/releases/#changes_10","title":"Changes","text":"char, unsigned char, uint8_t). This includes all kind of string representations (string literals, char arrays, std::string, const char*), contiguous containers (C-style arrays, std::vector, std::array, std::valarray, std::initializer_list). User-defined containers providing random-access iterator access via std::begin and std::end can be used as well. See the documentation (1, 2, 3, 4) for more information. Note that contiguous storage cannot be checked at compile time; if any of the parse functions are called with a noncompliant container, the behavior is undefined and will most likely yield segmentation violation. The preconditions are enforced by an assertion unless the library is compiled with preprocessor symbol NDEBUG.operator[] for const JSON objects. The behavior of this const version of the operator is undefined if the given key does not exist in the JSON object, because unlike the non-const version, it cannot add a null value at the given key. Assertions can be switched of by defining the preprocessor symbol NDEBUG. See the documentation of assert for more information.basic_json(std::istream&, const parser_callback_t) has been deprecated and will be deleted with the next major release 3.0.0 to unify the interface of the library. Deserialization will be done by stream operators or by calling one of the parse functions. That is, calls like json j(i); for an input stream i need to be replaced by json j = json::parse(i);. Compilers will produce a deprecation warning if client code uses this function./Wall now only warns about non-inlined functions (C4710) and the deprecation of the constructor from input-stream (C4996).make check.Files
This release combines a lot of small fixes and improvements. The release is backwards compatible.
"},{"location":"home/releases/#changes_11","title":"Changes","text":"\\x10-\\x1f are not accepted any more.NDEBUG, see the documentation of assert.#error command.get_ptr().sed.std::all_of, std::for_each, or std::accumulate. This facilitates reasoning about termination of loops and sometimes allowed to simplify functions to a single return statement.value() function for JSON pointers (similar to at function).std::cout in the test cases.Files
This release fixes a performance regression in the JSON serialization (function dump()). This fix is backwards compatible.
Files
This release adds several features such as JSON Pointers, JSON Patch, or support for 64 bit unsigned integers. Furthermore, several (subtle) bugs have been fixed.
As noexcept and constexpr specifier have been added to several functions, the public API has effectively been changed in a (potential) non-backwards compatible manner. As we adhere to Semantic Versioning, this calls for a new major version, so say hello to 2\ufe0f\u20e3.0\ufe0f\u20e3.0\ufe0f\u20e3.
uint64_t (default value for template parameter NumberUnsignedType) as data type for unsigned integer values. This type is used automatically when an unsigned number is parsed. Furthermore, constructors, conversion operators and an is_number_unsigned() test have been added.at() and operator[] functions. Furthermore, JSON values can be \u201cflattened\u201d to key/value pairs using flatten() where each key is a JSON Pointer. The original value can be restored by \u201cunflattening\u201d the flattened value using unflatten().diff(const basic_json&) and applied with patch(const basic_json&). Note the created patches use a rather primitive algorithm so far and leave room for improvement..) as decimal separator and ignores different settings from the locale.brew tap nlohmann/json && brew install nlohmann_json.std::istream (e.g., std::stringstream or std::ifstream).noexcept specifier to basic_json(boolean_t), basic_json(const number_integer_t), basic_json(const int), basic_json(const number_float_t), iterator functions (begin(), end(), etc.)0.0 (vs. -0.0) is preserved.std::move.re2c to version 0.16 to use a minimal DFAs for the lexer.is_number, etc.) and const value access constexpr.push_back and operator+= now work with key/value pairs passed as initializer list, e.g. j_object += {\"key\", 1}.CMakeLists.txt to make it easier to integrate the library into other projects.diff function is rather primitive and does not create minimal diffs.iteration_wrapper may change in the future and the function will be deprecated in the next release.Files
This release fixes several small bugs and adds functionality in a backwards-compatible manner. Compared to the last version (1.0.0), the following changes have been made:
"},{"location":"home/releases/#changes_14","title":"Changes","text":"assert is used, the assertions can be switched off by defining the preprocessor symbol NDEBUG during compilation. [#168]get_ref(). [#128, #184]operator[]) now works with all kind of string representations. [#171, #189]There are still known open issues (#178, #187) which will be fixed in version 2.0.0. However, these fixes will require a small API change and will not be entirely backwards-compatible.
"},{"location":"home/releases/#v100","title":"v1.0.0","text":"Files
This is the first official release. Compared to the prerelease version 1.0.0-rc1, only a few minor improvements have been made:
"},{"location":"home/releases/#changes_15","title":"Changes","text":"sprintf is no longer used.iterator_wrapper also works for const objects; note: the name may change!parse function now also works with type std::istream&&.value(key, default_value) returns either a copy of an object's element at the specified key or a given default value if no element with the key exists.You can sponsor this library at GitHub Sponsors.
"},{"location":"home/sponsors/#priority-sponsor","title":"Priority Sponsor","text":"Thanks everyone!
"},{"location":"integration/","title":"Header only","text":"json.hpp is the single required file in single_include/nlohmann or released here. You need to add
#include <nlohmann/json.hpp>\n\n// for convenience\nusing json = nlohmann::json;\n to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang).
You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.
You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags.
To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration:
Example
CMakeLists.txtcmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\nfind_package(nlohmann_json 3.11.3 REQUIRED)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.
To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.
Example
CMakeLists.txtcmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\n# If you only include this third party in PRIVATE source files, you do not need to install it\n# when your main project gets installed.\nset(JSON_Install OFF CACHE INTERNAL \"\")\n\nadd_subdirectory(nlohmann_json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n Note
Do not use include(nlohmann_json/CMakeLists.txt), since that carries with it unintended consequences that will break the build. It is generally discouraged (although not necessarily well documented as such) to use include(...) for pulling in other CMake projects anyways.
To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.
Example
CMakeLists.txtproject(ExampleProject LANGUAGES CXX)\n\noption(EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF)\n\nadd_subdirectory(thirdparty)\n\nadd_executable(example example.cpp)\n\n# Note that the namespaced target will always be available regardless of the import method\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n thirdparty/CMakeLists.txtif(EXAMPLE_USE_EXTERNAL_JSON)\n find_package(nlohmann_json 3.11.3 REQUIRED)\nelse()\n set(JSON_BuildTests OFF CACHE INTERNAL \"\")\n add_subdirectory(nlohmann_json)\nendif()\n thirdparty/nlohmann_json is then a complete copy of this source tree.
Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type.
Example
CMakeLists.txtcmake_minimum_required(VERSION 3.11)\nproject(ExampleProject LANGUAGES CXX)\n\ninclude(FetchContent)\n\nFetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)\nFetchContent_MakeAvailable(json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n Note
It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like
FetchContent_Declare(json\n GIT_REPOSITORY https://github.com/nlohmann/json\n GIT_TAG v3.11.3\n)\n However, the repository https://github.com/nlohmann/json download size is quite large.
"},{"location":"integration/cmake/#cmake-options","title":"CMake Options","text":""},{"location":"integration/cmake/#json_buildtests","title":"JSON_BuildTests","text":"Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option.
JSON_CI","text":"Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.
JSON_Diagnostics","text":"Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS. This option is OFF by default.
JSON_DisableEnumSerialization","text":"Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION. This option is OFF by default.
JSON_FastTests","text":"Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests.
JSON_GlobalUDLs","text":"Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS. This option is OFF by default.
JSON_ImplicitConversions","text":"Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS. This option is ON by default.
JSON_Install","text":"Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project.
JSON_MultipleHeaders","text":"Use non-amalgamated version of the library. This option is OFF by default.
JSON_SystemInclude","text":"Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default.
JSON_Valgrind","text":"Execute test suite with Valgrind. This option is OFF by default. Depends on JSON_BuildTests.
This page collects some guidelines on how to future-proof your code for future versions of this library.
"},{"location":"integration/migration_guide/#replace-deprecated-functions","title":"Replace deprecated functions","text":"The following functions have been deprecated and will be removed in the next major version (i.e., 4.0.0). All deprecations are annotated with HEDLEY_DEPRECATED_FOR to report which function to use instead.
Function friend std::istream& operator<<(basic_json&, std::istream&) is deprecated since 3.0.0. Please use friend std::istream& operator>>(std::istream&, basic_json&) instead.
nlohmann::json j;\nstd::stringstream ss(\"[1,2,3]\");\nj << ss;\n nlohmann::json j;\nstd::stringstream ss(\"[1,2,3]\");\nss >> j;\n Passing iterator pairs or pointer/length pairs to parsing functions (parse, accept, sax_parse, from_cbor, from_msgpack, from_ubjson, and from_bson via initializer lists is deprecated since 3.8.0. Instead, pass two iterators; for instance, call from_cbor(ptr, ptr+len) instead of from_cbor({ptr, len}).
const char* s = \"[1,2,3]\";\nbool ok = nlohmann::json::accept({s, s + std::strlen(s)});\n const char* s = \"[1,2,3]\";\nbool ok = nlohmann::json::accept(s, s + std::strlen(s));\n Comparing JSON Pointers with strings via operator== and operator!= is deprecated since 3.11.2. To compare a json_pointer p with a string s, convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!=.
nlohmann::json::json_pointer lhs(\"/foo/bar/1\");\nassert(lhs == \"/foo/bar/1\");\n nlohmann::json::json_pointer lhs(\"/foo/bar/1\");\nassert(lhs == nlohmann::json::json_pointer(\"/foo/bar/1\"));\n The implicit conversion from JSON Pointers to string (json_pointer::operator string_t) is deprecated since 3.11.0. Use json_pointer::to_string instead.
nlohmann::json::json_pointer ptr(\"/foo/bar/1\");\nstd::string s = ptr;\n nlohmann::json::json_pointer ptr(\"/foo/bar/1\");\nstd::string s = ptr.to_string();\n Passing a basic_json specialization as template parameter RefStringType to json_pointer is deprecated since 3.11.0. The string type can now be directly provided.
using my_json = nlohmann::basic_json<std::map, std::vector, my_string_type>;\nnlohmann::json_pointer<my_json> ptr(\"/foo/bar/1\");\n nlohmann::json_pointer<my_string_type> ptr(\"/foo/bar/1\");\n Thereby, nlohmann::my_json::json_pointer is an alias for nlohmann::json_pointer<my_string_type> and is always an alias to the json_pointer with the appropriate string type for all specializations of basic_json.
The function iterator_wrapper is deprecated since 3.1.0. Please use the member function items instead.
for (auto &x : nlohmann::json::iterator_wrapper(j))\n{\n std::cout << x.key() << \":\" << x.value() << std::endl;\n}\n for (auto &x : j.items())\n{\n std::cout << x.key() << \":\" << x.value() << std::endl;\n}\n Function friend std::ostream& operator>>(const basic_json&, std::ostream&) is deprecated since 3.0.0. Please use friend operator<<(std::ostream&, const basic_json&) instead.
j >> std::cout;\n std::cout << j;\n The legacy comparison behavior for discarded values is deprecated since 3.11.0. It is already disabled by default and can still be enabled by defining JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON to 1.
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1\n#include <nlohmann/json.hpp>\n #include <nlohmann/json.hpp>\n Implicit conversions via operator ValueType will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get, get_to, get_ref, or get_ptr.
nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n nlohmann::json j = \"Hello, world!\";\nstd::string s;\nj.get_to(s);\n You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
literals for UDLs","text":"The user-defined string literals operator\"\"_json and operator\"\"_json_pointer will be removed from the global namespace in the next major release of the library.
nlohmann::json j = \"[1,2,3]\"_json;\n using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.
The nlohmann namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use nlohmann as namespace or, when the exact version and configuration is relevant, use macro NLOHMANN_JSON_NAMESPACE to denote the namespace.
void to_json(nlohmann::json_abi_v3_11_2::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n void to_json(nlohmann::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n void to_json(NLOHMANN_JSON_NAMESPACE::json& j, const person& p)\n{\n j[\"age\"] = p.age;\n}\n"},{"location":"integration/migration_guide/#do-not-use-the-details-namespace","title":"Do not use the details namespace","text":"The details namespace is not part of the public API of the library and can change in any version without announcement. Do not rely on any function or type in the details namespace.
Throughout this page, we will describe how to compile the example file example.cpp below.
#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n When executed, this program should create output similar to
{\n \"compiler\": {\n \"c++\": \"201103\",\n \"family\": \"gcc\",\n \"version\": \"12.3.0\"\n },\n \"copyright\": \"(C) 2013-2022 Niels Lohmann\",\n \"name\": \"JSON for Modern C++\",\n \"platform\": \"apple\",\n \"url\": \"https://github.com/nlohmann/json\",\n \"version\": {\n \"major\": 3,\n \"minor\": 11,\n \"patch\": 3,\n \"string\": \"3.11.3\"\n }\n}\n"},{"location":"integration/package_managers/#homebrew","title":"Homebrew","text":"Summary
formula: nlohmann-json
--HEAD parameter)If you are using Homebrew, you can install the library with
brew install nlohmann-json\n The header can be used directly in your code or via CMake.
Example: Raw compilationCreate the following file:
example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Install the package:
brew install nlohmann-json\n Compile the code and pass the Homebrew prefix to the include path such that the library can be found:
c++ example.cpp -I$(brew --prefix nlohmann-json)/include -std=c++11 -o example\n Create the following files:
example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n Install the package:
brew install nlohmann-json\n Compile the code and pass the Homebrew prefix to CMake to find installed packages via find_package:
CMAKE_PREFIX_PATH=$(brew --prefix) cmake -S . -B build\ncmake --build build\n Summary
wrap: nlohmann_json
meson.build.If you are using the Meson Build System, add this source tree as a meson subproject. You may also use the include.zip published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB, or simply use
meson wrap install nlohmann_json\n Please see the Meson project for any issues regarding the packaging.
The provided meson.build can also be used as an alternative to CMake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly.
Create the following files:
meson.buildproject('json_example', 'cpp',\n version: '1.0',\n default_options: ['cpp_std=c++11']\n)\n\ndependency_json = dependency('nlohmann_json', required: true)\n\nexecutable('json_example',\n sources: ['example.cpp'],\n dependencies: [dependency_json],\n install: true\n)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Use the Meson WrapDB to fetch the nlohmann/json wrap:
mkdir subprojects\nmeson wrap install nlohmann_json\n Build:
meson setup build\nmeson compile -C build\n Summary
use http_archive, git_repository, or local_repository
WORKSPACE fileThis repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive, git_repository, or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g., via deps attribute).
Create the following files:
BUILDcc_binary(\n name = \"main\",\n srcs = [\"example.cpp\"],\n deps = [\"@nlohmann_json//:json\"],\n)\n WORKSPACEload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\nhttp_archive(\n name = \"nlohmann_json\",\n urls = [\"https://github.com/nlohmann/json/archive/refs/tags/v3.11.3.tar.gz\"],\n strip_prefix = \"json-3.11.3\",\n)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Build and run:
bazel build //:main\nbazel run //:main\n Summary
recipe: nlohmann_json
If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile's requires, where x.y.z is the release version you want to use.
Create the following files:
Conanfile.txt[requires]\nnlohmann_json/3.11.3\n\n[generators]\nCMakeToolchain\nCMakeDeps\n CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Call Conan:
conan install . --output-folder=build --build=missing\n Build:
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=\"conan_toolchain.cmake\" -DCMAKE_BUILD_TYPE=Release\ncmake --build build\n Summary
package: nlohmann-json
If you are using Spack to manage your dependencies, you can use the nlohmann-json package via
spack install nlohmann-json\n Please see the Spack project for any issues regarding the packaging.
ExampleCreate the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Install the library:
spack install nlohmann-json\n Load the environment for your Spack-installed packages:
spack load nlohmann-json\n Build the project with CMake:
cmake -S . -B build -DCMAKE_PREFIX_PATH=$(spack location -i nlohmann-json)\ncmake --build build\n Summary
package: nlohmann_json
If you are using Hunter on your project for external dependencies, then you can use the nlohmann_json package via
hunter_add_package(nlohmann_json)\n Please see the Hunter project for any issues regarding the packaging.
ExampleCreate the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\n\ninclude(\"cmake/HunterGate.cmake\")\nHunterGate(\n URL \"https://github.com/cpp-pm/hunter/archive/v0.23.297.tar.gz\"\n SHA1 \"3319fe6a3b08090df7df98dee75134d68e2ef5a3\"\n)\n\nproject(json_example)\n\nhunter_add_package(nlohmann_json)\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Download required files
mkdir cmake\nwget https://raw.githubusercontent.com/cpp-pm/gate/master/cmake/HunterGate.cmake -O cmake/HunterGate.cmake\n Build the project with CMake:
cmake -S . -B build\ncmake --build build\n If you are using Buckaroo, you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json. There is a demo repo here.
Warning
The module is outdated as the respective repository has not been updated in years.
"},{"location":"integration/package_managers/#vcpkg","title":"vcpkg","text":"Summary
package: nlohmann-json
If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with
vcpkg install nlohmann-json\n and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging.
ExampleCreate the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Install package:
vcpkg install nlohmann-json\n Build:
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake\ncmake --build build\n Summary
package: nlohmann/json
If you are using cget, you can install the latest master version with
cget install nlohmann/json\n A specific version can be installed with cget install nlohmann/json@v3.11.3. Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON).
Create the following files:
CMakeLists.txtcmake_minimum_required(VERSION 3.15)\nproject(json_example)\n\nfind_package(nlohmann_json CONFIG REQUIRED)\n\nadd_executable(json_example example.cpp)\ntarget_link_libraries(json_example PRIVATE nlohmann_json::nlohmann_json)\n example.cpp#include <nlohmann/json.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint main()\n{\n std::cout << std::setw(4) << json::meta() << std::endl;\n}\n Initialize cget
cget init\n Install the library
cget install nlohmann/json\n Build
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=cget/cget/cget.cmake\ncmake --build build\n If you are using CocoaPods, you can use the library by adding pod \"nlohmann_json\", '~>3.1.2' to your podfile (see an example). Please file issues here.
If you are using NuGet, you can use the package nlohmann.json. Please check this extensive description on how to use the package. Please file issues here.
"},{"location":"integration/package_managers/#conda","title":"Conda","text":"If you are using conda, you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json. Please file issues here.
If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages.
The package is updated automatically.
"},{"location":"integration/package_managers/#macports","title":"MacPorts","text":"If you are using MacPorts, execute sudo port install nlohmann-json to install the nlohmann-json package.
The package is updated automatically.
"},{"location":"integration/package_managers/#build2","title":"build2","text":"If you are using build2, you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository. In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints). If you are not familiar with using dependencies in build2, please read this introduction. Please file issues here if you experience problems with the packages.
The package is updated automatically.
"},{"location":"integration/package_managers/#wsjcpp","title":"wsjcpp","text":"If you are using wsjcpp, you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch.
wsjcpp reads directly from the GitHub repository and is always up-to-date.
"},{"location":"integration/package_managers/#cpmcmake","title":"CPM.cmake","text":"If you are using CPM.cmake, you can check this example. After adding CPM script to your project, implement the following snippet to your CMake:
CPMAddPackage(\"gh:nlohmann/json@3.11.3\")\n Example mkdir -p cmake\nwget -O cmake/CPM.cmake https://github.com/cpm-cmake/CPM.cmake/releases/latest/download/get_cpm.cmake\n cmake -S . -B build\ncmake --build build\n"},{"location":"integration/pkg-config/","title":"Pkg-config","text":"If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed:
pkg-config nlohmann_json --cflags\n Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config:
json = dependency('nlohmann_json', required: true)\n"}]}
\ No newline at end of file