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.
Warning
The module is outdated as the respective pod has not been updated in years.
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.
Warning
The package manager is outdated as the respective repository has not been updated in years.
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.
Warning
The module is outdated as the respective pod has not been updated in years.
\ No newline at end of file
diff --git a/search/search_index.json b/search/search_index.json
index ed7b948b6..3004a1689 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"JSON for Modern C++","text":""},{"location":"api/json/","title":"nlohmann::json","text":"
using json = basic_json<>;\n
This type is the default specialization of the basic_json class which uses the standard template types.
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":"
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;.
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:
This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS for details.
"},{"location":"api/operator_literal_json/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON object n (in) length of string s"},{"location":"api/operator_literal_json/#return-value","title":"Return value","text":"
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:
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":"
std::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)\n
Serialize the given JSON value j to the output stream o. The JSON value will be serialized using the dump member function.
The indentation of the output can be controlled with the member variable width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).
The indentation character can be controlled with the member variable fill of the output stream o. For instance, the manipulator std::setfill('\\\\t') sets indentation to use a tab character rather than the default space character.
Write a string representation of the given JSON pointer ptr to the output stream o. The string representation is obtained using the to_string member function.
"},{"location":"api/operator_ltlt/#parameters","title":"Parameters","text":"o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write"},{"location":"api/operator_ltlt/#return-value","title":"Return value","text":"
Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike the dump member functions, no error_handler can be set.
Function std::ostream& operator<<(std::ostream& o, const basic_json& j) replaces function std::ostream& operator>>(const basic_json& j, std::ostream& o) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o; with o << j;.
"},{"location":"api/operator_ltlt/#examples","title":"Examples","text":"Example: (1) serialize JSON value to stream
The example below shows the serialization with different parameters to width to adjust the indentation level.
Added in version 1.0.0. Added support for indentation character and deprecated std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.
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.
template<class Key, class T, class IgnoredLess = std::less<Key>,\n class Allocator = std::allocator<std::pair<const Key, T>>>\nstruct ordered_map : std::vector<std::pair<const Key, T>, Allocator>;\n
A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json (nlohmann::basic_json<ordered_map>).
"},{"location":"api/ordered_map/#template-parameters","title":"Template parameters","text":"Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std::map) Allocator allocator type"},{"location":"api/ordered_map/#iterator-invalidation","title":"Iterator invalidation","text":"
The type uses a std::vector to store object elements. Therefore, adding elements can yield a reallocation in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
This function is usually called by the get() function of the basic_json class (either explicitly or via the conversion operators).
This function is chosen for default-constructible value types.
This function is chosen for value types which are not default-constructible.
"},{"location":"api/adl_serializer/from_json/#parameters","title":"Parameters","text":"j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"
Copy of the JSON value, converted to ValueType
"},{"location":"api/adl_serializer/from_json/#examples","title":"Examples","text":"Example: (1) Default-constructible type
The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when template get<ns::person>() is called.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid from_json(const json& j, person& p)\n{\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n}\n} // namespace ns\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n
Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n
Example: (2) Non-default-constructible type
The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n
Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n
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.
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_tArrayType type for JSON arrays array_tStringType type for JSON strings and object keys string_tBooleanType type for JSON booleans boolean_tNumberIntegerType type for JSON integer numbers number_integer_tNumberUnsignedType type for JSON unsigned integer numbers number_unsigned_tNumberFloatType type for JSON floating-point numbers number_float_tAllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json()json_serializerBinaryType type for binary arrays binary_tCustomBaseClass extension point for user code json_base_class_t"},{"location":"api/basic_json/#specializations","title":"Specializations","text":"
json - default specialization
ordered_json - specialization that maintains the insertion order of object keys
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.
StandardLayoutType: JSON values have standard layout: All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes.
exception - general exception of the basic_json class
parse_error - exception indicating a parse error
invalid_iterator - exception indicating errors with iterators
type_error - exception indicating executing a member function with a wrong type
out_of_range - exception indicating access out of the defined range
other_error - exception indicating other library errors
"},{"location":"api/basic_json/#container-types","title":"Container types","text":"Type Definition value_typebasic_jsonreferencevalue_type&const_referenceconst value_type&difference_typestd::ptrdiff_tsize_typestd::size_tallocator_typeAllocatorType<basic_json>pointerstd::allocator_traits<allocator_type>::pointerconst_pointerstd::allocator_traits<allocator_type>::const_pointeriterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iteratorconst_reverse_iterator reverse iterator, derived from const_iteratoriteration_proxy helper type for items function"},{"location":"api/basic_json/#json-value-data-types","title":"JSON value data types","text":"
array_t - type for arrays
binary_t - type for binary arrays
boolean_t - type for booleans
default_object_comparator_t - default comparator for objects
number_float_t - type for numbers (floating-point)
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.
a pointer to a null-terminated string of single byte characters (throws if null)
a std::string
an object obj for which begin(obj) and end(obj) produces a valid pair of iterators.
IteratorType
a compatible iterator type, for instance.
a pair of std::string::iterator or std::vector<std::uint8_t>::iterator
a pair of pointers such as ptr and ptr + len
"},{"location":"api/basic_json/accept/#parameters","title":"Parameters","text":"i (in) Input to parse from. ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"
Ignoring comments via ignore_comments added in version 3.9.0.
Changed runtime assertion in case of 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.
Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.
"},{"location":"api/basic_json/array/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an array from (optional)"},{"location":"api/basic_json/array/#return-value","title":"Return value","text":"
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:
creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys
creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n
The type used to store JSON arrays.
RFC 8259 describes JSON arrays as follows:
An array is an ordered sequence of zero or more values.
To store objects in C++, a type is defined by the template parameters explained below.
"},{"location":"api/basic_json/array_t/#template-parameters","title":"Template parameters","text":"ArrayType container type to store arrays (e.g., std::vector or std::list) AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/array_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/array_t/#default-type","title":"Default type","text":"
With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:
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.
Returns a reference to the array element at specified location idx, with bounds checking.
Returns a reference to the object element with specified key key, with bounds checking.
See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
Returns a reference to the element at specified JSON pointer ptr, with bounds checking.
"},{"location":"api/basic_json/at/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/at/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the elements to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/at/#return-value","title":"Return value","text":"
Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.
Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.
The function can throw the following exceptions:
Throws type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.
Throws out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.
See 2.
The function can throw the following exceptions:
Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.
Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.
Throws out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.
Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.
Throws out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.
Throws out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.
"},{"location":"api/basic_json/at/#examples","title":"Examples","text":"Example: (1) access specified array element with bounds checking
The example below shows how array elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n\n // change element at index 1 (second element) to \"second\"\n array.at(1) = \"second\";\n\n // output changed array\n std::cout << array << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-array type\n json str = \"I am a string\";\n str.at(0) = \"Another string\";\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to write beyond the array limit\n array.at(5) = \"sixth\";\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n
Output:
\"third\"\n[\"first\",\"second\",\"third\",\"fourth\"]\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n
Example: (1) access specified array element with bounds checking
The example below shows how array elements can be read using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-array type\n const json str = \"I am a string\";\n std::cout << str.at(0) << '\\n';\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to read beyond the array limit\n std::cout << array.at(5) << '\\n';\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n
Output:
\"third\"\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n
Example: (2) access specified object element with bounds checking
The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
\"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.
\"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
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.
Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:
Value type initial value null null boolean false string \"\" number 0 object {} array [] binary empty array
The postcondition of this constructor can be restored by calling clear().
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:
arrays: array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.
objects: object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.
strings: string_t, string literals, and all compatible string containers can be used.
numbers: number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.
boolean: boolean_t / bool can be used.
binary: binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type.
See the examples below.
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:
If the list is empty, an empty JSON object value {} is created.
If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values.
In all other cases, an array is created.
The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
The empty initializer list is written as {} which is exactly an empty JSON object.
C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object.
In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe.
With the rules described above, the following JSON values cannot be expressed by an initializer list:
the empty array ([]): use array(initializer_list_t) with an empty initializer list in this case
arrays whose elements satisfy rule 2: use array(initializer_list_t) with the same initializer list in this case
Function array() and object() force array and object creation from initializer lists, respectively.
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:
In case of a null type, invalid_iterator.206 is thrown.
In case of other primitive types (number, boolean, or string), first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.
In case of structured types (array, object), the constructor behaves as similar versions for std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.
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 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&&) method
BasicJsonType:
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":"
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
No-throw guarantee: this constructor never throws exceptions.
Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
No-throw guarantee: this constructor never throws exceptions.
Throws type_error.301 if type_deduction is false, manual_type is value_t::object, but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.
(none)
The function can throw the following exceptions:
Throws invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.
Throws invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.
Throws invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.
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
Iterators first and last must be initialized. **This precondition is enforced with a runtime assertion.
Range [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 value
"},{"location":"api/basic_json/basic_json/#examples","title":"Examples","text":"Example: (1) create an empty value with a given type
The following code shows the constructor for different value_t values.
Example: (3) create a JSON value from compatible types
The following code shows the constructor with several compatible types.
#include <iostream>\n#include <deque>\n#include <list>\n#include <forward_list>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <valarray>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // ============\n // object types\n // ============\n\n // create an object from an object_t value\n json::object_t object_value = { {\"one\", 1}, {\"two\", 2} };\n json j_object_t(object_value);\n\n // create an object from std::map\n std::map<std::string, int> c_map\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 3}\n };\n json j_map(c_map);\n\n // create an object from std::unordered_map\n std::unordered_map<const char*, double> c_umap\n {\n {\"one\", 1.2}, {\"two\", 2.3}, {\"three\", 3.4}\n };\n json j_umap(c_umap);\n\n // create an object from std::multimap\n std::multimap<std::string, bool> c_mmap\n {\n {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n };\n json j_mmap(c_mmap); // only one entry for key \"three\" is used\n\n // create an object from std::unordered_multimap\n std::unordered_multimap<std::string, bool> c_ummap\n {\n {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n };\n json j_ummap(c_ummap); // only one entry for key \"three\" is used\n\n // serialize the JSON objects\n std::cout << j_object_t << '\\n';\n std::cout << j_map << '\\n';\n std::cout << j_umap << '\\n';\n std::cout << j_mmap << '\\n';\n std::cout << j_ummap << \"\\n\\n\";\n\n // ===========\n // array types\n // ===========\n\n // create an array from an array_t value\n json::array_t array_value = {\"one\", \"two\", 3, 4.5, false};\n json j_array_t(array_value);\n\n // create an array from std::vector\n std::vector<int> c_vector {1, 2, 3, 4};\n json j_vec(c_vector);\n\n // create an array from std::valarray\n std::valarray<short> c_valarray {10, 9, 8, 7};\n json j_valarray(c_valarray);\n\n // create an array from std::deque\n std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};\n json j_deque(c_deque);\n\n // create an array from std::list\n std::list<bool> c_list {true, true, false, true};\n json j_list(c_list);\n\n // create an array from std::forward_list\n std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};\n json j_flist(c_flist);\n\n // create an array from std::array\n std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};\n json j_array(c_array);\n\n // create an array from std::set\n std::set<std::string> c_set {\"one\", \"two\", \"three\", \"four\", \"one\"};\n json j_set(c_set); // only one entry for \"one\" is used\n\n // create an array from std::unordered_set\n std::unordered_set<std::string> c_uset {\"one\", \"two\", \"three\", \"four\", \"one\"};\n json j_uset(c_uset); // only one entry for \"one\" is used\n\n // create an array from std::multiset\n std::multiset<std::string> c_mset {\"one\", \"two\", \"one\", \"four\"};\n json j_mset(c_mset); // both entries for \"one\" are used\n\n // create an array from std::unordered_multiset\n std::unordered_multiset<std::string> c_umset {\"one\", \"two\", \"one\", \"four\"};\n json j_umset(c_umset); // both entries for \"one\" are used\n\n // serialize the JSON arrays\n std::cout << j_array_t << '\\n';\n std::cout << j_vec << '\\n';\n std::cout << j_valarray << '\\n';\n std::cout << j_deque << '\\n';\n std::cout << j_list << '\\n';\n std::cout << j_flist << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_set << '\\n';\n std::cout << j_uset << '\\n';\n std::cout << j_mset << '\\n';\n std::cout << j_umset << \"\\n\\n\";\n\n // ============\n // string types\n // ============\n\n // create string from a string_t value\n json::string_t string_value = \"The quick brown fox jumps over the lazy dog.\";\n json j_string_t(string_value);\n\n // create a JSON string directly from a string literal\n json j_string_literal(\"The quick brown fox jumps over the lazy dog.\");\n\n // create string from std::string\n std::string s_stdstring = \"The quick brown fox jumps over the lazy dog.\";\n json j_stdstring(s_stdstring);\n\n // serialize the JSON strings\n std::cout << j_string_t << '\\n';\n std::cout << j_string_literal << '\\n';\n std::cout << j_stdstring << \"\\n\\n\";\n\n // ============\n // number types\n // ============\n\n // create a JSON number from number_integer_t\n json::number_integer_t value_integer_t = -42;\n json j_integer_t(value_integer_t);\n\n // create a JSON number from number_unsigned_t\n json::number_integer_t value_unsigned_t = 17;\n json j_unsigned_t(value_unsigned_t);\n\n // create a JSON number from an anonymous enum\n enum { enum_value = 17 };\n json j_enum(enum_value);\n\n // create values of different integer types\n short n_short = 42;\n int n_int = -23;\n long n_long = 1024;\n int_least32_t n_int_least32_t = -17;\n uint8_t n_uint8_t = 8;\n\n // create (integer) JSON numbers\n json j_short(n_short);\n json j_int(n_int);\n json j_long(n_long);\n json j_int_least32_t(n_int_least32_t);\n json j_uint8_t(n_uint8_t);\n\n // create values of different floating-point types\n json::number_float_t v_ok = 3.141592653589793;\n json::number_float_t v_nan = NAN;\n json::number_float_t v_infinity = INFINITY;\n\n // create values of different floating-point types\n float n_float = 42.23;\n float n_float_nan = 1.0f / 0.0f;\n double n_double = 23.42;\n\n // create (floating point) JSON numbers\n json j_ok(v_ok);\n json j_nan(v_nan);\n json j_infinity(v_infinity);\n json j_float(n_float);\n json j_float_nan(n_float_nan);\n json j_double(n_double);\n\n // serialize the JSON numbers\n std::cout << j_integer_t << '\\n';\n std::cout << j_unsigned_t << '\\n';\n std::cout << j_enum << '\\n';\n std::cout << j_short << '\\n';\n std::cout << j_int << '\\n';\n std::cout << j_long << '\\n';\n std::cout << j_int_least32_t << '\\n';\n std::cout << j_uint8_t << '\\n';\n std::cout << j_ok << '\\n';\n std::cout << j_nan << '\\n';\n std::cout << j_infinity << '\\n';\n std::cout << j_float << '\\n';\n std::cout << j_float_nan << '\\n';\n std::cout << j_double << \"\\n\\n\";\n\n // =============\n // boolean types\n // =============\n\n // create boolean values\n json j_truth = true;\n json j_falsity = false;\n\n // serialize the JSON booleans\n std::cout << j_truth << '\\n';\n std::cout << j_falsity << '\\n';\n}\n
Output:
{\"one\":1,\"two\":2}\n{\"one\":1,\"three\":3,\"two\":2}\n{\"one\":1.2,\"three\":3.4,\"two\":2.3}\n{\"one\":true,\"three\":false,\"two\":true}\n{\"one\":true,\"three\":false,\"two\":true}\n\n[\"one\",\"two\",3,4.5,false]\n[1,2,3,4]\n[10,9,8,7]\n[1.2,2.3,3.4,5.6]\n[true,true,false,true]\n[12345678909876,23456789098765,34567890987654,45678909876543]\n[1,2,3,4]\n[\"four\",\"one\",\"three\",\"two\"]\n[\"four\",\"three\",\"two\",\"one\"]\n[\"four\",\"one\",\"one\",\"two\"]\n[\"four\",\"two\",\"one\",\"one\"]\n\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\n-42\n17\n17\n42\n-23\n1024\n-17\n8\n3.141592653589793\nnull\nnull\n42.22999954223633\nnull\n23.42\n\ntrue\nfalse\n
Note the output is platform-dependent.
Example: (5) create a container (array or object) from an initializer list
The example below shows how JSON values are created from initializer lists.
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
#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
Creates a JSON binary array value from a given binary container.
Creates a JSON binary array value from a given binary container with subtype.
Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"
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.
using binary_t = byte_container_with_subtype<BinaryType>;\n
This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
Additionally, as an implementation detail, the subtype of the binary data is carried around as a std::uint64_t, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to BinaryType via the helper type byte_container_with_subtype.
CBOR's RFC 7049 describes this type as:
Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).
MessagePack's documentation on the bin type family describes this type as:
Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.
BSON's specifications describe several binary types; however, this type is intended to represent the generic binary type which has the description:
Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.
None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.
The default representation of this binary format is a std::vector<std::uint8_t>, which is a very common way to represent a byte array in modern C++.
"},{"location":"api/basic_json/binary_t/#template-parameters","title":"Template parameters","text":"BinaryType container type to store arrays"},{"location":"api/basic_json/binary_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/binary_t/#default-type","title":"Default type","text":"
The default values for BinaryType is std::vector<std::uint8_t>.
Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t* must be dereferenced.
"},{"location":"api/basic_json/binary_t/#notes-on-subtypes","title":"Notes on subtypes","text":"
CBOR
Binary values are represented as byte strings. Subtypes are written as tags.
MessagePack
If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as signed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
BSON
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.
#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
enum class cbor_tag_handler_t\n{\n error,\n ignore,\n store\n};\n
This enumeration is used in the from_cbor function to choose how to treat tags:
error throw a parse_error exception in case of a tag ignore ignore tags store store tagged values as binary container with subtype (for bytes 0xd8..0xdb)"},{"location":"api/basic_json/cbor_tag_handler_t/#examples","title":"Examples","text":"Example
The example below shows how the different values of the cbor_tag_handler_t influence the behavior of from_cbor when reading a tagged byte string.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // 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
Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type():
Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array []
Check whether an element exists in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, false is returned.
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.
Check whether the given JSON pointer ptr can be resolved in the current JSON value.
"},{"location":"api/basic_json/contains/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/contains/#parameters","title":"Parameters","text":"key (in) key value to check its existence. ptr (in) JSON pointer to check its existence."},{"location":"api/basic_json/contains/#return-value","title":"Return value","text":"
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.
See 1.
true if the JSON pointer can be resolved to a stored value, false otherwise.
Returns the number of elements with key key. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/count/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/count/#parameters","title":"Parameters","text":"key (in) key value of the element to count."},{"location":"api/basic_json/count/#return-value","title":"Return value","text":"
Number of elements with key key. If the JSON value is not an object, the return value will be 0.
The following code shows an example for crbegin().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-beginning\n json::const_reverse_iterator it = array.crbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n
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.
#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
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":"
Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent and ensure_ascii parameters.
"},{"location":"api/basic_json/dump/#parameters","title":"Parameters","text":"indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are three possible values (see error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged))."},{"location":"api/basic_json/dump/#return-value","title":"Return value","text":"
string containing the serialization of the JSON value
Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.
"},{"location":"api/basic_json/emplace/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace/#iterator-invalidation","title":"Iterator invalidation","text":"
For ordered_json, adding a value to an object can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
"},{"location":"api/basic_json/emplace/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace/#return-value","title":"Return value","text":"
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.
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
Creates a JSON value from the passed parameters args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from args.
"},{"location":"api/basic_json/emplace_back/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace_back/#iterator-invalidation","title":"Iterator invalidation","text":"
By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise, only the end() iterator is invalidated.
"},{"location":"api/basic_json/emplace_back/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace_back/#return-value","title":"Return value","text":"
The return value depends on the different types and is defined as follows:
Value type return value null true boolean false string false number false binary false object result of function object_t::empty() array result of function array_t::empty()"},{"location":"api/basic_json/empty/#exception-safety","title":"Exception safety","text":"
No-throw guarantee: this function never throws exceptions.
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.
#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
Returns the position immediately following the last character of the JSON string from which the value was parsed from.
JSON type return value object position after the closing } array position after the closing ] string position after the closing \" number position after the last character boolean position after e null position after l"},{"location":"api/basic_json/end_pos/#return-value","title":"Return value","text":"
the position of the character following the last character of the given value in the parsed JSON string, if the value was created by the parse function, or std::string::npos if the value was constructed otherwise
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.
"},{"location":"api/basic_json/erase/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/erase/#parameters","title":"Parameters","text":"pos (in) iterator to the element to remove first (in) iterator to the beginning of the range to remove last (in) iterator past the end of the range to remove key (in) object key of the elements to remove idx (in) array index of the element to remove"},{"location":"api/basic_json/erase/#return-value","title":"Return value","text":"
Iterator following the last removed element. If the iterator pos refers to the last element, the end() iterator is returned.
Iterator following the last removed element. If the iterator last refers to the last element, the end() iterator is returned.
Number of elements removed. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: \"iterator out of range\"
The function can throw the following exceptions:
Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
Throws invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: \"iterators do not fit current value\"
Throws invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: \"iterators out of range\"
The function can throw the following exceptions:
Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
See 3.
The function can throw the following exceptions:
Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
Throws out_of_range.401 when idx >= size(); example: \"array index 17 is out of range\"
enum class error_handler_t {\n strict,\n replace,\n ignore\n};\n
This enumeration is used in the dump function to choose how to treat decoding errors while serializing a basic_json value. Three values are differentiated:
strict throw a type_error exception in case of invalid UTF-8 replace replace invalid UTF-8 sequences with U+FFFD (\ufffd REPLACEMENT CHARACTER) ignore ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged"},{"location":"api/basic_json/error_handler_t/#examples","title":"Examples","text":"Example
The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.
[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
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 error
invalid_iterator for exceptions indicating errors with iterators
type_error for exceptions indicating executing a member function with a wrong type
out_of_range for exceptions indicating access out of the defined range
other_error for exceptions indicating other library errors
To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.
Finds an element in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, end() is returned.
See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/find/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/find/#parameters","title":"Parameters","text":"key (in) key value of the element to search for."},{"location":"api/basic_json/find/#return-value","title":"Return value","text":"
Iterator to an element with a key equivalent to key. If no such element is found or the JSON value is not an object, a past-the-end iterator (see end()) is returned.
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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Changed to consume input adapters, removed start_index parameter, and added strict parameter in version 3.0.0.
Added allow_exceptions parameter in version 3.2.0.
Added tag_handler parameter in version 3.9.0.
Deprecation
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Changed to consume input adapters, removed start_index parameter, and added strict parameter in version 3.0.0.
Added allow_exceptions parameter in version 3.2.0.
Deprecation
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Added allow_exceptions parameter in version 3.2.0.
Deprecation
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
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.
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.
json_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)
If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.
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.
"},{"location":"api/basic_json/get/#template-parameters","title":"Template parameters","text":"ValueType the value type to return BasicJsonType a specialization of basic_jsonPointerType 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":"
copy of the JSON value, converted to ValueType
a copy of *this, converted into BasicJsonType
pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use explicit conversions\n auto v1 = json_types[\"boolean\"].template get<bool>();\n auto v2 = json_types[\"number\"][\"integer\"].template get<int>();\n auto v3 = json_types[\"number\"][\"integer\"].template get<short>();\n auto v4 = json_types[\"number\"][\"floating-point\"].template get<float>();\n auto v5 = json_types[\"number\"][\"floating-point\"].template get<int>();\n auto v6 = json_types[\"string\"].template get<std::string>();\n auto v7 = json_types[\"array\"].template get<std::vector<short>>();\n auto v8 = json_types.template get<std::unordered_map<std::string, json>>();\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n
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.
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
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.
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
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
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\".
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.
json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&)
"},{"location":"api/basic_json/get_to/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"
The 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
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.
"},{"location":"api/basic_json/insert/#parameters","title":"Parameters","text":"pos (in) iterator before which the content will be inserted; may be the end() iterator val (in) value to insert cnt (in) number of copies of val to insert first (in) begin of the range of elements to insert last (in) end of the range of elements to insert ilist (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"
iterator pointing to the inserted val.
iterator pointing to the first element inserted, or pos if cnt==0
iterator pointing to the first element inserted, or pos if first==last
iterator pointing to the first element inserted, or pos if ilist is empty
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
Throws invalid_iterator.211 if first or last are iterators into container for which insert is called; example: \"passed iterators may not belong to container\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than objects; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
Constant plus linear in the distance between pos and end of the container.
Linear in cnt plus linear in the distance between pos and end of the container.
Linear in std::distance(first, last) plus linear in the distance between pos and end of the container.
Linear in ilist.size() plus linear in the distance between pos and end of the container.
Logarithmic: O(N*log(size() + N)), where N is the number of elements to insert.
"},{"location":"api/basic_json/insert/#examples","title":"Examples","text":"Example (1): insert element into array
The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 10 before number 3\n auto new_pos = v.insert(v.begin() + 2, 10);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n
Output:
10\n[1,2,10,3,4]\n
Example (2): insert copies of element into array
The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 7 copies of number 7 before number 3\n auto new_pos = v.insert(v.begin() + 2, 7, 7);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n
Output:
7\n[1,2,7,7,7,7,7,7,7,3,4]\n
Example (3): insert range of elements into array
The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // create a JSON array to copy values from\n json v2 = {\"one\", \"two\", \"three\", \"four\"};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), v2.begin(), v2.end());\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n
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
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.
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.
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
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.
Added items and deprecated iterator_wrapper in version 3.1.0.
Added structured binding support in version 3.5.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.
"},{"location":"api/basic_json/json_base_class_t/#template-parameters","title":"Template parameters","text":"CustomBaseClass the base class to be added to basic_json"},{"location":"api/basic_json/json_base_class_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_base_class_t/#default-type","title":"Default type","text":"
The default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.
The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.
"},{"location":"api/basic_json/json_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
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 null 0 (same as size()) boolean 1 (same as size()) string 1 (same as size()) number 1 (same as size()) binary 1 (same as size()) object result of function object_t::max_size() array result of function array_t::max_size()"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"
No-throw guarantee: this function never throws exceptions.
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 merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):
define MergePatch(Target, Patch):\n if Patch is an Object:\n if Target is not an Object:\n Target = {} // Ignore the contents and set it to an empty Object\n for each Name/Value pair in Patch:\n if Value is null:\n if Name exists in Target:\n remove the Name/Value pair from Target\n else:\n Target[Name] = MergePatch(Target[Name], Value)\n return Target\n else:\n return Patch\n
Thereby, Target is the current object; that is, the patch is applied to the current value.
"},{"location":"api/basic_json/merge_patch/#parameters","title":"Parameters","text":"apply_patch (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"
key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown. url The URL of the project as string. version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal 01.2 will be serialized to 1.2. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.
"},{"location":"api/basic_json/object/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"
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.
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).
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:
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.
When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, {\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.
Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see 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}.
When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, {\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be treated as equal.
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.
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.
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
the current value is an object,
the initializer list init contains only two elements, and
the first element of init is a string,
init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).
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.
"},{"location":"api/basic_json/operator%2B%3D/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"
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\"
(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
"},{"location":"api/basic_json/operator%2B%3D/#examples","title":"Examples","text":"Example: (1) add element to array
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
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.
Copy assignment operator. Copies a JSON value via the \"copy and swap\" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function.
"},{"location":"api/basic_json/operator%3D/#parameters","title":"Parameters","text":"other (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"
The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json a = 23;\n json b = 42;\n\n // copy-assign a to b\n b = a;\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n
Returns a reference to the array element at specified location idx.
Returns a reference to the object element with specified key key. The non-const qualified overload takes the key by value.
See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
Returns a reference to the element with specified JSON pointer ptr.
"},{"location":"api/basic_json/operator%5B%5D/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#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.
"},{"location":"api/basic_json/operator%5B%5D/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the element to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"
(const) reference to the element at index idx
(const) reference to the element at key key
(const) reference to the element at key key
(const) reference to the element pointed to by ptr
If the element with key idx does not exist, the behavior is undefined.
If the element with key 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:
If the JSON pointer points to an object key that does not exist, it is created and filled with a null value before a reference to it is returned.
If the JSON pointer points to an array index that does not exist, it is created and filled with a null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.
The special value - is treated as a synonym for the index past the end.
"},{"location":"api/basic_json/operator%5B%5D/#examples","title":"Examples","text":"Example: (1) access specified array element
The example below shows how array elements can be read and written using [] operator. Note the addition of null values.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json array = {1, 2, 3, 4, 5};\n\n // output element at index 3 (fourth element)\n std::cout << array[3] << '\\n';\n\n // change last element to 6\n array[array.size() - 1] = 6;\n\n // output changed array\n std::cout << array << '\\n';\n\n // write beyond array limit\n array[10] = 11;\n\n // output changed array\n std::cout << array << '\\n';\n}\n
Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.
"},{"location":"api/basic_json/operator_ValueType/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"
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>.
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
Compares two JSON values for equality according to the following rules:
Two JSON values are equal if (1) neither value is discarded, or (2) they are of the same type and their stored values are the same according to their respective operator==.
Integer and floating-point numbers are automatically converted before comparison.
Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the scalar to a JSON value and comparing both JSON values according to 1.
"},{"location":"api/basic_json/operator_eq/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"
NaN values are unordered within the domain of numbers. The following comparisons all yield false:
Comparing a NaN with itself.
Comparing a NaN with another NaN.
Comparing a NaN and any other number.
JSON null values are all equal.
Discarded values never compare equal to themselves.
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:
Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(lhs < rhs) (see operator<).
Compares whether a JSON value is greater than or equal to a scalar or a scalar is greater than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
"},{"location":"api/basic_json/operator_ge/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"
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<=>.
Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(lhs <= rhs) (see operator<=).
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.
"},{"location":"api/basic_json/operator_gt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"
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<=>.
Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(rhs < lhs) (see operator<).
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.
"},{"location":"api/basic_json/operator_le/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"
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<=>.
Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:
If either operand is discarded, the comparison yields false.
If both operands have the same type, the values are compared using their respective operator<.
Integer and floating-point numbers are automatically converted before comparison.
In case lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:
null
boolean
number (all types)
object
array
string
binary For instance, any boolean value is considered less than any string.
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.
"},{"location":"api/basic_json/operator_lt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"
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<=>.
Compares two JSON values for inequality according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).
Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1.
"},{"location":"api/basic_json/operator_ne/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"
whether the values lhs/*this and rhs are not equal
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.
3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:
Two JSON values compare with a result of std::partial_ordering::unordered if either value is discarded.
If both JSON values are of the same type, the result is produced by 3-way comparing their stored values using their respective operator<=>.
Integer and floating-point numbers are converted to their common type and then 3-way compared using their respective operator<=>. For instance, comparing an integer and a floating-point value will 3-way compare the first value converted to floating-point with the second value.
Otherwise, yields a result by comparing the type (see value_t).
3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way comparing both JSON values (see 1).
"},{"location":"api/basic_json/operator_spaceship/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"rhs (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"
the std::partial_ordering of the 3-way comparison of *this and rhs
Value type return value nullvalue_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.
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
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.
a pointer to a null-terminated string of single byte characters (throws if null)
a std::string
an object obj for which begin(obj) and end(obj) produces a valid pair of iterators.
IteratorType
a compatible iterator type, for instance.
a pair of std::string::iterator or std::vector<std::uint8_t>::iterator
a pair of pointers such as ptr and ptr + len
"},{"location":"api/basic_json/parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. cb (in) a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"
Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
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.
[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
Overload for contiguous containers (1) added in version 2.0.3.
Ignoring comments via ignore_comments added in version 3.9.0.
Changed runtime assertion in case of 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.
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
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.
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
With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
parameter event description parameter depth parameter parsedparse_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:
Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read.
In case a value outside a structured type is skipped, it is replaced with null. This case happens if the top-level element is skipped.
"},{"location":"api/basic_json/parser_callback_t/#parameters","title":"Parameters","text":"depth (in) the depth of the recursion during parsing event (in) an event of type parse_event_t indicating the context in the callback function has been called parsed (in, out) the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"
Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.
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.
Throws parse_error.104 if the JSON patch does not consist of an array of objects.
Throws parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".
Throws out_of_range.401 if an array index is out of range.
Throws 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\".
Throws out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")
Throws 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.
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.
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.
Throws parse_error.104 if the JSON patch does not consist of an array of objects.
Throws parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".
Throws out_of_range.401 if an array index is out of range.
Throws 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\".
Throws out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")
Throws 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.
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.
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
the current value is an object,
the initializer list init contains only two elements, and
the first element of init is a string,
init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).
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.
"},{"location":"api/basic_json/push_back/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"
All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use push_back() with number\"
(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
"},{"location":"api/basic_json/push_back/#examples","title":"Examples","text":"Example: (1) add element to array
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
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 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
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.
#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
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.
a pointer to a null-terminated string of single byte characters
an object obj 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":"
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.
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
Ignoring comments via 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);.
The return value depends on the different types and is defined as follows:
Value type return value null 0 boolean 1 string 1 number 1 binary 1 object result of function object_t::size() array result of function array_t::size()"},{"location":"api/basic_json/size/#exception-safety","title":"Exception safety","text":"
No-throw guarantee: this function never throws exceptions.
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.
Returns the position of the first character in the JSON string from which the value was parsed from.
JSON type return value object position of the opening { array position of the opening [ string position of the opening \" number position of the first character boolean position of t for true and f for false null position of n"},{"location":"api/basic_json/start_pos/#return-value","title":"Return value","text":"
the position of the first character of the value in the parsed JSON string, if the value was created by the parse function, or std::string::npos if the value was constructed otherwise
Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.
"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"j1 (in, out) value to be replaced by j2j2 (in, out) value to be replaced by j1"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"
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.
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.
Exchanges the contents of the JSON value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of the JSON value from left with those of right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Implemented as a friend function callable via ADL.
Exchanges the contents of a JSON array with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a JSON object with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a JSON string with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a binary value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a binary value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike version (6), no binary subtype is involved.
"},{"location":"api/basic_json/swap/#parameters","title":"Parameters","text":"other (in, out) value to exchange the contents with left (in, out) value to exchange the contents with right (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"
No-throw guarantee: this function never throws exceptions.
No-throw guarantee: this function never throws exceptions.
Throws type_error.310 if called on JSON values other than arrays; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than objects; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than strings; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
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.
Returns a byte vector containing the BJData serialization.
Writes the BJData serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default. version (in) which version of BJData to use (see note on \"Binary values\" on BJData); optional, bjdata_version_t::draft2 by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"
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).
Returns a byte vector containing the BSON serialization.
Writes the BSON serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"
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.
Returns a byte vector containing the CBOR serialization.
Writes the CBOR serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"
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.
Returns a byte vector containing the MessagePack serialization.
Writes the MessagePack serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"
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
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.
Returns a byte vector containing the UBJSON serialization.
Writes the UBJSON serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"
Value type return value nullvalue_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.
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
The following code exemplifies type_name() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type_name()\n std::cout << j_null << \" is a \" << j_null.type_name() << '\\n';\n std::cout << j_boolean << \" is a \" << j_boolean.type_name() << '\\n';\n std::cout << j_number_integer << \" is a \" << j_number_integer.type_name() << '\\n';\n std::cout << j_number_unsigned << \" is a \" << j_number_unsigned.type_name() << '\\n';\n std::cout << j_number_float << \" is a \" << j_number_float.type_name() << '\\n';\n std::cout << j_object << \" is an \" << j_object.type_name() << '\\n';\n std::cout << j_array << \" is an \" << j_array.type_name() << '\\n';\n std::cout << j_string << \" is a \" << j_string.type_name() << '\\n';\n}\n
Output:
null is a null\ntrue is a boolean\n-17 is a number\n42 is a number\n23.42 is a number\n{\"one\":1,\"two\":2} is an object\n[1,2,4,8,16] is an array\n\"Hello, world\" is a string\n
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:
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().
For ordered_json, adding a value to an object can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
"},{"location":"api/basic_json/update/#parameters","title":"Parameters","text":"j (in) JSON object to read values from merge_objects (in) when true, existing keys are not overwritten, but contents of objects are merged recursively (default: false) first (in) begin of the range of elements to insert last (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"
The function can throw the following exceptions:
Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
The function can throw the following exceptions:
Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
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.
Unlike at, this function does not throw if the given key/ptr was not found.
Unlike 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.
"},{"location":"api/basic_json/value/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17). ValueType type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"key (in) key of the element to access default_value (in) the value to return if key/ptr found no value ptr (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"
copy of the element at key key or default_value if key is not found
copy of the element at key key or default_value if key is not found
copy of the element at JSON Pointer ptr or default_value if no value for ptr is found
The value function is a template, and the return type of the function is determined by the type of the provided default value unless otherwise specified. This can have unexpected effects. In the example below, we store a 64-bit unsigned integer. We get exactly that value when using operator[]. However, when we call value and provide 0 as default value, then -1 is returned. The occurs, because 0 has type int which overflows when handling the value 18446744073709551615.
To address this issue, either provide a correctly typed default value or use the template parameter to specify the desired return type. Note that this issue occurs even when a value is stored at the provided key, and the default value is not used as the return value.
operator[]: 18446744073709551615\ndefault value (int): -1\ndefault value (uint64_t): 18446744073709551615\nexplict return value type: 18446744073709551615\n
"},{"location":"api/basic_json/value/#examples","title":"Examples","text":"Example: (1) access specified object element with default value
The example below shows how object elements can be queried with a default value.
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.
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 integers
number_integer_t for signed integers
number_float_t for floating-point numbers or to approximate integers which do not fit into the limits of their respective type
Comparison operators
operator< and operator<=> (since C++20) are overloaded and compare according to the ordering described above. Until C++20 all other relational and equality operators yield results according to the integer value of each enumerator. Since C++20 some compilers consider the rewritten candidates generated from operator<=> during overload resolution, while others do not. For predictable and portable behavior use:
operator< or operator<=> when wanting to compare according to the order described above
operator== or operator!= when wanting to compare according to each enumerators integer value
template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n
This type extends the template parameter BinaryType provided to basic_json with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type.
"},{"location":"api/byte_container_with_subtype/#template-parameters","title":"Template parameters","text":"BinaryType container to store bytes (std::vector<std::uint8_t> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":"
container_type - the type of the underlying container (BinaryType)
subtype_type - the type of the subtype (std::uint64_t)
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.
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.
A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.
"},{"location":"api/json_pointer/#template-parameters","title":"Template parameters","text":"RefStringType the string type used for the reference tokens making up the JSON pointer
Deprecation
For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.
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":"
Throws parse_error.107 if the given JSON pointer s is nonempty and does not begin with a slash (/); see example below.
Throws parse_error.108 if a tilde (~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.
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
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.
"},{"location":"api/json_pointer/operator_eq/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"
\"\" == \"\": 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
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.
"},{"location":"api/json_pointer/operator_ne/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"
whether the values lhs/*this and rhs are not equal
\"\" != \"\": 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
append another JSON pointer at the end of this JSON pointer
append an unescaped reference token at the end of this JSON pointer
append an array index at the end of this JSON pointer
"},{"location":"api/json_pointer/operator_slasheq/#parameters","title":"Parameters","text":"ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"
JSON pointer with ptr appended
JSON pointer with token appended without escaping token
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":"
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":"
number_integer_t - BasicJsonType's type for numbers (integer)
number_unsigned_t - BasicJsonType's type for numbers (unsigned)
number_float_t - BasicJsonType's type for numbers (floating-point)
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
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
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
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
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/#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":"
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
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
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/#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).
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/#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":"
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/#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":"
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
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
The library uses numerous assertions to guarantee invariants and to abort in case of otherwise undefined behavior (e.g., when calling operator[] with a missing object key on a const object). See page runtime assertions for more information.
Defining the macro to code that does not call std::abort may leave the library in an undefined state.
This macro enables position diagnostics for generated JSON objects.
When enabled, two new member functions start_pos() and end_pos() are added to basic_json values. If the value was created by calling theparse function, then these functions allow to query the byte positions of the value in the input it was parsed from. In case the value was constructed by other means, std::string::npos is returned.
start_pos() returns the position of the first character of a given value in the original JSON string, while end_pos() returns the position of the character following the last character. For objects and arrays, the first and last characters correspond to the opening or closing braces/brackets, respectively. For primitive values, the first and last character represent the opening and closing quotes (strings) or the first and last character of the field's numerical or predefined value (true, false, null), respectively.
JSON type return value start_pos() return value end_pos() object position of the opening { position after the closing } array position of the opening [ position after the closing ] string position of the opening \" position after the closing \" number position of the first character position after the last character boolean position of t for true and f for false position after e null position of n position after l
Given the above, end_pos()-start_pos() for a JSON value provides the length of the parsed JSON string for that value, including the opening or closing braces, brackets, or quotes.
Note that enabling this macro increases the size of every JSON value by two std::size_t fields and adds slight runtime overhead to parsing, copying JSON value objects, and the generation of error messages for exceptions. It also causes these values to be reported in those error messages.
Diagnostic positions can also be controlled with the CMake option JSON_Diagnostic_Positions (OFF by default) which defines JSON_DIAGNOSTIC_POSITIONS accordingly.
Availability
Diagnostic positions are only available if the value was created by the parse function. The sax_parse function or all other means to create a JSON value do not set the diagnostic positions and start_pos() and end_pos() will only return std::string::npos for these values.
Invalidation
The returned positions are only valid as long as the JSON value is not changed. The positions are not updated when the JSON value is changed.
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.
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.
#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.
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.
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.
#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>).
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.
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.
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)).
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.
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.
// (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.
This macro overrides catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.
This macro overrides throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
This macro overrides try calls inside the library. It has no arguments and is always followed by a scope.
"},{"location":"api/macros/json_throw_user/#parameters","title":"Parameters","text":"exception (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"
By default, the macros map to their respective C++ keywords:
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
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 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
#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.
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.
When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.
The 3-way comparison operator (<=>) will always give the correct result (std::partial_ordering::unordered) regardless of the value of JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON.
Overloads for the equality and relational operators emulate the legacy behavior.
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.
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.
Macros 1, 2 and 3 are to be defined inside the class/struct to create code for. Like NLOHMANN_DEFINE_TYPE_INTRUSIVE, they can access private members.
Macros 4, 5 and 6 are to be defined outside the class/struct to create code for, but inside its namespace. Like 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.
Macros 1 and 4 will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
Macros 2 and 5 will use value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.
Summary:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE"},{"location":"api/macros/nlohmann_define_derived_type/#parameters","title":"Parameters","text":"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:
In first two 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\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, const B& b) {\n nlohmann::to_json(j, static_cast<const A&>(b));\n // ...\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, B& b) {\n nlohmann::from_json(j, static_cast<A&>(b));\n // ...\n}\n
In the third case, only to_json will be called:
class A { /* ... */ };\nclass B : public A { /* ... */ };\n\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, const B& b) {\n nlohmann::to_json(j, static_cast<const A&>(b));\n // ...\n}\n
NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT / NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE for similar macros that can be defined inside a non-derived type.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT / NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for similar macros that can be defined outside a non-derived type.
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.
Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
Will use value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.
Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
Summary:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_TYPE_INTRUSIVE NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE"},{"location":"api/macros/nlohmann_define_type_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","title":"Default definition","text":"
The macros add two friend functions to the class which take care of the serialization and deserialization:
The type type must be default constructible (except (3)). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
The macro must be used inside the type (class/struct).
Implementation limits
The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the to_json/from_json functions manually.
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.
The macro NLOHMANN_DEFINE_TYPE_INTRUSIVE is used inside the class.
A missing key \"age\" in the deserialization yields an exception. To fall back to the default value, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT can be used.
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.
The macro NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT is used inside the class.
A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value -1 is used.
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.
The macro NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE is used inside the class.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for a similar macro that can be defined outside the type.
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for similar macros for derived types
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.
Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
Will use value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.
Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
Summary:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the (public) member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","title":"Default definition","text":"
The macros add two functions to the namespace which take care of the serialization and deserialization:
The type type must be default constructible (except (3). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
The macro must be used outside the type (class/struct).
The passed members must be public.
Implementation limits
The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the to_json/from_json functions manually.
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.
The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE is used outside the class, but inside its namespace ns.
A missing key \"age\" in the deserialization yields an exception. To fall back to the default value, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT can be used.
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.
The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE is used outside the class, but inside its namespace ns.
NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE for a similar macro that can be defined inside the type.
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for similar macros for derived types
The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann\nusing json = NLOHMANN_JSON_NAMESPACE::json;\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n
By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.
"},{"location":"api/macros/nlohmann_json_serialize_enum/#parameters","title":"Parameters","text":"type (in) name of the enum to serialize/deserialize conversion (in) a pair of an enumerator and a JSON serialization; arbitrary pairs can be given as a comma-separated list"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","title":"Default definition","text":"
The macro adds two functions to the namespace which take care of the serialization and deserialization:
The macro must be used inside the namespace of the enum.
Important notes
When using template get<ENUM_TYPE>(), undefined JSON values will default to the first specified conversion. Select this default pair carefully. See example 1 below.
If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the list will be returned when converting to or from JSON. See example 2 below.
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.
Code of Conduct - the rules and norms of this project
Contribution Guidelines - guidelines how to contribute to this project
Governance - the governance model of this project
Quality Assurance - how quality of this project is assured
Security Policy - the security policy of the project
"},{"location":"community/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"community/code_of_conduct/#our-pledge","title":"Our Pledge","text":"
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders 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, and will communicate reasons for moderation decisions when appropriate.
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mail@nlohmann.me. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
Community Impact: A violation through a single incident or series of actions.
Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
Consequence: A permanent ban from any sort of public interaction within the community.
This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
Community Impact Guidelines were inspired by Mozilla's code of conduct enforcement ladder.
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
Thank you for your interest in contributing to this project! What began as an exercise to explore the exciting features of C++11 has evolved into a widely-used JSON library. I truly appreciate all the contributions from the community, whether it's proposing features, identifying bugs, or fixing mistakes! To ensure that our collaboration is efficient and effective, please follow these guidelines.
Feel free to discuss or suggest improvements to this document by submitting a pull request.
"},{"location":"community/contribution_guidelines/#ways-to-contribute","title":"Ways to Contribute","text":"
There are multiple ways to contribute.
"},{"location":"community/contribution_guidelines/#reporting-an-issue","title":"Reporting an issue","text":"
Please create an issue, assuming one does not already exist, and describe your concern. Note you need a GitHub account for this.
Clearly describe the issue:
If it is a bug, please describe how to reproduce it. If possible, attach a complete example which demonstrates the error. Please also state what you expected to happen instead of the error.
If you propose a change or addition, try to give an example how the improved code could look like or how to use it.
If you found a compilation error, please tell us which compiler (version and operating system) you used and paste the (relevant part of) the error messages to the ticket.
Please stick to the provided issue template bug report if possible.
"},{"location":"community/contribution_guidelines/#reporting-a-security-vulnerability","title":"Reporting a security vulnerability","text":"
You can report a security vulnerability according to our security policy.
"},{"location":"community/contribution_guidelines/#discussing-a-new-feature","title":"Discussing a new feature","text":"
For questions, feature or support requests, please open a discussion. If you find a proposed answer satisfactory, please use the \"Mark as answer\" button to make it easier for readers to see what helped and for the community to filter for open questions.
"},{"location":"community/contribution_guidelines/#proposing-a-fix-or-an-improvement","title":"Proposing a fix or an improvement","text":"
Join an ongoing discussion or comment on an existing issue before starting to code. This can help to avoid duplicate efforts or other frustration during the later review.
Create a pull request against the develop branch and follow the pull request template. In particular,
describe the changes in detail, both the what and why,
reference existing issues where applicable,
add tests to maintain 100% test coverage,
update the documentation as needed, and
ensure the source code is amalgamated.
We describe all points in detail below.
All contributions (including pull requests) must agree to the Developer Certificate of Origin (DCO) version 1.1. This is exactly the same one created and used by the Linux kernel developers and posted on http://developercertificate.org/. This is a developer's certification that he or she has the right to submit the patch for inclusion into the project.
"},{"location":"community/contribution_guidelines/#how-to","title":"How to...","text":""},{"location":"community/contribution_guidelines/#describe-your-changes","title":"Describe your changes","text":"
This library is primarily maintained as a spare-time project. As such, I can not make any guarantee how quickly changes are merged and released. Therefore, it is very important to make the review as smooth as possible by explaining not only what you changed, but why. This rationale can be very valuable down the road when improvements or bugs are discussed years later.
Link a pull request to an issue to clarify that a fix is forthcoming and which issue can be closed after merging. Only few cases (e.g., fixing typos) don\u2019t require prior discussions.
The library has an extensive test suite that currently covers 100 % of the library's code. These test are crucial to maintain API stability and give future contributors confidence that they do not accidentally break things. As Titus Winters aptly put it:
If you liked it, you should have put a test on it.
"},{"location":"community/contribution_guidelines/#run-the-tests","title":"Run the tests","text":"
First, ensure the test suite runs before making any changes:
The tests are located in tests/src/unit-*.cpp and contain doctest assertions like CHECK. The tests are structured along the features of the library or the nature of the tests. Usually, it should be clear from the context which existing file needs to be extended, and only very few cases require creating new test files.
When fixing a bug, edit unit-regression2.cpp and add a section referencing the fixed issue.
If test coverage decreases, an automatic warning comment will be posted on the pull request. You can access a code coverage report as artifact to the \u201cUbuntu\u201d workflow.
"},{"location":"community/contribution_guidelines/#update-the-documentation","title":"Update the documentation","text":"
The main documentation of the library is generated from the files docs/mkdocs/docs. This folder contains dedicated pages for certain features, a list of all exceptions, and an extensive API documentation with details on every public API function.
Build the documentation locally using:
make install_venv -C docs/mkdocs\nmake serve -C docs/mkdocs\n
The documentation will then available at http://127.0.0.1:8000/. See the documentation of mkdocs and Material for MkDocs for more information.
"},{"location":"community/contribution_guidelines/#amalgamate-the-source-code","title":"Amalgamate the source code","text":"
The single-header files single_include/nlohmann/json.hpp and single_include/nlohmann/json_fwd.hpp are generated from the source files in the include/nlohmann directory. Do not edit the files directly; instead, modify the include/nlohmann sources and regenerate the files by executing:
"},{"location":"community/contribution_guidelines/#break-the-public-api","title":"Break the public API","text":"
We take pride in the library being used by numerous customers across various industries. They all rely on the guarantees provided by semantic versioning. Please do not change the library such that the public API of the 3.x.y version is broken. This includes:
Changing function signatures (altering parameter types, return types, number of parameters) or changing the const-ness of member functions.
Removing functions.
Renaming functions or classes.
Changing exception handling.
Changing exception ids.
Changing access specifiers.
Changing default arguments.
Although these guidelines may seem restrictive, they are essential for maintaining the library\u2019s utility.
Breaking changes may be introduced when they are guarded with a feature macro such as JSON_USE_IMPLICIT_CONVERSIONS which allows to selectively change the behavior of the library. In next steps, the current behavior can then be deprecated. Using feature macros then allows users to test their code against the library in the next major release.
"},{"location":"community/contribution_guidelines/#break-c11-language-conformance","title":"Break C++11 language conformance","text":"
This library is designed to work with C++11 and later. This means that any supported C++11 compiler should compile the library without problems. Some compilers like GCC 4.7 (and earlier), Clang 3.3 (and earlier), or Microsoft Visual Studio 13.0 and earlier are known not to work due to missing or incomplete C++11 support.
Please do not add features that do not work with the mentioned supported compilers. Please guard features from C++14 and later against the respective JSON_HAS_CPP_14 macros.
Please refrain from proposing changes that would break JSON conformance. If you propose a conformant extension of JSON to be supported by the library, please motivate this extension.
The following areas really need contribution and are always welcomed:
Extending the continuous integration toward more exotic compilers such as Android NDK, Intel's Compiler, or the bleeding-edge versions Clang.
Improving the efficiency of the JSON parser. The current parser is implemented as a naive recursive descent parser with hand coded string handling. More sophisticated approaches like LALR parsers would be really appreciated. That said, parser generators like Bison or ANTLR do not play nice with single-header files -- I really would like to keep the parser inside the json.hpp header, and I am not aware of approaches similar to re2c for parsing.
Extending and updating existing benchmarks to include (the most recent version of) this library. Though efficiency is not everything, speed and memory consumption are very important characteristics for C++ developers, so having proper comparisons would be interesting.
We look forward to your contributions and collaboration to enhance the library!
The governance model for the JSON for Modern C++ project is a Benevolent Dictator for Life (BDFL) structure. As the sole maintainer, Niels Lohmann is responsible for all key aspects of the project. The project governance may evolve as the project grows, but any changes will be documented here and communicated to contributors.
This project is led by a benevolent dictator, Niels Lohmann, and managed by the community. That is, the community actively contributes to the day-to-day maintenance of the project, but the general strategic line is drawn by the benevolent dictator. In case of disagreement, they have the last word. It is the benevolent dictator\u2019s job to resolve disputes within the community and to ensure that the project is able to progress in a coordinated way. In turn, it is the community\u2019s job to guide the decisions of the benevolent dictator through active engagement and contribution.
"},{"location":"community/governance/#roles-and-responsibilities","title":"Roles and responsibilities","text":""},{"location":"community/governance/#benevolent-dictator-project-lead","title":"Benevolent dictator (project lead)","text":"
Typically, the benevolent dictator, or project lead, is self-appointed. However, because the community always has the ability to fork, this person is fully answerable to the community. The project lead\u2019s role is a difficult one: they set the strategic objectives of the project and communicate these clearly to the community. They also have to understand the community as a whole and strive to satisfy as many conflicting needs as possible, while ensuring that the project survives in the long term.
In many ways, the role of the benevolent dictator is less about dictatorship and more about diplomacy. The key is to ensure that, as the project expands, the right people are given influence over it and the community rallies behind the vision of the project lead. The lead\u2019s job is then to ensure that the committers (see below) make the right decisions on behalf of the project. Generally speaking, as long as the committers are aligned with the project\u2019s strategy, the project lead will allow them to proceed as they desire.
Committers are contributors who have made several valuable contributions to the project and are now relied upon to both write code directly to the repository and screen the contributions of others. In many cases they are programmers but it is also possible that they contribute in a different role. Typically, a committer will focus on a specific aspect of the project, and will bring a level of expertise and understanding that earns them the respect of the community and the project lead. The role of committer is not an official one, it is simply a position that influential members of the community will find themselves in as the project lead looks to them for guidance and support.
Committers have no authority over the overall direction of the project. However, they do have the ear of the project lead. It is a committer\u2019s job to ensure that the lead is aware of the community\u2019s needs and collective objectives, and to help develop or elicit appropriate contributions to the project. Often, committers are given informal control over their specific areas of responsibility, and are assigned rights to directly modify certain areas of the source code. That is, although committers do not have explicit decision-making authority, they will often find that their actions are synonymous with the decisions made by the lead.
Contributors are community members who either have no desire to become committers, or have not yet been given the opportunity by the benevolent dictator. They make valuable contributions, such as those outlined in the list below, but generally do not have the authority to make direct changes to the project code. Contributors engage with the project through communication tools, such as email lists, and via reports and patches attached to issues in the issue tracker, as detailed in our community tools document.
Anyone can become a contributor. There is no expectation of commitment to the project, no specific skill requirements and no selection process. To become a contributor, a community member simply has to perform one or more actions that are beneficial to the project.
Some contributors will already be engaging with the project as users, but will also find themselves doing one or more of the following:
supporting new users (current users often provide the most effective new user support)
reporting bugs
identifying requirements
supplying graphics and web design
programming
assisting with project infrastructure
writing documentation
fixing bugs
adding features
As contributors gain experience and familiarity with the project, they may find that the project lead starts relying on them more and more. When this begins to happen, they gradually adopt the role of committer, as described above.
Users are community members who have a need for the project. They are the most important members of the community: without them, the project would have no purpose. Anyone can be a user; there are no specific requirements.
Users should be encouraged to participate in the life of the project and the community as much as possible. User contributions enable the project team to ensure that they are satisfying the needs of those users. Common user activities include (but are not limited to):
evangelising about the project
informing developers of project strengths and weaknesses from a new user\u2019s perspective
providing moral support (a \u2018thank you\u2019 goes a long way)
providing financial support
Users who continue to engage with the project and its community will often find themselves becoming more and more involved. Such users may then go on to become contributors, as described above.
All participants in the community are encouraged to provide support for new users within the project management infrastructure. This support is provided as a way of growing the community. Those seeking support should recognise that all support activity within the project is voluntary and is therefore provided as and when time allows. A user requiring guaranteed response times or results should therefore seek to purchase a support contract from a vendor. (Of course, that vendor should be an active member of the community.) However, for those willing to engage with the project on its own terms, and willing to help support other users, the community support channels are ideal.
Anyone can contribute to the project, regardless of their skills, as there are many ways to contribute. For instance, a contributor might be active on the project mailing list and issue tracker, or might supply patches. The various ways of contributing are described in more detail in our roles in open source document.
The developer mailing list is the most appropriate place for a contributor to ask for help when making their first contribution.
The benevolent dictatorship model does not need a formal conflict resolution process, since the project lead\u2019s word is final. If the community chooses to question the wisdom of the actions of a committer, the project lead can review their decisions by checking the email archives, and either uphold or reverse them.
Source
The text was taken from http://oss-watch.ac.uk/resources/benevolentdictatorgovernancemodel.
Ensuring quality is paramount for this project, particularly because numerous other projects depend on it. Each commit to the library undergoes rigorous checks against the following requirements, and any violations will result in a failed build.
"},{"location":"community/quality_assurance/#c-language-compliance-and-compiler-compatibility","title":"C++ language compliance and compiler compatibility","text":"
Requirement: Compiler support
Any compiler with complete C++11 support can compile the library without warnings.
The library is compiled library with 50+ different C++ compilers with different operating systems and platforms, including the oldest versions known to compile the library.
The library is compiled with all C++ language revisions (C++11, C++14, C++17, C++20, C++23, and C++26) to detect and fix language deprecations early.
The library is checked for compiler warnings:
On Clang, -Weverything is used with 7 exceptions.
Clang warnings
# Ignored Clang warnings:\n# -Wno-c++98-compat The library targets C++11.\n# -Wno-c++98-compat-pedantic The library targets C++11.\n# -Wno-deprecated-declarations The library contains annotations for deprecated functions.\n# -Wno-extra-semi-stmt The library uses assert which triggers this warning.\n# -Wno-padded We do not care about padding warnings.\n# -Wno-covered-switch-default All switches list all cases and a default case.\n# -Wno-unsafe-buffer-usage Otherwise Doctest would not compile.\n\nset(CLANG_CXXFLAGS\n -Werror\n -Weverything\n -Wno-c++98-compat\n -Wno-c++98-compat-pedantic\n -Wno-deprecated-declarations\n -Wno-extra-semi-stmt\n -Wno-padded\n -Wno-covered-switch-default\n -Wno-unsafe-buffer-usage\n)\n
On GCC, 300+ warnings are enabled with 8 exceptions.
A common code style is used throughout all code files of the library.
The code is formatted with Artistic Style (astyle) against a style configuration that is also enforced in the CI.
Astyle configuration (tools/astyle/.astylerc)
# Configuration for Artistic Style\n# see https://astyle.sourceforge.net/astyle.html\n\n#######################\n# Brace Style Options #\n#######################\n\n# use Allman style for braces\n--style=allman\n\n###############\n# Tab Options #\n###############\n\n# indent using 4 spaces\n--indent=spaces=4\n\n#######################\n# Indentation Options #\n#######################\n\n# indent access modifiers one half indent\n--indent-modifiers\n\n# indent switch cases to the switch block\n--indent-switches\n\n# indent preprocessor blocks\n--indent-preproc-block\n\n# indent preprocessor defines\n--indent-preproc-define\n\n# indent C++ comments\n--indent-col1-comments\n\n###################\n# Padding Options #\n###################\n\n# insert space padding around operators\n--pad-oper\n\n# insert space between if/for/while... and the following parentheses\n--pad-header\n\n# attach the pointer to the variable type (left)\n--align-pointer=type\n\n# attach the reference to the variable type (left)\n--align-reference=type\n\n######################\n# Formatting Options #\n######################\n\n# add braces to unbraced one line conditional statements\n--add-braces\n\n# convert tabs to spaces\n--convert-tabs\n\n# closes whitespace between the ending angle brackets of template definitions\n--close-templates\n\n#################\n# Other Options #\n#################\n\n# do not create backup files\n--suffix=none\n\n# preserve the original file date\n--preserve-date\n\n# display only the files that have been formatted\n--formatted\n\n# for the linux (LF) line end style\n--lineend=linux\n
The code style is checked with cpplint with 61 enabled rules.
The library can be used by adding a single header to a C++ project.
An amalgamation script is used to check if the source code is exposed as self-contained single-header file.
The test suite is checked against the amalgamated source file as well as the individual source file.
Requirement: CMake as primary development tool
All library functions are exposed and usable by CMake.
All library options are exposed as CMake options and tested.
The library is tested against the earliest supported CMake version.
"},{"location":"community/security_policy/","title":"Security Policy","text":""},{"location":"community/security_policy/#reporting-a-vulnerability","title":"Reporting a Vulnerability","text":"
We value the security of our users and appreciate your efforts to responsibly disclose vulnerabilities. If you have identified a security vulnerability in this repository, please use the GitHub Security Advisory \"Report a Vulnerability\" tab.
Until it is published, this draft security advisory will only be visible to the maintainers of this project. Other users and teams may be added once the advisory is created.
We will send a response indicating the next steps in handling your report. After the initial reply to your report, we will keep you informed of the progress towards a fix and full announcement and may ask for additional information or guidance.
For vulnerabilities in third-party dependencies or modules, please report them directly to the respective maintainers.
Explore security-related topics and contribute to tools and projects through GitHub Security Lab.
Learn more about responsible disclosure and reporting vulnerabilities in GitHub at About coordinated disclosure of security vulnerabilities.
We sincerely thank you for contributing to the security and integrity of this project!
"},{"location":"features/arbitrary_types/","title":"Arbitrary Type Conversions","text":"
Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:
namespace ns {\n // a simple struct to model a person\n struct person {\n std::string name;\n std::string address;\n int age;\n };\n} // namespace ns\n\nns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// convert to JSON: copy each value into the JSON object\njson j;\nj[\"name\"] = p.name;\nj[\"address\"] = p.address;\nj[\"age\"] = p.age;\n\n// ...\n\n// convert from JSON: copy each value from the JSON object\nns::person p {\n j[\"name\"].template get<std::string>(),\n j[\"address\"].template get<std::string>(),\n j[\"age\"].template get<int>()\n};\n
It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
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:
Those methods MUST be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace ns, where person is defined).
Those methods MUST be available (e.g., proper headers must be included) everywhere you use these conversions. Look at #1108 for errors that may occur otherwise.
When using template get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)
In function 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.
You do not need to add serializers or deserializers for STL types like std::vector: the library already implements these.
"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","title":"Simplify your life with macros","text":"
If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate.
There are six 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_NON_INTRUSIVE_ONLY_SERIALIZE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It does not define a from_json() function which is needed in case the type does not have a default constructor.
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.
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It does not define a from_json() function which is needed in case the type does not have a default constructor.
Furthermore, there exist versions to use in case of derived classes:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_TYPE_INTRUSIVE NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE
For derived classes and structs, use the following macros
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE
Implementation limits
The current macro implementations are limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the to_json/from_json functions manually.
Example
The to_json/from_json functions for the person struct above can be created with:
Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed:
namespace ns {\n class address {\n private:\n std::string street;\n int housenumber;\n int postcode;\n\n public:\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)\n };\n}\n
"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"
This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
The library uses JSON Serializers to convert types to json. The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).
It is implemented like this (simplified):
template <typename T>\nstruct adl_serializer {\n static void to_json(json& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n static void from_json(const json& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n
This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...
To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:
// partial specialization (full specialization works too)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<boost::optional<T>> {\n static void to_json(json& j, const boost::optional<T>& opt) {\n if (opt == boost::none) {\n j = nullptr;\n } else {\n j = *opt; // this will call adl_serializer<T>::to_json which will\n // find the free function to_json in T's namespace!\n }\n }\n\n static void from_json(const json& j, boost::optional<T>& opt) {\n if (j.is_null()) {\n opt = boost::none;\n } else {\n opt = j.template get<T>(); // same as above, but with\n // adl_serializer<T>::from_json\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n
ABI compatibility
Use NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END instead of namespace nlohmann { } in code which may be linked with different versions of this library.
"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types","title":"How can I use get() for non-default constructible/non-copyable types?","text":"
There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:
struct move_only_type {\n move_only_type() = delete;\n move_only_type(int ii): i(ii) {}\n move_only_type(const move_only_type&) = delete;\n move_only_type(move_only_type&&) = default;\n\n int i;\n};\n\nnamespace nlohmann {\n template <>\n struct adl_serializer<move_only_type> {\n // note: the return type is no longer 'void', and the method only takes\n // one argument\n static move_only_type from_json(const json& j) {\n return {j.template get<int>()};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert move_only_type to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, move_only_type t) {\n j = t.i;\n }\n };\n}\n
"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"
Yes. You might want to take a look at unit-udt.cpp in the test suite, to see a few examples.
If you write your own serializer, you'll need to do a few things:
use a different basic_json alias than nlohmann::json (the last template parameter of basic_json is the JSONSerializer)
use your basic_json alias (or a template parameter) in all your to_json/from_json methods
use nlohmann::to_json and nlohmann::from_json when you need ADL
Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
// You should use void as a second template argument\n// if you don't need compile-time checks on T\ntemplate<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>\nstruct less_than_32_serializer {\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, T value) {\n // we want to use ADL, and call the correct to_json overload\n using nlohmann::to_json; // this method is called by adl_serializer,\n // this is where the magic happens\n to_json(j, value);\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing here\n using nlohmann::from_json;\n from_json(j, value);\n }\n};\n
Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
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.
"},{"location":"features/assertions/#function-with-runtime-assertions","title":"Function with runtime assertions","text":""},{"location":"features/assertions/#unchecked-object-access-to-a-const-value","title":"Unchecked object access to a const value","text":"
Function operator[] implements unchecked access for objects. Whereas a missing key is added in case of non-const objects, accessing a const object with a missing key is undefined behavior (think of a dereferenced null pointer) and yields a runtime assertion.
If you are not sure whether an element in an object exists, use checked access with the at function or call the contains function before.
See also the documentation on element access.
Example 1: Missing object key
The following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n
Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n
"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"
Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.
Example 2: Uninitialized iterator range
The following code will trigger an assertion at runtime:
Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n
"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"
Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.
Example 3: Uninitialized iterator
The following code will trigger an assertion at runtime:
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.
Example 4: Reading from null pointer
The following code will trigger an assertion at runtime:
The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored.
JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.
"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"
By default, binary values are stored as std::vector<std::uint8_t>. This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t:
JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: bytes holds an array of integers, and subtype is an integer or null.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// serialize to standard output\nstd::cout << j.dump(2) << std::endl;\n
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.
BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
Example
Code:
// create a binary value of subtype 42 (will be ignored in BJData)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BJData\nauto v = json::to_bjdata(j); \n
v is a std::vector<std::uint8t> with the following 20 elements:
BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BSON\nauto v = json::to_bson(j); \n
v is a std::vector<std::uint8t> with the following 22 elements:
0x16 0x00 0x00 0x00 // number of bytes in the document\n 0x05 // binary value\n 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte\n 0x04 0x00 0x00 0x00 // number of bytes\n 0x2a // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n0x00 // end of the document\n
Note that the serialization preserves the subtype, and deserializing v would yield the following value:
CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to CBOR\nauto v = json::to_cbor(j); \n
v is a std::vector<std::uint8t> with the following 15 elements:
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.
MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to MessagePack\nauto v = json::to_msgpack(j); \n
v is a std::vector<std::uint8t> with the following 14 elements:
UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
Example
Code:
// create a binary value of subtype 42 (will be ignored in UBJSON)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to UBJSON\nauto v = json::to_ubjson(j); \n
v is a std::vector<std::uint8t> with the following 20 elements:
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:
This library does not support comments by default. It does so for three reasons:
Comments are not part of the JSON specification. You may argue that // 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.
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:
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
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.
It MUST be available (e.g., proper headers must be included) everywhere you use the conversions.
Other Important points:
When using template get<ENUM_TYPE>(), undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.
If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.
To disable the default serialization of enumerators as integers and force a compiler error instead, see 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().
"},{"location":"features/iterators/#iteration-order-for-objects","title":"Iteration order for objects","text":"
When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.
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.
"},{"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.
Example
json j = {1, 2, 3, 4};\n\nfor (auto it = j.rbegin(); it != j.rend(); ++it)\n{\n std::cout << *it << std::endl;\n}\n
Output:
4\n3\n2\n1\n
"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"
Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe the underlying string or binary array is empty.
Example
json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n
Output:
\"Hello, world\"\n
"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators clear all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"
JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
Example
The following code shows how a JSON patch is applied to a value.
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.
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
Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.
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.
When enabled, two new member functions start_pos() and end_pos() are added to basic_json values. If the value was created by calling theparse function, then these functions allow to query the byte positions of the value in the input it was parsed from. The byte positions are also used in exceptions to help locate errors.
The diagnostics positions can also be controlled with the CMake option JSON_Diagnostic_Positions (OFF by default) which sets JSON_DIAGNOSTIC_POSITIONS accordingly.
See full documentation of JSON_DIAGNOSTIC_POSITIONS
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.
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.
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.
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)).
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.
The library defines 12 macros to simplify the serialization/deserialization of types. See the page on arbitrary type conversion for a detailed discussion.
The library supports JSON Merge Patch (RFC 7386) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.
Example
The following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n
Output:
{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n
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.
The complete default namespace name is derived as follows:
The root namespace is always nlohmann.
The inline namespace starts with 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.
The inline namespace ends with the suffix _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:
Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS. This is illustrated in the diagram below.
In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.
Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types.
There is an exception when forward declarations are used (i.e., when including json_fwd.hpp) in which case the linker may complain about undefined references.
"},{"location":"features/namespace/#disabling-the-version-component","title":"Disabling the version component","text":"
Different versions are not necessarily ABI-incompatible, but the project does not actively track changes in the ABI and recommends that all parts of a codebase exchanging library types be built with the same version. Users can, at their own risk, disable the version component of the linline namespace, allowing different versions \u2013 but not configurations \u2013 to be used in cases where the linker would otherwise output undefined reference errors.
To do so, define NLOHMANN_JSON_NAMESPACE_NO_VERSION to 1.
This applies to version 3.11.2 and above only, versions 3.11.0 and 3.11.1 can apply the technique described in the next section to emulate the effect of the NLOHMANN_JSON_NAMESPACE_NO_VERSION macro.
Use at your own risk
Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!
"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"
When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows:
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.
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.
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
BJData (Binary JData),
BSON (Binary JSON),
CBOR (Concise Binary Object Representation),
MessagePack, and
UBJSON (Universal Binary JSON)
to efficiently encode JSON values to byte vectors and to decode such vectors.
"},{"location":"features/binary_formats/#comparison","title":"Comparison","text":""},{"location":"features/binary_formats/#completeness","title":"Completeness","text":"Format Serialization Deserialization BJData complete complete BSON incomplete: top-level value must be an object incomplete, but all JSON types are supported CBOR complete incomplete, but all JSON types are supported MessagePack complete complete UBJSON complete complete"},{"location":"features/binary_formats/#binary-values","title":"Binary values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported
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 5 new type markers - [u] - uint16, [m] - uint32, [M] - uint64, [h] - float16 and [B] - byte - 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.
The library uses the following mapping from JSON values types to BJData types according to the BJData specification:
JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { binary see notes on binary values array [$B
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:
strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 bytes (theoretical)
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:
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 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
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 UiuImlMLhdDCB. 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
BJData provides a dedicated B marker (defined in the BJData specification (Draft 3)) that is used in optimized arrays to designate binary data. This means that, unlike UBJSON, binary data can be both serialized and deserialized.
To preserve compatibility with BJData Draft 2, the Draft 3 optimized binary array must be explicitly enabled using the version parameter of to_bjdata.
In Draft2 mode (default), if the JSON data contains the binary type, the value stored as 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
The library maps BJData types to JSON value types as follows:
BJData type JSON value type marker no-op no value, next value is read N null nullZ false falseF true trueT 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 byte number_unsigned B 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) { binary binary (strongly-typed byte array) [$B
Complete mapping
The mapping is complete in the sense that any BJData value can be converted to a JSON value.
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.
The library uses the following mapping from JSON values types to BSON types:
JSON value type value/range BSON type marker null null null 0x0A boolean true, false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 uint64 0x11 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, 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
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 uint64(Timestamp) 0x11 number_unsigned 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported
Incomplete mapping
The mapping is incomplete. The unsupported mappings are indicated in the table above.
Handling of BSON type 0x11
BSON type 0x11 is used to represent uint64 numbers. This library treats these values purely as uint64 numbers and does not parse them into date-related formats.
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
CBOR Website - the main source on CBOR
CBOR Playground - an interactive webpage to translate between JSON and CBOR
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:
UTF-8 strings terminated by \"break\" (0x7F)
arrays terminated by \"break\" (0x9F)
maps terminated by \"break\" (0xBF)
byte strings terminated by \"break\" (0x5F)
date/time (0xC0..0xC1)
bignum (0xC2..0xC3)
decimal fraction (0xC4)
bigfloat (0xC5)
expected conversions (0xD5..0xD7)
simple values (0xE0..0xF3, 0xF8)
undefined (0xF7)
half-precision floats (0xF9)
break (0xFF)
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
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:
date/time (0xC0..0xC1)
bignum (0xC2..0xC3)
decimal fraction (0xC4)
bigfloat (0xC5)
expected conversions (0xD5..0xD7)
simple values (0xE0..0xF3, 0xF8)
undefined (0xF7)
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.
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.
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:
strings with more than 4294967295 bytes
byte strings with more than 4294967295 bytes
arrays with more than 4294967295 elements
objects with more than 4294967295 elements
NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the dump function which serializes NaN or Infinity to null.
Example
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n
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.
The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:
JSON value type value/range UBJSON type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map {
Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.
Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson.
Size constraints
The following values can not be converted to a UBJSON value:
strings with more than 9223372036854775807 bytes (theoretical)
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
The library maps UBJSON types to JSON value types as follows:
UBJSON type JSON value type marker no-op no value, next value is read N null nullZ false falseF true trueT 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.
The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise.
When accessing an invalid index (i.e., an index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown.
Accessing via invalid index or missing key
j.at(\"hobbies\").at(3) = \"cooking\";\n
This code produces the following exception:
[json.exception.out_of_range.401] array index 3 is out of range\n
When you extended diagnostic messages are enabled by defining JSON_DIAGNOSTICS, the exception further gives information where the key or index is missing or out of range.
[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n
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.
"},{"location":"features/element_access/checked_access/#summary","title":"Summary","text":"scenario non-const value const value access to existing object key reference to existing value is returned const reference to existing value is returned access to valid array index reference to existing value is returned const reference to existing value is returned access to non-existing object key basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown access to invalid array index basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown"},{"location":"features/element_access/default_value/","title":"Access with default value: value","text":""},{"location":"features/element_access/default_value/#overview","title":"Overview","text":"
In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. For this case, use value(key, default_value) which takes the key you want to access and a default value in case there is no value stored with that key.
expression value j{\"logOutput\": \"result.log\", \"append\": true}j.value(\"logOutput\", \"logfile.log\")\"result.log\"j.value(\"append\", true)truej.value(\"append\", false)truej.value(\"logLevel\", \"verbose\")\"verbose\""},{"location":"features/element_access/default_value/#notes","title":"Notes","text":"
Exceptions
value can only be used with objects. For other types, a basic_json::type_error is thrown.
Return type
The value function is a template, and the return type of the function is determined by the type of the provided default value unless otherwise specified. This can have unexpected effects. In the example below, we store a 64-bit unsigned integer. We get exactly that value when using operator[]. However, when we call value and provide 0 as default value, then -1 is returned. The occurs, because 0 has type int which overflows when handling the value 18446744073709551615.
To address this issue, either provide a correctly typed default value or use the template parameter to specify the desired return type. Note that this issue occurs even when a value is stored at the provided key, and the default value is not used as the return value.
operator[]: 18446744073709551615\ndefault value (int): -1\ndefault value (uint64_t): 18446744073709551615\nexplict return value type: 18446744073709551615\n
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.
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.
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
It is undefined behavior to access a const object with a non-existing key.
It is undefined behavior to access a const array with an invalid index.
In debug mode, an assertion will fire in both cases. You can disable assertions by defining the preprocessor symbol 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.
"},{"location":"features/element_access/unchecked_access/#summary","title":"Summary","text":"scenario non-const value const value access to existing object key reference to existing value is returned const reference to existing value is returned access to valid array index reference to existing value is returned const reference to existing value is returned access to non-existing object key reference to newly inserted null value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted null value is returned; any index between previous maximal index and passed index are filled with null undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"
Note
This page is under construction.
"},{"location":"features/parsing/#input","title":"Input","text":""},{"location":"features/parsing/#sax-vs-dom-parsing","title":"SAX vs. DOM parsing","text":""},{"location":"features/parsing/#exceptions","title":"Exceptions","text":"
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.
{\"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
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
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).
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
With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
parameter event description parameter depth parameter parsedparse_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
// 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:
Implement the SAX interface in a class. You can use class nlohmann::json_sax<json> as base class, but you can also use any class where the functions described above are implemented and public.
Create an object of your SAX interface class, e.g. my_sax.
Call bool json::sax_parse(input, &my_sax); where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.
Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return json value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error - it is up to you what to do with the exception object passed to your parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file json_sax.hpp.
JSON type C++ type object std::map<std::string, basic_json> array std::vector<basic_json> null std::nullptr_t string std::string boolean bool number std::int64_t, std::uint64_t, and double
Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.
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:
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.
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.
When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, {\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.
Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see 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}.
When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, {\"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.
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.
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.
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.
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.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
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:
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.
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
Numbers with a decimal digit or scientific notation are always stored as double.
The number types can be changed, see Template number types.
As of version 3.9.1, the conversion is realized by std::strtoull, std::strtoll, and std::strtod, respectively.
Examples
Integer -12345678912345789123456789 is smaller than INT64_MIN and will be stored as floating-point number -1.2345678912345788e+25.
Integer 1E3 will be stored as floating-point number 1000.0.
Any 64-bit signed or unsigned integer can be stored without loss of precision.
Numbers exceeding the limits of 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.
Floating-point numbers are rounded to the next number representable as double. For instance 3.141592653589793238462643383279 is stored as 0x400921fb54442d18. This is the same behavior as the code double x = 3.141592653589793238462643383279;.
Interoperability
The library interoperable with respect to the specification, because its supported range [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1].
All integers outside the range [-2^{63}, 2^{64}-1], as well as floating-point numbers are stored as 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 Serialization 0std::uint64_t(0)0-0std::int64_t(0)00.0double(0.0)0.0-0.0double(-0.0)-0.00E0double(0.0)0.0-0E0double(-0.0)-0.0
That is, -0 is stored as a signed integer, but the serialization does not reproduce the -.
Integer numbers are serialized as is; that is, no scientific notation is used.
Floating-point numbers are serialized as specified by 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:
The serialization can have fewer decimal places than the input: 2555.5599999999999 will be serialized as 2555.56. The reverse can also be true.
The serialization can be in scientific notation even if the input is not: 0.0000972439793401814 will be serialized as 9.72439793401814e-05. The reverse can also be true: 12345E-5 will be serialized as 0.12345.
Conversions from float to double can also introduce rounding errors:
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.
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:
JSON does not define a number type or precision (see above).
C++ also allows to silently convert between number types.
Conditional number conversion
The code above can be solved by explicitly checking the nature of the value with members such as is_number_integer() or is_number_unsigned():
// check if jd is really integer-valued\nif (jd.is_number_integer())\n{\n // if so, do the conversion and use i\n std::int64_t i = jd.template get<std::int64_t>();\n // ...\n}\nelse\n{\n // otherwise, take appropriate action\n // ...\n}\n
Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.
(Example taken from #777.)
"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"
As the example in Number conversion shows, there are different functions to determine the type of the stored number:
is_number() returns true for any number type
is_number_integer() returns true for signed and unsigned integers
is_number_unsigned() returns true for unsigned integers only
is_number_float() returns true for floating-point numbers
type_name() returns \"number\" for any number type
type() returns a different enumerator of value_t for all number types
function unsigned integer signed integer floating-point string is_number()truetruetruefalseis_number_integer()truetruefalsefalseis_number_unsigned()truefalsefalsefalseis_number_float()falsefalsetruefalsetype_name()\"number\"\"number\"\"number\"\"string\"type()number_unsignednumber_integernumber_floatstring"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"
The number types can be changed with template parameters.
position number type default type possible values 5 signed integers std::int64_tstd::int32_t, std::int16_t, etc. 6 unsigned integers std::uint64_tstd::uint32_t, std::uint16_t, etc. 7 floating-point doublefloat, long double
Constraints on number types
The type for signed integers must be convertible from long long. The type for floating-point numbers is used in case of overflow.
The type for unsigned integers must be convertible from unsigned long long. The type for floating-point numbers is used in case of overflow.
The types for signed and unsigned integers must be distinct, see #2573.
Only 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.
This page is still under construction. Its goal is to provide a high-level overview of the library's architecture. This should help new contributors to get an idea of the used concepts and where to make changes.
Values are stored as a tagged union of value_t and json_value.
/// the type of the current element\nvalue_t m_type = value_t::null;\n\n/// the value of the current element\njson_value m_value = {};\n
with
enum class value_t : std::uint8_t\n{\n null, ///< null value\n object, ///< object (unordered set of name/value pairs)\n array, ///< array (ordered collection of values)\n string, ///< string value\n boolean, ///< boolean value\n number_integer, ///< number value (signed integer)\n number_unsigned, ///< number value (unsigned integer)\n number_float, ///< number value (floating-point)\n binary, ///< binary array (ordered collection of bytes)\n discarded ///< discarded by the parser callback function\n};\n\nunion json_value {\n /// object (stored with pointer to save storage)\n object_t *object;\n /// array (stored with pointer to save storage)\n array_t *array;\n /// string (stored with pointer to save storage)\n string_t *string;\n /// binary (stored with pointer to save storage)\n binary_t *binary;\n /// boolean\n boolean_t boolean;\n /// number (integer)\n number_integer_t number_integer;\n /// number (unsigned integer)\n number_unsigned_t number_unsigned;\n /// number (floating-point)\n number_float_t number_float;\n};\n
Input is read via input adapters that abstract a source with a common interface:
/// read a single character\nstd::char_traits<char>::int_type get_character() noexcept;\n\n/// read multiple characters to a destination buffer and\n/// returns the number of characters successfully read\ntemplate<class T>\nstd::size_t get_elements(T* dest, std::size_t count = 1);\n
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.
Peregrine Lunar Lander Flight 01 - The library was utilized for payload management in the Peregrine Moon Lander, developed by Astrobotic Technology and launched as part of NASA's Commercial Lunar Payload Services (CLPS) program. After six days in orbit, the spacecraft was intentionally redirected into Earth's atmosphere, where it burned up over the Pacific Ocean on January 18, 2024.
Alexa Auto SDK, a software development kit enabling the integration of Alexa into automotive systems
Apollo, a framework for building autonomous driving systems
Automotive Grade Linux (AGL): a collaborative open-source platform for automotive software development
Genesis Motor (infotainment), a luxury automotive brand
Hyundai (infotainment), a global automotive brand
Kia (infotainment), a global automotive brand
Mercedes-Benz Operating System (MB.OS), a core component of the vehicle software ecosystem from Mercedes-Benz
Rivian (infotainment), an electric vehicle manufacturer
Suzuki (infotainment), a global automotive and motorcycle manufacturer
"},{"location":"home/customers/#gaming-and-entertainment","title":"Gaming and Entertainment","text":"
Assassin's Creed: Mirage: a stealth-action game set in the Middle East, focusing on the journey of a young assassin with classic parkour and stealth mechanics
Chasm: The Rift: a first-person shooter blending horror and adventure, where players navigate dark realms and battle monsters
College Football 25: a college football simulation game featuring gameplay that mimics real-life college teams and competitions
Concepts: a digital sketching app designed for creative professionals, offering flexible drawing tools for illustration, design, and brainstorming
Depthkit: a tool for creating and capturing volumetric video, enabling immersive 3D experiences and interactive content
immersivetech: a technology company focused on immersive experiences, providing tools and solutions for virtual and augmented reality applications
LOOT, a tool for optimizing the load order of game plugins, commonly used in The Elder Scrolls and Fallout series
Madden NFL 25: a sports simulation game capturing the excitement of American football with realistic gameplay and team management features
Marne, an unofficial private server platform for hosting custom Battlefield 1 game experiences
Minecraft, a popular sandbox video game
NHL 22: a hockey simulation game offering realistic gameplay, team management, and various modes to enhance the hockey experience
Pixelpart: a 2D animation and video compositing software that allows users to create animated graphics and visual effects with a focus on simplicity and ease of use
Red Dead Redemption II: an open-world action-adventure game following an outlaw's story in the late 1800s, emphasizing deep storytelling and immersive gameplay
Tactics Ogre: Reborn, a tactical role-playing game featuring strategic battles and deep storytelling elements
Throne and Liberty, an MMORPG that offers an expansive fantasy world with dynamic gameplay and immersive storytelling
Unity Vivox, a communication service that enables voice and text chat functionality in multiplayer games developed with Unity
Zool: Redimensioned: a modern reimagining of the classic platformer featuring fast-paced gameplay and vibrant environments
Audinate: a provider of networked audio solutions specializing in Dante technology, which facilitates high-quality digital audio transport over IP networks
Cisco Webex Desk Camera, a video camera designed for professional-quality video conferencing and remote collaboration
Philips Hue Personal Wireless Lighting: a smart lighting system for customizable and wireless home illumination
Ray-Ban Meta Smart glasses, a pair of smart glasses designed for capturing photos and videos with integrated connectivity and social features
Siemens SINEMA Remote Connect, a remote connectivity solution for monitoring and managing industrial networks and devices securely
Sony PlayStation 4, a gaming console developed by Sony that offers a wide range of games and multimedia entertainment features
Sony Virtual Webcam Driver for Remote Camera, a software driver that enables the use of Sony cameras as virtual webcams for video conferencing and streaming
Apple iOS and macOS, a family of operating systems developed by Apple, including iOS for mobile devices and macOS for desktop computers
Google Fuchsia, an open-source operating system developed by Google, designed to be secure, updatable, and adaptable across various devices
SerenityOS, an open-source operating system that aims to provide a simple and beautiful user experience with a focus on simplicity and elegance
Yocto: a Linux-based build system for creating custom operating systems and software distributions, tailored for embedded devices and IoT applications
"},{"location":"home/customers/#development-tools-and-ides","title":"Development Tools and IDEs","text":"
Accentize SpectralBalance, an adaptive speech analysis tool designed to enhance audio quality by optimizing frequency balance in recordings
Arm Compiler for Linux, a software development toolchain for compiling and optimizing applications on Arm-based Linux systems
BBEdit, a professional text and code editor for macOS
CoderPad, a collaborative coding platform that enables real-time code interviews and assessments for developers; the library is included in every CoderPad instance and can be accessed with a simple #include \"json.hpp\"
Compiler Explorer, a web-based tool that allows users to write, compile, and visualize the assembly output of code in various programming languages; the library is readily available and accessible with the directive #include <nlohmann/json.hpp>.
GitHub CodeQL, a code analysis tool used for identifying security vulnerabilities and bugs in software through semantic queries
Hex-Rays: a reverse engineering toolset for analyzing and decompiling binaries, primarily used for security research and vulnerability analysis
ImHex, a hex editor designed for reverse engineering, providing advanced features for data analysis and manipulation
Intel GPA Framework, a suite of cross-platform tools for capturing, analyzing, and optimizing graphics applications across different APIs
Meta Yoga, a layout engine that facilitates flexible and efficient user interface design across multiple platforms
MKVToolNix, a set of tools for creating, editing, and inspecting MKV (Matroska) multimedia container files
NVIDIA Nsight Compute, a performance analysis tool for CUDA applications that provides detailed insights into GPU performance metrics
Notepad++, a free source code editor that supports various programming languages
OpenRGB, an open source RGB lighting control that doesn't depend on manufacturer software
OpenTelemetry C++: a library for collecting and exporting observability data in C++, enabling developers to implement distributed tracing and metrics in their application
Qt Creator, an IDE for developing applications using the Qt application framework
Scanbot SDK: a software development kit (SDK) that provides tools for integrating advanced document scanning and barcode scanning capabilities into applications
"},{"location":"home/customers/#machine-learning-and-ai","title":"Machine Learning and AI","text":"
Apple Core ML Tools, a set of tools for converting and configuring machine learning models for deployment in Apple's Core ML framework
Avular Mobile Robotics: a platform for developing and deploying mobile robotics solutions
Google gemma.cpp, a lightweight C++ inference engine designed for running AI models from the Gemma family
llama.cpp, a C++ library designed for efficient inference of large language models (LLMs), enabling streamlined integration into applications
MLX, an array framework for machine learning on Apple silicon
Mozilla llamafile, a tool designed for distributing and executing large language models (LLMs) efficiently using a single file format
NVIDIA ACE, a suite of real-time AI solutions designed for the development of interactive avatars and digital human applications, enabling scalable and sophisticated user interactions
Peer: a platform offering personalized AI assistants for interactive learning and creative collaboration
stable-diffusion.cpp: a C++ implementation of the Stable Diffusion image generation model
TanvasTouch: a software development kit (SDK) that enables developers to create tactile experiences on touchscreens, allowing users to feel textures and physical sensations in a digital environment
TensorFlow, a machine learning framework that facilitates the development and training of models, supporting data serialization and efficient data exchange between components
"},{"location":"home/customers/#scientific-research-and-analysis","title":"Scientific Research and Analysis","text":"
BLACK, a bounded linear temporal logic (LTL) satisfiability checker
CERN Atlas Athena, a software framework used in the ATLAS experiment at the Large Hadron Collider (LHC) for performance monitoring
KAMERA: a platform for synchronized data collection and real-time deep learning to map marine species like polar bears and seals, aiding Arctic ecosystem research
KiCad: a free and open-source software suite for electronic design automation
MeVisLab: a software framework for medical image processing and visualization.
OpenPMD API: a versatile programming interface for accessing and managing scientific data, designed to facilitate the efficient storage, retrieval, and sharing of simulation data across various applications and platforms
ParaView: an open-source tool for large-scale data visualization and analysis across various scientific domains
QGIS: a free and open-source geographic information system (GIS) application that allows users to create, edit, visualize, and analyze geospatial data across a variety of formats
VTK: a software library for 3D computer graphics, image processing, and visualization
VolView: a lightweight application for interactive visualization and analysis of 3D medical imaging data.
"},{"location":"home/customers/#business-and-productivity-software","title":"Business and Productivity Software","text":"
ArcGIS PRO, a desktop geographic information system (GIS) application developed by Esri for mapping and spatial analysis
Autodesk Desktop, a software platform developed by Autodesk for creating and managing desktop applications and services
Check Point: a cybersecurity company specializing in threat prevention and network security solutions, offering a range of products designed to protect enterprises from cyber threats and ensure data integrity
Microsoft Office for Mac, a suite of productivity applications developed by Microsoft for macOS, including tools for word processing, spreadsheets, and presentations
Nexthink Infinity: a digital employee experience management platform for monitoring and improving IT performance
Sophos Connect Client: a secure VPN client from Sophos that allows remote users to connect to their corporate network, ensuring secure access to resources and data
Stonebranch: a cloud-based cybersecurity solution that integrates backup, disaster recovery, and cybersecurity features to protect data and ensure business continuity for organizations
Tablecruncher: a data analysis tool that allows users to import, analyze, and visualize spreadsheet data, offering interactive features for better insights and decision-making
magicplan, a mobile application for creating floor plans and interior designs using augmented reality
"},{"location":"home/customers/#databases-and-big-data","title":"Databases and Big Data","text":"
ADIOS2: a data management framework designed for high-performance input and output operations
Cribl Stream: a real-time data processing platform that enables organizations to collect, route, and transform observability data, enhancing visibility and insights into their systems
DB Browser for SQLite, a visual open-source tool for creating, designing, and editing SQLite database files
MySQL Connector/C++, a C++ library for connecting and interacting with MySQL databases
MySQL NDB Cluster, a distributed database system that provides high availability and scalability for MySQL databases
PrestoDB, a distributed SQL query engine designed for large-scale data analytics, originally developed by Facebook
ROOT Data Analysis Framework, an open-source data analysis framework widely used in high-energy physics and other fields for data processing and visualization
"},{"location":"home/customers/#simulation-and-modeling","title":"Simulation and Modeling","text":"
Arcturus HoloSuite, a software toolset for capturing, editing, and streaming volumetric video, featuring advanced compression technologies for high-quality 3D content creation
azul, a fast and efficient 3D city model viewer designed for visualizing urban environments and spatial data
Blender, a free and open-source 3D creation suite for modeling, animation, rendering, and more
cpplot, a library for creating interactive graphs and charts in C++, which can be viewed in web browsers
NVIDIA Omniverse, a platform for 3D content creation and collaboration that enables real-time simulations and interactive experiences across various industries
Pixar Renderman, a photorealistic 3D rendering software developed by Pixar, widely used in the film industry for creating high-quality visual effects and animations
ROS - Robot Operating System, a set of software libraries and tools that assist in developing robot applications
UBS, a multinational financial services and banking company
GAMS: a high-performance mathematical modeling system for optimization and decision support
M-Star: a computational fluid dynamics software for simulating and analyzing fluid flow
MapleSim CAD Toolbox: a software extension for MapleSim that integrates CAD models, allowing users to import, manipulate, and analyze 3D CAD data within the MapleSim environment for enhanced modeling and simulation
Kitware SMTK: a software toolkit for managing simulation models and workflows in scientific and engineering applications
"},{"location":"home/customers/#enterprise-and-cloud-applications","title":"Enterprise and Cloud Applications","text":"
Acronis Cyber Protect Cloud: an all-in-one data protection solution that combines backup, disaster recovery, and cybersecurity to safeguard business data from threats like ransomware
Baereos: a backup solution that provides data protection and recovery options for various environments, including physical and virtual systems
Bitdefender Home Scanner, a tool from Bitdefender that scans devices for malware and security threats, providing a safeguard against potential online dangers
Citrix Provisioning: a solution that streamlines the delivery of virtual desktops and applications by allowing administrators to manage and provision resources efficiently across multiple environments
Citrix Virtual Apps and Desktops, a solution from Citrix that delivers virtual apps and desktops
Cyberarc: a security solution that specializes in privileged access management, enabling organizations to control and monitor access to critical systems and data, thereby enhancing overall cybersecurity posture
Elster: a digital platform developed by German tax authorities for secure and efficient electronic tax filing and management using secunet protect4use
Egnyte Desktop: a secure cloud storage solution designed for businesses, enabling file sharing, collaboration, and data management across teams while ensuring compliance and data protection
Ethereum Solidity, a high-level, object-oriented programming language designed for implementing smart contracts on the Ethereum platform
Inciga: a monitoring tool for IT infrastructure, designed to provide insights into system performance and availability through customizable dashboards and alerts
Intel Accelerator Management Daemon for VMware ESXi: a management tool designed for monitoring and controlling Intel hardware accelerators within VMware ESXi environments, optimizing performance and resource allocation
Juniper Identity Management Service
Microsoft Azure IoT SDK, a collection of tools and libraries to help developers connect, build, and deploy Internet of Things (IoT) solutions on the Azure cloud platform
Microsoft WinGet, a command-line utility included in the Windows Package Manager
Pointr: a platform for indoor positioning and navigation solutions, offering tools and SDKs for developers to create location-based applications
secunet protect4use: a secure, passwordless multi-factor authentication solution that transforms smartphones into digital keyrings, ensuring high security for online services and digital identities
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.
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.
Example
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
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.
[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.
This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.
Exceptions have ids 1xx.
Byte index
Member byte holds the byte index of the last read character in the input file.
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).
Example
The following code shows how a parse_error exception can be caught.
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
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
Make sure the input is correctly read. Try to write the input to standard output to check if, for instance, the input file was successfully opened.
Paste the input to a JSON validator like http://jsonlint.com or a tool like jq.
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.
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
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
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
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
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
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
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
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
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
This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx.
Example
The following code shows how a type_error exception can be caught.
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
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
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
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
The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON)
Example messages
Serializing null to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n
Serializing [1,2,3] to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n
Tip
Encapsulate the JSON value in an object. That is, instead of serializing true, serialize {\"value\": true}
"},{"location":"home/exceptions/#out-of-range","title":"Out of range","text":"
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx.
Example
The following code shows how an out_of_range exception can be caught.
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.
This exception previously indicated that the UBJSON and BSON binary formats did not support integer numbers greater than 9223372036854775807 due to limitations in the implemented mapping. However, these limitations have since been resolved, and this exception no longer occurs.
Exception cannot occur any more
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers.
Since version 3.12.0, integer numbers beyond int64 are serialized as uint64 BSON numbers.
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.
Why is the parser complaining about a Chinese character?
Does the library support Unicode?
I get an exception [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:
Only UTF-8 encoded input is supported which is the default encoding for JSON according to RFC 8259.
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.
Other encodings such as Latin-1 or ISO 8859-1 are not supported and will yield parse or serialization errors.
Unicode noncharacters will not be replaced by the library.
Invalid surrogates (e.g., incomplete pairs such as \\uDEAD) will yield parse errors.
The strings stored in the library are UTF-8 encoded. When using the default string type (std::string), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.
When you store strings with different encodings in the library, calling 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/#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.
It seems that precision is lost when serializing a double.
Can I change the precision for floating-point serialization?
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.
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.
Why do I get a compilation error 'to_string' is not a member of 'std' (or similarly, for strtod or strtof)?
Why does the code not compile with MinGW or Android SDK?
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.
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.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
Fixed a bug that lead to stack overflow for deeply nested JSON values (objects, array) by changing the implementation of the destructor from a recursive to an iterative approach. #832, #1419, #1835
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.
Add overload of the contains function to check if a JSON pointer is valid without throwing exceptions, just like its counterpart for object keys. #1600
Add a function to_string to allow for generic conversion to strings. #916 #1585
Add return value for the emplace_back function, returning a reference to the added element just like C++17 is introducing this for std::vector. #1609
Add info how to use the library with the pacman package manager on MSYS2. #1670
Use GNUInstallDirs to set library install directories. #1673
Fix links in the README. #1620 #1621 #1622 #1623 #1625
Mention json type on the documentation start page. #1616
Complete documentation of value() function with respect to type_error.302 exception. #1601
Fix links in the documentation. #1598
Add regression tests for MSVC. #1543 #1570
Use CircleCI for continuous integration.
Use Doozer for continuous integration on Linux (CentOS, Raspbian, Fedora)
Add tests to check each CMake flag (JSON_BuildTests, JSON_Install, JSON_MultipleHeaders, JSON_Sanitizer, JSON_Valgrind, JSON_NoExceptions, JSON_Coverage).
Use Hedley to avoid re-inventing several compiler-agnostic feature macros like 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.
Build and run tests on AppVeyor in DEBUG and RELEASE mode.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
Overworked the public interface for JSON Pointers. The creation of JSON Pointers is simplified with operator/ and operator/=. JSON Pointers can be inspected with empty, back, and parent_pointer, and manipulated with push_back and pop_back. #1434
Added a boolean method contains to check whether an element exists in a JSON object with a given key. Returns false when called on non-object types. #1471 #1474
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
This release introduces the support for structured bindings and reading from FILE*. Besides, a few bugs have been fixed. All changes are backward-compatible.
Added a warning for implicit conversions to the documentation: It is not recommended to use implicit conversions when reading from a JSON value. Details about this recommendation can be found here. #1363
Fixed typos in the documentation. #1329 #1380 #1382
Fixed a C4800 warning. #1364
Fixed a -Wshadow warning #1346
Wrapped std::snprintf calls to avoid error in MSVC. #1337
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
BSON (Binary JSON) is next to CBOR, MessagePack, and UBJSON the fourth binary (de)serialization format supported by the library.
Adjustable error handlers for invalid Unicode allows to specify the behavior when invalid byte sequences are serialized.
Simplified enum/JSON mapping with a macro in case the default mapping to integers is not desired.
Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.
The library can read and write a subset of BSON (Binary JSON). All data types known from JSON are supported, whereas other types more tied to MongoDB such as timestamps, object ids, or binary data are currently not implemented. See the README for examples. #1244 #1320
The behavior when the library encounters an invalid Unicode sequence during serialization can now be controlled by defining one of three Unicode error handlers: (1) throw an exception (default behavior), (2) replace invalid sequences by the Unicode replacement character (U+FFFD), or (3) ignore/filter invalid sequences. See the documentation of the dump function for examples. #1198 #1314
To easily specify a user-defined enum/JSON mapping, a macro NLOHMANN_JSON_SERIALIZE_ENUM has been introduced. See the README section for more information. #1208 #1323
The diagnosis messages for parse errors have been improved: error messages now indicated line/column positions where possible (in addition to a byte count) and also the context in which the error occurred (e.g., \"while parsing a JSON string\"). Example: error parse 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 #1303
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
The library can now also built with GCC 4.8. Though this compiler does not fully support C++11, it can successfully compile and run the test suite. Note that bug 57824 in GCC 4.8 still forbids to use multiline raw strings in arguments to macros. #1257
Added new function 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 #1231
Added documentation on CMake integration of the library. #1270
Changed the CMake file to use find_package(nlohmann_json) without installing the library. #1202
Improved error messages in case operator[] is used with the wrong combination (json.exception.type_error.305) of JSON container type and argument type. Example: \"cannot use operator[] with a string argument\". #1220 #1221
Added a license and version information to the Meson build file. #1252
Removed static assertions to indicated missing to_json or from_json functions as such assertions do not play well with SFINAE. These assertions also led to problems with GMock. #960 #1212 #1228
The test suite now does not wait forever if run in a wrong directory and input files are not found. #1262
The test suite does not show deprecation warnings for deprecated functions which frequently led to confusion. #1271
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
support to parse from wide string types std::wstring, std::u16string, and std::u32string; the input will be converted to UTF-8 (#1031)
added support for std::string_view when using C++17 (#1028)
allow to roundtrip 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)
improved continuous integration: added builders for Xcode 9.3 and 9.4, added builders for GCC 8 and Clang 6, added builder for MinGW, added builders for MSVC targeting x86
required CMake version is now at least 3.8 (#1040)
overworked CMake file wrt. packaging (#1048)
added package managers: Spack (#1041) and CocoaPods (#1148)
fixed Meson include directory (#1142)
preprocessor macro JSON_SKIP_UNSUPPORTED_COMPILER_CHECK can skip the rejection of unsupported compilers - use at your own risk! (#1128)
preprocessor macro JSON_INTERNAL_CATCH/JSON_INTERNAL_CATCH_USER allows to control the behavior of exception handling inside the library (#1187)
added note on char to JSON conversion
added note how to send security-related issue via encrypted email
removed dependency to std::stringstream (#1117)
added SPDX-License-Identifier
added updated JSON Parsing Test Suite, described in Parsing JSON is a Minefield \ud83d\udca3
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
Fixed a memory leak occurring in the parser callback (#1001).
Different specializations of basic_json (e.g., using different template arguments for strings or objects) can now be used in assignments (#972, #977, #986).
Fixed a logical error in an iterator range check (#992).
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
Fixed parsing of CBOR strings with indefinite length (#961). Earlier versions of this library misinterpreted the CBOR standard and rejected input with the 0x7F start byte.
Fixed user-defined conversion to vector type (#924, #969). A wrong SFINAE check rejected code though a user-defined conversion was provided.
Fixed documentation of the parser behavior for objects with duplicate keys (#963). The exact behavior is not specified by RFC 8259 and the library now also provides no guarantee which object key is stored.
Added check to detect memory overflow when parsing UBJSON containers (#962). The optimized UBJSON format allowed for specifying an array with billions of null elements with a few bytes and the library did not check whether this size exceeded max_size().
Code coverage is now calculated for the individual header files, allowing to find uncovered lines more quickly than by browsing through the single header version (#953, #957).
A Makefile target run_benchmarks was added to quickly build and run the benchmark suite.
The documentation was harmonized with respect to the header inclusion (#955). Now all examples and the README use #include <nlohmann/json.hpp> to allow for selecting single_include or include or whatever installation folder as include directory.
Added note on how to use the library with the cget package manager (#954).
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
The library now supports UBJSON (Universal Binary JSON Specification) as binary format to read and write JSON values space-efficiently. See the documentation overview for a comparison of the different formats CBOR, MessagePack, and UBJSON.
JSON Merge Patch (RFC 7386) offers an intuitive means to describe patches between JSON values (#876, #877). See the documentation of merge_patch for more information.
The library now uses the Grisu2 algorithm for printing floating-point numbers (based on the reference implementation by Florian Loitsch) which produces a short representation which is guaranteed to round-trip (#360, #935, #936).
The UTF-8 handling was further simplified by using the decoder of Bj\u00f6rn Hoehrmann in more scenarios.
Though the library is released as a single header, its development got more and more complicated. With this release, the header is split into several files and the single-header file 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).
The split further allowed for a forward declaration header include/nlohmann/json_fwd.hpp to speed up compilation times (#314).
Google Benchmark is now used for micro benchmarks (see benchmarks folder, #921).
The serialization (JSON and binary formats) now properly work with the libraries string template parameter, allowing for optimized string implementations to be used in constraint environments such as embedded software (#941, #950).
The exceptional behavior can now be overridden by defining macros 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).
To facilitate the interplay with flex and Bison, the library does not use the variable name yytext any more as it could clash with macro definitions (#933).
The library now defines 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).
A compilation error with ICC has been fixed (#947).
Typos and links in the documentation have been fixed (#900, #930).
A compiler error related to incomplete types has been fixed (#919).
The tests form the UTF-8 decoder stress test have been added to the test suite.
Function 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):
The \"copy\" operation of JSON Patch (RFC 6902) requests that it is an error if the target path points into a non-existing array or object (see #894 for a detailed description). This release fixes the implementation to detect such invalid target paths and throw an exception.
An array index in a JSON Pointer (RFC 6901) must be an integer. This release fixes the implementation to throw an exception in case invalid array indices such as 10e2 are used.
Added the JSON Patch tests from Byron Ruth and Mike McCabe.
Fixed the documentation of the at(ptr) function with JSON Pointers to list all possible exceptions (see #888).
Updated the container overview documentation (see #883).
The CMake files now respect the 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):
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.
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.
The library now uses user-defined exceptions instead of re-using those defined in <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).
When strings with a different encoding as UTF-8 were stored in JSON values, their serialization could not be parsed by the library itself, as only UTF-8 is supported. To enforce this library limitation and improve consistency, non-UTF-8 encoded strings now yield a json::type_error exception during serialization (#838). The check for valid UTF-8 is realized with code from Bj\u00f6rn Hoehrmann.
NaN and infinity values can now be stored inside the JSON value without throwing an exception. They are, however, still serialized as null (#388).
The library's iterator tag was changed from RandomAccessIterator to BidirectionalIterator (#593). Supporting RandomAccessIterator was incorrect as it assumed an ordering of values in a JSON objects which are unordered by definition.
The library does not include the standard headers <iostream>, <ctype>, and <stdexcept> any more. You may need to add these headers to code relying on them.
Removed constructor 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):
With all this breaking and deprecation out of the way, let's talk about features!
We improved the diagnostic information for syntax errors (#301). Now, an exception 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.
We added a non-throwing syntax check (#458): The new 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.
An update function was added to merge two JSON objects (#428). In case you are wondering: the name was inspired by Python.
The insert function now also supports an iterator range to add elements to an object.
The binary exchange formats CBOR and MessagePack can now be parsed from input streams and written to output streams (#477).
Input streams are now only read until the end of a JSON value instead of the end of the input (#367).
The serialization function 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).
Added built-in type support for C arrays (#502), 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:
Replaced the re2c generated scanner by a self-coded version which allows for a better modularization of the parser and better diagnostics. To test the new scanner, we added millions (8,860,608 to be exact) of unit tests to check all valid and invalid byte sequences of the Unicode standard.
Google's OSS-Fuzz is still constantly fuzz-testing the library and found several issues that were fixed in this release (#497, #504, #514, #516, #518, #519, #575).
We now also ignore UTF-8 byte order marks when parsing from an iterator range (#602).
Values can be now moved from initializer lists (#663).
Updated to Catch 1.9.7. Unfortunately, Catch2 currently has some performance issues.
The non-exceptional paths of the library are now annotated with __builtin_expect to optimize branch prediction as long as no error occurs.
MSVC now produces a stack trace in MSVC if a 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).
Overworked the documentation and added even more examples.
The build workflow now relies on CMake and CTest. Special flags can be chosen with CMake, including coverage (JSON_Coverage), compilation without exceptions (JSON_NoExceptions), LLVM sanitizers (JSON_Sanitizer), or execution with Valgrind (JSON_Valgrind).
Added support for package managers Meson (#576), Conan (#566), Hunter (#671, #829), and vcpkg (#753).
Added CI builders: Xcode 8.3, 9.0, 9.1, and 9.2; GCC 7.2; Clang 3.8, 3.9, 4.0, and 5.0; Visual Studio 2017. The library is further built with C++17 settings on the latest Clang, GCC, and MSVC version to quickly detect new issues.
"},{"location":"home/releases/#moving-from-2xx-to-300","title":"Moving from 2.x.x to 3.0.0","text":""},{"location":"home/releases/#user-defined-exceptions","title":"User-defined Exceptions","text":"
There are five different exceptions inheriting from json::exception:
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, and
json::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.
"},{"location":"home/releases/#removal-of-deprecated-functions","title":"Removal of deprecated functions","text":"
Function explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) should be replaced by the parse function: Let ss be a stream and cb be a parse callback function.
Old code:
json j(ss, cb);\n
New code:
json j = json::parse(ss, cb);\n
If no callback function is used, also the following code works:
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.
Locales that have a different character than . 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.
Numbers like 1.0 were correctly parsed as floating-point number, but serialized as integer (1). Now, floating-point numbers correctly round trip.
Parsing incorrect JSON numbers with leading 0 (0123) could yield a buffer overflow. This is fixed now by detecting such errors directly by the lexer.
Constructing a JSON value from a pointer was incorrectly interpreted as a Boolean; such code will now yield a compiler error.
Comparing a JSON number with 0 led to a comparison with null. This is fixed now.
All throw calls are now wrapped in macros.
Starting during the preparation of this release (since 8 February 2017), commits and released files are cryptographically signed with this GPG key. Previous releases have also been signed.
The parser for MessagePack and CBOR now supports an optional start index parameter to define a byte offset for the parser.
Some more warnings have been fixed. With Clang, the code compiles without warnings with -Weverything (well, it needs -Wno-documentation-unknown-command and -Wno-deprecated-declarations, but you get the point).
The code can be compiled easier with many Android NDKs by avoiding macros like UINT8_MAX which previously required defining a preprocessor macro for compilation.
The unit tests now compile two times faster.
Cotire is used to speed up the build.
Fixed a lot of typos in the documentation.
Added a section to the README file that lists all used third-party code/tools.
Added a note on constructing a string value vs. parsing.
The test suite now contains 11202597 unit tests.
Improved the Doxygen documentation by shortening the template parameters of class basic_json.
The library now offers an elegant way to convert from and to arbitrary value types. All you need to do is to implement two functions: to_json and from_json. Then, a conversion is as simple as putting a = between variables. See the README for more information and examples.
Exceptions can now be switched off. This can be done by defining the preprocessor symbol JSON_NOEXCEPTION or by passing -fno-exceptions to your compiler. In case the code would usually thrown an exception, abort() is now called.
Information on the library can be queried with the new (static) function meta() which returns a JSON object with information on the version, compiler, and platform. See the documentation for an example.
A bug in the CBOR parser was fixed which led to a buffer overflow.
The function type_name() is now public. It allows to query the type of a JSON value as string.
Added the Big List of Naughty Strings as test case.
Fixed a lot of bugs in the CBOR and MesssagePack parsers. These bugs occurred if invalid input was parsed and then could lead in buffer overflows. These bugs were found with Google's OSS-Fuzz, see #405, #407, #408, #409, #411, and #412 for more information.
We now also use the Doozer continuous integration platform.
The complete test suite is now also run with Clang's address sanitizer and undefined-behavior sanitizer.
Overworked fuzz testing; CBOR and MessagePack implementations are now fuzz-tested. Furthermore, all fuzz tests now include a round trip which ensures created output can again be properly parsed and yields the same JSON value.
Clarified documentation of find() function to always return end() when called on non-object value types.
Moved thirdparty test code to test/thirdparty directory.
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.
The library can now read and write the binary formats CBOR (Concise Binary Object Representation) and MessagePack. Both formats are aimed to produce a very compact representation of JSON which can be parsed very efficiently. See the README file for more information and examples.
simplified the iteration implementation allowing to remove dozens of lines of code
fixed an integer overflow error detected by Google's OSS-Fuzz
suppressed documentation warnings inside the library to facilitate compilation with -Wdocumentation
fixed an overflow detection error in the number parser
updated contribution guidelines to a list of frequentely asked features that will most likely be never added to the library
added a table of contents to the README file to add some structure
mentioned the many examples and the documentation in the README file
split unit tests into individual independent binaries to speed up compilation and testing
The article Parsing JSON is a Minefield \ud83d\udca3 discusses a lot of pitfalls of the JSON specification. When investigating the published test cases, a few bugs in the library were found and fixed:
Files with less than 5 bytes can now be parsed without error.
The library now properly rejects any file encoding other than UTF-8. Furthermore, incorrect surrogate pairs are properly detected and rejected.
The library now accepts all but one \"yes\" test (y_string_utf16.json): UTF-16 is not supported.
The library rejects all but one \"no\" test (n_number_then_00.json): Null bytes are treated as end of file instead of an error. This allows to parse input from null-terminated strings.
The string length passed to a user-defined string literal is now exploited to choose a more efficient constructor.
A few grammar mistakes in the README file have been fixed.
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.
overworked a helper SFINAE function
fixed some documentation issues
fixed the CMake files to allow to run the test suite outside the main project directory
Bug fix: The end of a file stream was not detected properly which led to parse errors. This bug should have been fixed with 2.0.4, but there was still a flaw in the code.
The parser/deserialization functions have been generalized to process any contiguous sequence of 1-byte elements (e.g., 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.
As a general remark on assertions: The library uses assertions to preclude undefined behavior. A prominent example for this is the 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.
In the course of cleaning up the parser/deserialization functions, the constructor 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.
Minor improvements:
Improved the performance of the serialization by avoiding the re-creation of a locale object.
Fixed two MSVC warnings. Compiling the test suite with /Wall now only warns about non-inlined functions (C4710) and the deprecation of the constructor from input-stream (C4996).
Some project internals:
The project has qualified for the Core Infrastructure Initiative Best Practices Badge. While most requirements where already satisfied, some led to a more explicit documentation of quality-ensuring procedures. For instance, static analysis is now executed with every commit on the build server. Furthermore, the contribution guidelines document how to communicate security issues privately.
The test suite has been overworked and split into several files to allow for faster compilation and analysis. The execute the test suite, simply execute make check.
The continuous integration with Travis was extended with Clang versions 3.6.0 to 3.8.1 and now includes 18 different compiler/OS combinations.
An 11-day run of American fuzzy lop checked 962 million inputs on the parser and found no issue.
The parser has been overworked, and a lot of small issues have been fixed:
Improved parser performance by avoiding recursion and using move semantics for the return value.
Unescaped control characters \\x10-\\x1f are not accepted any more.
Fixed a bug in the parser when reading from an input stream.
Improved test case coverage for UTF-8 parsing: now, all valid Unicode code points are tested both escaped and unescaped.
The precision of output streams is now preserved by the parser.
Started to check the code correctness by proving termination of important loops. Furthermore, individual assertions have been replaced by a more systematic function which checks the class invariants. Note that assertions should be switched off in production by defining the preprocessor macro NDEBUG, see the documentation of assert.
A lot of code cleanup: removed unused headers, fixed some compiler warnings, and fixed a build error for Windows-based Clang builds.
Added some compile-time checks:
Unsupported compilers are rejected during compilation with an #error command.
Static assertion prohibits code with incompatible pointer types used in get_ptr().
Improved the documentation, and adjusted the documentation script to choose the correct version of sed.
Replaced a lot of \"raw loops\" by STL functions like 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.
Implemented a value() function for JSON pointers (similar to at function).
The Homebrew formula (see Integration) is now tested for all Xcode builds (6.1 - 8.x) with Travis.
The locale of the output stream (or the internal string stream if a JSON value is serialized to a string) is now adjusted once for the whole serialization instead of for each floating-point number.
The locale of an output stream is now correctly reset to the previous value by the JSON library.
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.
\ud83d\udd1f A JSON value now uses 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.
\ud83d\udc49 JSON Pointer (RFC 6901) support: A JSON Pointer is a string (similar to an XPath expression) to address a value inside a structured JSON value. JSON Pointers can be used in 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().
\ud83c\udfe5 JSON Patch (RFC 6902) support. A JSON Patch is a JSON value that describes the required edit operations (add, change, remove, \u2026) to transform a JSON value into another one. A JSON Patch can be created with function 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.
\ud83c\uddea\ud83c\uddfa The code is now locale-independent: Floating-point numbers are always serialized with a period (.) as decimal separator and ignores different settings from the locale.
\ud83c\udf7a Homebrew support: Install the library with brew tap nlohmann/json && brew install nlohmann_json.
Added constructor to create a JSON value by parsing a std::istream (e.g., std::stringstream or std::ifstream).
Parser error messages are still very vague and contain no information on the error location.
The implemented diff function is rather primitive and does not create minimal diffs.
The name of function iteration_wrapper may change in the future and the function will be deprecated in the next release.
Roundtripping (i.e., parsing a JSON value from a string, serializing it, and comparing the strings) of floating-point numbers is not 100% accurate. Note that RFC 8259 defines no format to internally represent numbers and states not requirement for roundtripping. Nevertheless, benchmarks like Native JSON Benchmark treat roundtripping deviations as conformance errors.
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:
Fixed: Floating-point numbers are now serialized and deserialized properly such that rountripping works in more cases. [#185, #186, #190, #191, #194]
Added: The code now contains assertions to detect undefined behavior during development. As the standard function assert is used, the assertions can be switched off by defining the preprocessor symbol NDEBUG during compilation. [#168]
Added: It is now possible to get a reference to the stored values via the newly added function get_ref(). [#128, #184]
Fixed: Access to object values via keys (operator[]) now works with all kind of string representations. [#171, #189]
Fixed: The code now compiles again with Microsoft Visual Studio 2015. [#144, #167, #188]
Fixed: All required headers are now included.
Fixed: Typos and other small issues. [#162, #166, #175, #177, #179, #180]
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.
Changed: A UTF-8 byte order mark is silently ignored.
Changed: sprintf is no longer used.
Changed: iterator_wrapper also works for const objects; note: the name may change!
Changed: Error messages during deserialization have been improved.
Added: The parse function now also works with type std::istream&&.
Added: Function 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.
Added: Public functions are tagged with the version they were introduced. This shall allow for better versioning in the future.
Added: All public functions and types are documented (see http://nlohmann.github.io/json/doxygen/) including executable examples.
Added: Allocation of all types (in particular arrays, strings, and objects) is now exception-safe.
Added: They descriptions of thrown exceptions have been overworked and are part of the tests suite and documentation.
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.txt
cmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\nfind_package(nlohmann_json 3.11.3 REQUIRED)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n
The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.
To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.
Example
CMakeLists.txt
cmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\n# If you only include this third party in PRIVATE source files, you do not need to install it\n# when your main project gets installed.\nset(JSON_Install OFF CACHE INTERNAL \"\")\n\nadd_subdirectory(nlohmann_json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n
Note
Do not use include(nlohmann_json/CMakeLists.txt), since that carries with it unintended consequences that will break the build. It is generally discouraged (although not necessarily well documented as such) to use include(...) for pulling in other CMake projects anyways.
To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.
Example
CMakeLists.txt
project(ExampleProject LANGUAGES CXX)\n\noption(EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF)\n\nadd_subdirectory(thirdparty)\n\nadd_executable(example example.cpp)\n\n# Note that the namespaced target will always be available regardless of the import method\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n
thirdparty/CMakeLists.txt
if(EXAMPLE_USE_EXTERNAL_JSON)\n find_package(nlohmann_json 3.11.3 REQUIRED)\nelse()\n set(JSON_BuildTests OFF CACHE INTERNAL \"\")\n add_subdirectory(nlohmann_json)\nendif()\n
thirdparty/nlohmann_json is then a complete copy of this source tree.
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.
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.
Enable the (incorrect) legacy comparison behavior of discarded JSON values by defining macro JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON. This option is OFF by default.
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.
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.
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}).
DeprecatedFuture-proof
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_pointerp with a string s, convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!=.
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.
DeprecatedFuture-proof
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.
DeprecatedFuture-proof
using my_json = nlohmann::basic_json<std::map, std::vector, my_string_type>;\nnlohmann::json_pointer<my_json> 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.
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.
DeprecatedFuture-proof
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.
Implicit conversions via operator ValueType will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get, get_to, get_ref, or get_ptr.
DeprecatedFuture-proofFuture-proof (alternative)
nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n
nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
"},{"location":"integration/migration_guide/#import-namespace-literals-for-udls","title":"Import namespace literals for UDLs","text":"
The user-defined string literals operator\"\"_json and operator\"\"_json_pointer will be removed from the global namespace in the next major release of the library.
DeprecatedFuture-proof
nlohmann::json j = \"[1,2,3]\"_json;\n
using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n
To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.
"},{"location":"integration/migration_guide/#do-not-hard-code-the-complete-library-namespace","title":"Do not hard-code the complete library namespace","text":"
The nlohmann namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use nlohmann as namespace or, when the exact version and configuration is relevant, use macro NLOHMANN_JSON_NAMESPACE to denote the namespace.
"},{"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.
Availalbe versions: current version and select older versions (see WrapDB)
The package is update automatically from file meson.build.
File issues at the library issue tracker
Meson website
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 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, 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.
use bazel_dep, git_override, or local_path_override
Any version, that is available via Bazel Central Registry
File issues at the library issue tracker
Bazel website
This repository provides a Bazel MODULE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced within a MODULE.bazel by rules such as archive_override, git_override, or local_path_override. To use the library you need to depend on the target @nlohmann_json//:json (i.e., via deps attribute).
Example
Create the following files:
BUILD
cc_binary(\n name = \"main\",\n srcs = [\"example.cpp\"],\n deps = [\"@nlohmann_json//:json\"],\n)\n
WORKSPACE
bazel_dep(name = \"nlohmann_json\", version = \"3.11.3.bcr.1\")\n
Availalbe versions: current version and older versions (see Conan Center)
The package is update automatically via this recipe.
File issues at the Conan Center issue tracker
Conan website
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.
Availalbe versions: current version and older versions
The package is updated with every release.
File issues at the cget issue tracker
cget website
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).
If you are using NuGet, you can use the package nlohmann.json with
dotnet add package nlohmann.json\n
Example
Probably the easiest way to use NuGet packages is through Visual Studio graphical interface. Just right-click on a project (any C++ project would do) in \u201cSolution Explorer\u201d and select \u201cManage NuGet Packages\u2026\u201d
Now you can click on \u201cBrowse\u201d tab and find the package you like to install.
Most of the packages in NuGet gallery are .NET packages and would not be useful in a C++ project. Microsoft recommends adding \u201cnative\u201d and \u201cnativepackage\u201d tags to C++ NuGet packages to distinguish them, but even adding \u201cnative\u201d to search query would still show many .NET-only packages in the list.
Nevertheless, after finding the package you want, click on \u201cInstall\u201d button and accept confirmation dialogs. After the package is successfully added to the projects, you should be able to build and execute the project without the need for making any more changes to build settings.
Note
A few notes:
NuGet packages are installed per project and not system-wide. The header and binaries for the package are only available to the project it is added to, and not other projects (obviously unless we add the package to those projects as well)
One of the many great things about your elegant work is that it is a header-only library, which makes deployment very straightforward. In case of libraries which need binary deployment (.lib, .dll and .pdb for debug info) the different binaries for each supported compiler version must be added to the NuGet package. Some library creators cram binary versions for all supported Visual C++ compiler versions in the same package, so a single package will support all compilers. Some others create a different package for each compiler version (and you usually see things like \u201cv140\u201d or \u201cvc141\u201d in package name to clarify which VC++ compiler this package supports).
Packages can have dependency to other packages, and in this case, NuGet will install all dependencies as well as the requested package recursively.
What happens behind the scenes
After you add a NuGet package, three changes occur in the project source directory. Of course, we could make these changes manually instead of using GUI:
A packages.config file will be created (or updated to include the package name if one such file already exists). This file contains a list of the packages required by this project (name and minimum version) and must be added to the project source code repository, so if you move the source code to a new machine, MSBuild/NuGet knows which packages it has to restore (which it does automatically before each build).
A packages folder which contains actual files in the packages (these are header and binary files required for a successful build, plus a few metadata files). In case of this library for example, it contains json.hpp:
Note
This directory should not be added to the project source code repository, as it will be restored before each build by MSBuild/NuGet. If you go ahead and delete this folder, then build the project again, it will magically re-appear!
Project MSBuild makefile (which for Visual C++ projects has a .vcxproj extension) will be updated to include settings from the package.
The important bit for us here is line 170, which tells MSBuild to import settings from packages\\nlohmann.json.3.5.0\\build\\native\\nlohmann.json.targets file. This is a file the package creator created and added to the package (you can see it is one of the two files I created in this repository, the other just contains package attributes like name and version number). What does it contain?
For our header-only repository, the only setting we need is to add our include directory to the list of AdditionalIncludeDirectories:
For libraries with binary files, we will need to add .lib files to linker inputs and add settings to copy .dll and other redistributable files to output directory, if needed.
There are other changes to the makefile as well:
Lines 165-167 add the packages.config as one of project files (so it is shown in Solution Explorer tree view). It is added as None (no build action) and removing it wouldn\u2019t affect build.
Lines 172-177 check to ensure the required packages are present. This will display a build error if package directory is empty (for example when NuGet cannot restore packages because Internet connection is down). Again, if you omit this section, the only change in build would be a more cryptic error message if build fails.
Note
Changes to .vcxproj makefile should also be added to project source code repository.
As you can see, the mechanism NuGet uses to modify project settings is through MSBuild makefiles, so using NuGet with other build systems and compilers (like CMake) as a dependency manager is either impossible or more problematic than useful.
Please refer to this extensive description for more information.
If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, 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.
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, 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.
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.
Warning
The module is outdated as the respective pod has not been updated in years.
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.
Warning
The package manager is outdated as the respective repository has not been updated in years.
"}]}
\ 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.
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":"
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;.
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:
This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS for details.
"},{"location":"api/operator_literal_json/#parameters","title":"Parameters","text":"s (in) a string representation of a JSON object n (in) length of string s"},{"location":"api/operator_literal_json/#return-value","title":"Return value","text":"
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:
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":"
std::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)\n
Serialize the given JSON value j to the output stream o. The JSON value will be serialized using the dump member function.
The indentation of the output can be controlled with the member variable width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).
The indentation character can be controlled with the member variable fill of the output stream o. For instance, the manipulator std::setfill('\\\\t') sets indentation to use a tab character rather than the default space character.
Write a string representation of the given JSON pointer ptr to the output stream o. The string representation is obtained using the to_string member function.
"},{"location":"api/operator_ltlt/#parameters","title":"Parameters","text":"o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write"},{"location":"api/operator_ltlt/#return-value","title":"Return value","text":"
Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded. Note that unlike the dump member functions, no error_handler can be set.
Function std::ostream& operator<<(std::ostream& o, const basic_json& j) replaces function std::ostream& operator>>(const basic_json& j, std::ostream& o) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o; with o << j;.
"},{"location":"api/operator_ltlt/#examples","title":"Examples","text":"Example: (1) serialize JSON value to stream
The example below shows the serialization with different parameters to width to adjust the indentation level.
Added in version 1.0.0. Added support for indentation character and deprecated std::ostream& operator>>(const basic_json& j, std::ostream& o) in version 3.0.0.
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.
template<class Key, class T, class IgnoredLess = std::less<Key>,\n class Allocator = std::allocator<std::pair<const Key, T>>>\nstruct ordered_map : std::vector<std::pair<const Key, T>, Allocator>;\n
A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json (nlohmann::basic_json<ordered_map>).
"},{"location":"api/ordered_map/#template-parameters","title":"Template parameters","text":"Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std::map) Allocator allocator type"},{"location":"api/ordered_map/#iterator-invalidation","title":"Iterator invalidation","text":"
The type uses a std::vector to store object elements. Therefore, adding elements can yield a reallocation in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
This function is usually called by the get() function of the basic_json class (either explicitly or via the conversion operators).
This function is chosen for default-constructible value types.
This function is chosen for value types which are not default-constructible.
"},{"location":"api/adl_serializer/from_json/#parameters","title":"Parameters","text":"j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"
Copy of the JSON value, converted to ValueType
"},{"location":"api/adl_serializer/from_json/#examples","title":"Examples","text":"Example: (1) Default-constructible type
The example below shows how a from_json function can be implemented for a user-defined type. This function is called by the adl_serializer when template get<ns::person>() is called.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid from_json(const json& j, person& p)\n{\n j.at(\"name\").get_to(p.name);\n j.at(\"address\").get_to(p.address);\n j.at(\"age\").get_to(p.age);\n}\n} // namespace ns\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n
Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n
Example: (2) Non-default-constructible type
The example below shows how a from_json is implemented as part of a specialization of the adl_serializer to realize the conversion of a non-default-constructible type.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n person(std::string n, std::string a, int aa)\n : name(std::move(n)), address(std::move(a)), age(aa)\n {}\n\n std::string name;\n std::string address;\n int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n static ns::person from_json(const json& j)\n {\n return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert person to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, ns::person p)\n {\n j[\"name\"] = p.name;\n j[\"address\"] = p.address;\n j[\"age\"] = p.age;\n }\n};\n} // namespace nlohmann\n\nint main()\n{\n json j;\n j[\"name\"] = \"Ned Flanders\";\n j[\"address\"] = \"744 Evergreen Terrace\";\n j[\"age\"] = 60;\n\n auto p = j.template get<ns::person>();\n\n std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n
Output:
Ned Flanders (60) lives in 744 Evergreen Terrace\n
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.
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_tArrayType type for JSON arrays array_tStringType type for JSON strings and object keys string_tBooleanType type for JSON booleans boolean_tNumberIntegerType type for JSON integer numbers number_integer_tNumberUnsignedType type for JSON unsigned integer numbers number_unsigned_tNumberFloatType type for JSON floating-point numbers number_float_tAllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json()json_serializerBinaryType type for binary arrays binary_tCustomBaseClass extension point for user code json_base_class_t"},{"location":"api/basic_json/#specializations","title":"Specializations","text":"
json - default specialization
ordered_json - specialization that maintains the insertion order of object keys
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.
StandardLayoutType: JSON values have standard layout: All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes.
exception - general exception of the basic_json class
parse_error - exception indicating a parse error
invalid_iterator - exception indicating errors with iterators
type_error - exception indicating executing a member function with a wrong type
out_of_range - exception indicating access out of the defined range
other_error - exception indicating other library errors
"},{"location":"api/basic_json/#container-types","title":"Container types","text":"Type Definition value_typebasic_jsonreferencevalue_type&const_referenceconst value_type&difference_typestd::ptrdiff_tsize_typestd::size_tallocator_typeAllocatorType<basic_json>pointerstd::allocator_traits<allocator_type>::pointerconst_pointerstd::allocator_traits<allocator_type>::const_pointeriterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iteratorconst_reverse_iterator reverse iterator, derived from const_iteratoriteration_proxy helper type for items function"},{"location":"api/basic_json/#json-value-data-types","title":"JSON value data types","text":"
array_t - type for arrays
binary_t - type for binary arrays
boolean_t - type for booleans
default_object_comparator_t - default comparator for objects
number_float_t - type for numbers (floating-point)
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.
a pointer to a null-terminated string of single byte characters (throws if null)
a std::string
an object obj for which begin(obj) and end(obj) produces a valid pair of iterators.
IteratorType
a compatible iterator type, for instance.
a pair of std::string::iterator or std::vector<std::uint8_t>::iterator
a pair of pointers such as ptr and ptr + len
"},{"location":"api/basic_json/accept/#parameters","title":"Parameters","text":"i (in) Input to parse from. ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/accept/#return-value","title":"Return value","text":"
Ignoring comments via ignore_comments added in version 3.9.0.
Changed runtime assertion in case of 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.
Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.
"},{"location":"api/basic_json/array/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an array from (optional)"},{"location":"api/basic_json/array/#return-value","title":"Return value","text":"
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:
creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys
creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n
The type used to store JSON arrays.
RFC 8259 describes JSON arrays as follows:
An array is an ordered sequence of zero or more values.
To store objects in C++, a type is defined by the template parameters explained below.
"},{"location":"api/basic_json/array_t/#template-parameters","title":"Template parameters","text":"ArrayType container type to store arrays (e.g., std::vector or std::list) AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/array_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/array_t/#default-type","title":"Default type","text":"
With the default values for ArrayType (std::vector) and AllocatorType (std::allocator), the default value for array_t is:
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.
Returns a reference to the array element at specified location idx, with bounds checking.
Returns a reference to the object element with specified key key, with bounds checking.
See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
Returns a reference to the element at specified JSON pointer ptr, with bounds checking.
"},{"location":"api/basic_json/at/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/at/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the elements to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/at/#return-value","title":"Return value","text":"
Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.
Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See example below.
The function can throw the following exceptions:
Throws type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.
Throws out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See example below.
See 2.
The function can throw the following exceptions:
Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See example below.
Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See example below.
Throws out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See example below.
Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.
Throws out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below.
Throws out_of_range.404 if the JSON pointer ptr can not be resolved. See example below.
"},{"location":"api/basic_json/at/#examples","title":"Examples","text":"Example: (1) access specified array element with bounds checking
The example below shows how array elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n\n // change element at index 1 (second element) to \"second\"\n array.at(1) = \"second\";\n\n // output changed array\n std::cout << array << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-array type\n json str = \"I am a string\";\n str.at(0) = \"Another string\";\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to write beyond the array limit\n array.at(5) = \"sixth\";\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n
Output:
\"third\"\n[\"first\",\"second\",\"third\",\"fourth\"]\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n
Example: (1) access specified array element with bounds checking
The example below shows how array elements can be read using at(). It also demonstrates the different exceptions that can be thrown.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON array\n const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n // output element at index 2 (third element)\n std::cout << array.at(2) << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-array type\n const json str = \"I am a string\";\n std::cout << str.at(0) << '\\n';\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to read beyond the array limit\n std::cout << array.at(5) << '\\n';\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}\n
Output:
\"third\"\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n
Example: (2) access specified object element with bounds checking
The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.
\"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.
\"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
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.
Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:
Value type initial value null null boolean false string \"\" number 0 object {} array [] binary empty array
The postcondition of this constructor can be restored by calling clear().
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:
arrays: array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.
objects: object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.
strings: string_t, string literals, and all compatible string containers can be used.
numbers: number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.
boolean: boolean_t / bool can be used.
binary: binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type.
See the examples below.
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:
If the list is empty, an empty JSON object value {} is created.
If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values.
In all other cases, an array is created.
The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
The empty initializer list is written as {} which is exactly an empty JSON object.
C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object.
In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe.
With the rules described above, the following JSON values cannot be expressed by an initializer list:
the empty array ([]): use array(initializer_list_t) with an empty initializer list in this case
arrays whose elements satisfy rule 2: use array(initializer_list_t) with the same initializer list in this case
Function array() and object() force array and object creation from initializer lists, respectively.
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:
In case of a null type, invalid_iterator.206 is thrown.
In case of other primitive types (number, boolean, or string), first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.
In case of structured types (array, object), the constructor behaves as similar versions for std::vector or std::map; that is, a JSON array or object is constructed from the values in the range.
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 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&&) method
BasicJsonType:
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":"
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
No-throw guarantee: this constructor never throws exceptions.
Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
Depends on the called constructor. For types directly supported by the library (i.e., all types for which no to_json() function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
No-throw guarantee: this constructor never throws exceptions.
Throws type_error.301 if type_deduction is false, manual_type is value_t::object, but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true, an array would have been created. See object(initializer_list_t) for an example.
(none)
The function can throw the following exceptions:
Throws invalid_iterator.201 if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.
Throws invalid_iterator.204 if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element anymore. In this case, the range [first, last) is undefined. See example code below.
Throws invalid_iterator.206 if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.
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
Iterators first and last must be initialized. **This precondition is enforced with a runtime assertion.
Range [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 value
"},{"location":"api/basic_json/basic_json/#examples","title":"Examples","text":"Example: (1) create an empty value with a given type
The following code shows the constructor for different value_t values.
Example: (3) create a JSON value from compatible types
The following code shows the constructor with several compatible types.
#include <iostream>\n#include <deque>\n#include <list>\n#include <forward_list>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <valarray>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // ============\n // object types\n // ============\n\n // create an object from an object_t value\n json::object_t object_value = { {\"one\", 1}, {\"two\", 2} };\n json j_object_t(object_value);\n\n // create an object from std::map\n std::map<std::string, int> c_map\n {\n {\"one\", 1}, {\"two\", 2}, {\"three\", 3}\n };\n json j_map(c_map);\n\n // create an object from std::unordered_map\n std::unordered_map<const char*, double> c_umap\n {\n {\"one\", 1.2}, {\"two\", 2.3}, {\"three\", 3.4}\n };\n json j_umap(c_umap);\n\n // create an object from std::multimap\n std::multimap<std::string, bool> c_mmap\n {\n {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n };\n json j_mmap(c_mmap); // only one entry for key \"three\" is used\n\n // create an object from std::unordered_multimap\n std::unordered_multimap<std::string, bool> c_ummap\n {\n {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n };\n json j_ummap(c_ummap); // only one entry for key \"three\" is used\n\n // serialize the JSON objects\n std::cout << j_object_t << '\\n';\n std::cout << j_map << '\\n';\n std::cout << j_umap << '\\n';\n std::cout << j_mmap << '\\n';\n std::cout << j_ummap << \"\\n\\n\";\n\n // ===========\n // array types\n // ===========\n\n // create an array from an array_t value\n json::array_t array_value = {\"one\", \"two\", 3, 4.5, false};\n json j_array_t(array_value);\n\n // create an array from std::vector\n std::vector<int> c_vector {1, 2, 3, 4};\n json j_vec(c_vector);\n\n // create an array from std::valarray\n std::valarray<short> c_valarray {10, 9, 8, 7};\n json j_valarray(c_valarray);\n\n // create an array from std::deque\n std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};\n json j_deque(c_deque);\n\n // create an array from std::list\n std::list<bool> c_list {true, true, false, true};\n json j_list(c_list);\n\n // create an array from std::forward_list\n std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};\n json j_flist(c_flist);\n\n // create an array from std::array\n std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};\n json j_array(c_array);\n\n // create an array from std::set\n std::set<std::string> c_set {\"one\", \"two\", \"three\", \"four\", \"one\"};\n json j_set(c_set); // only one entry for \"one\" is used\n\n // create an array from std::unordered_set\n std::unordered_set<std::string> c_uset {\"one\", \"two\", \"three\", \"four\", \"one\"};\n json j_uset(c_uset); // only one entry for \"one\" is used\n\n // create an array from std::multiset\n std::multiset<std::string> c_mset {\"one\", \"two\", \"one\", \"four\"};\n json j_mset(c_mset); // both entries for \"one\" are used\n\n // create an array from std::unordered_multiset\n std::unordered_multiset<std::string> c_umset {\"one\", \"two\", \"one\", \"four\"};\n json j_umset(c_umset); // both entries for \"one\" are used\n\n // serialize the JSON arrays\n std::cout << j_array_t << '\\n';\n std::cout << j_vec << '\\n';\n std::cout << j_valarray << '\\n';\n std::cout << j_deque << '\\n';\n std::cout << j_list << '\\n';\n std::cout << j_flist << '\\n';\n std::cout << j_array << '\\n';\n std::cout << j_set << '\\n';\n std::cout << j_uset << '\\n';\n std::cout << j_mset << '\\n';\n std::cout << j_umset << \"\\n\\n\";\n\n // ============\n // string types\n // ============\n\n // create string from a string_t value\n json::string_t string_value = \"The quick brown fox jumps over the lazy dog.\";\n json j_string_t(string_value);\n\n // create a JSON string directly from a string literal\n json j_string_literal(\"The quick brown fox jumps over the lazy dog.\");\n\n // create string from std::string\n std::string s_stdstring = \"The quick brown fox jumps over the lazy dog.\";\n json j_stdstring(s_stdstring);\n\n // serialize the JSON strings\n std::cout << j_string_t << '\\n';\n std::cout << j_string_literal << '\\n';\n std::cout << j_stdstring << \"\\n\\n\";\n\n // ============\n // number types\n // ============\n\n // create a JSON number from number_integer_t\n json::number_integer_t value_integer_t = -42;\n json j_integer_t(value_integer_t);\n\n // create a JSON number from number_unsigned_t\n json::number_integer_t value_unsigned_t = 17;\n json j_unsigned_t(value_unsigned_t);\n\n // create a JSON number from an anonymous enum\n enum { enum_value = 17 };\n json j_enum(enum_value);\n\n // create values of different integer types\n short n_short = 42;\n int n_int = -23;\n long n_long = 1024;\n int_least32_t n_int_least32_t = -17;\n uint8_t n_uint8_t = 8;\n\n // create (integer) JSON numbers\n json j_short(n_short);\n json j_int(n_int);\n json j_long(n_long);\n json j_int_least32_t(n_int_least32_t);\n json j_uint8_t(n_uint8_t);\n\n // create values of different floating-point types\n json::number_float_t v_ok = 3.141592653589793;\n json::number_float_t v_nan = NAN;\n json::number_float_t v_infinity = INFINITY;\n\n // create values of different floating-point types\n float n_float = 42.23;\n float n_float_nan = 1.0f / 0.0f;\n double n_double = 23.42;\n\n // create (floating point) JSON numbers\n json j_ok(v_ok);\n json j_nan(v_nan);\n json j_infinity(v_infinity);\n json j_float(n_float);\n json j_float_nan(n_float_nan);\n json j_double(n_double);\n\n // serialize the JSON numbers\n std::cout << j_integer_t << '\\n';\n std::cout << j_unsigned_t << '\\n';\n std::cout << j_enum << '\\n';\n std::cout << j_short << '\\n';\n std::cout << j_int << '\\n';\n std::cout << j_long << '\\n';\n std::cout << j_int_least32_t << '\\n';\n std::cout << j_uint8_t << '\\n';\n std::cout << j_ok << '\\n';\n std::cout << j_nan << '\\n';\n std::cout << j_infinity << '\\n';\n std::cout << j_float << '\\n';\n std::cout << j_float_nan << '\\n';\n std::cout << j_double << \"\\n\\n\";\n\n // =============\n // boolean types\n // =============\n\n // create boolean values\n json j_truth = true;\n json j_falsity = false;\n\n // serialize the JSON booleans\n std::cout << j_truth << '\\n';\n std::cout << j_falsity << '\\n';\n}\n
Output:
{\"one\":1,\"two\":2}\n{\"one\":1,\"three\":3,\"two\":2}\n{\"one\":1.2,\"three\":3.4,\"two\":2.3}\n{\"one\":true,\"three\":false,\"two\":true}\n{\"one\":true,\"three\":false,\"two\":true}\n\n[\"one\",\"two\",3,4.5,false]\n[1,2,3,4]\n[10,9,8,7]\n[1.2,2.3,3.4,5.6]\n[true,true,false,true]\n[12345678909876,23456789098765,34567890987654,45678909876543]\n[1,2,3,4]\n[\"four\",\"one\",\"three\",\"two\"]\n[\"four\",\"three\",\"two\",\"one\"]\n[\"four\",\"one\",\"one\",\"two\"]\n[\"four\",\"two\",\"one\",\"one\"]\n\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\n-42\n17\n17\n42\n-23\n1024\n-17\n8\n3.141592653589793\nnull\nnull\n42.22999954223633\nnull\n23.42\n\ntrue\nfalse\n
Note the output is platform-dependent.
Example: (5) create a container (array or object) from an initializer list
The example below shows how JSON values are created from initializer lists.
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
#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
Creates a JSON binary array value from a given binary container.
Creates a JSON binary array value from a given binary container with subtype.
Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
"},{"location":"api/basic_json/binary/#parameters","title":"Parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON"},{"location":"api/basic_json/binary/#return-value","title":"Return value","text":"
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.
using binary_t = byte_container_with_subtype<BinaryType>;\n
This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
Additionally, as an implementation detail, the subtype of the binary data is carried around as a std::uint64_t, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to BinaryType via the helper type byte_container_with_subtype.
CBOR's RFC 7049 describes this type as:
Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).
MessagePack's documentation on the bin type family describes this type as:
Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.
BSON's specifications describe several binary types; however, this type is intended to represent the generic binary type which has the description:
Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.
None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.
The default representation of this binary format is a std::vector<std::uint8_t>, which is a very common way to represent a byte array in modern C++.
"},{"location":"api/basic_json/binary_t/#template-parameters","title":"Template parameters","text":"BinaryType container type to store arrays"},{"location":"api/basic_json/binary_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/binary_t/#default-type","title":"Default type","text":"
The default values for BinaryType is std::vector<std::uint8_t>.
Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t* must be dereferenced.
"},{"location":"api/basic_json/binary_t/#notes-on-subtypes","title":"Notes on subtypes","text":"
CBOR
Binary values are represented as byte strings. Subtypes are written as tags.
MessagePack
If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as signed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
BSON
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.
#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
enum class cbor_tag_handler_t\n{\n error,\n ignore,\n store\n};\n
This enumeration is used in the from_cbor function to choose how to treat tags:
error throw a parse_error exception in case of a tag ignore ignore tags store store tagged values as binary container with subtype (for bytes 0xd8..0xdb)"},{"location":"api/basic_json/cbor_tag_handler_t/#examples","title":"Examples","text":"Example
The example below shows how the different values of the cbor_tag_handler_t influence the behavior of from_cbor when reading a tagged byte string.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // 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
Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type():
Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array []
Check whether an element exists in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, false is returned.
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.
Check whether the given JSON pointer ptr can be resolved in the current JSON value.
"},{"location":"api/basic_json/contains/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/contains/#parameters","title":"Parameters","text":"key (in) key value to check its existence. ptr (in) JSON pointer to check its existence."},{"location":"api/basic_json/contains/#return-value","title":"Return value","text":"
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.
See 1.
true if the JSON pointer can be resolved to a stored value, false otherwise.
Returns the number of elements with key key. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/count/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/count/#parameters","title":"Parameters","text":"key (in) key value of the element to count."},{"location":"api/basic_json/count/#return-value","title":"Return value","text":"
Number of elements with key key. If the JSON value is not an object, the return value will be 0.
The following code shows an example for crbegin().
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create an array value\n json array = {1, 2, 3, 4, 5};\n\n // get an iterator to the reverse-beginning\n json::const_reverse_iterator it = array.crbegin();\n\n // serialize the element that the iterator points to\n std::cout << *it << '\\n';\n}\n
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.
#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
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":"
Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent and ensure_ascii parameters.
"},{"location":"api/basic_json/dump/#parameters","title":"Parameters","text":"indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are three possible values (see error_handler_t: strict (throws and exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), and ignore (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged))."},{"location":"api/basic_json/dump/#return-value","title":"Return value","text":"
string containing the serialization of the JSON value
Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.
"},{"location":"api/basic_json/emplace/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace/#iterator-invalidation","title":"Iterator invalidation","text":"
For ordered_json, adding a value to an object can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
"},{"location":"api/basic_json/emplace/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace/#return-value","title":"Return value","text":"
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.
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
Creates a JSON value from the passed parameters args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from args.
"},{"location":"api/basic_json/emplace_back/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace_back/#iterator-invalidation","title":"Iterator invalidation","text":"
By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise, only the end() iterator is invalidated.
"},{"location":"api/basic_json/emplace_back/#parameters","title":"Parameters","text":"args (in) arguments to forward to a constructor of basic_json"},{"location":"api/basic_json/emplace_back/#return-value","title":"Return value","text":"
The return value depends on the different types and is defined as follows:
Value type return value null true boolean false string false number false binary false object result of function object_t::empty() array result of function array_t::empty()"},{"location":"api/basic_json/empty/#exception-safety","title":"Exception safety","text":"
No-throw guarantee: this function never throws exceptions.
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.
#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
Returns the position immediately following the last character of the JSON string from which the value was parsed from.
JSON type return value object position after the closing } array position after the closing ] string position after the closing \" number position after the last character boolean position after e null position after l"},{"location":"api/basic_json/end_pos/#return-value","title":"Return value","text":"
the position of the character following the last character of the given value in the parsed JSON string, if the value was created by the parse function, or std::string::npos if the value was constructed otherwise
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.
"},{"location":"api/basic_json/erase/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/erase/#parameters","title":"Parameters","text":"pos (in) iterator to the element to remove first (in) iterator to the beginning of the range to remove last (in) iterator past the end of the range to remove key (in) object key of the elements to remove idx (in) array index of the element to remove"},{"location":"api/basic_json/erase/#return-value","title":"Return value","text":"
Iterator following the last removed element. If the iterator pos refers to the last element, the end() iterator is returned.
Iterator following the last removed element. If the iterator last refers to the last element, the end() iterator is returned.
Number of elements removed. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: \"iterator out of range\"
The function can throw the following exceptions:
Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\"
Throws invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: \"iterators do not fit current value\"
Throws invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: \"iterators out of range\"
The function can throw the following exceptions:
Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
See 3.
The function can throw the following exceptions:
Throws type_error.307 when called on a type other than JSON object; example: \"cannot use erase() with null\"
Throws out_of_range.401 when idx >= size(); example: \"array index 17 is out of range\"
enum class error_handler_t {\n strict,\n replace,\n ignore\n};\n
This enumeration is used in the dump function to choose how to treat decoding errors while serializing a basic_json value. Three values are differentiated:
strict throw a type_error exception in case of invalid UTF-8 replace replace invalid UTF-8 sequences with U+FFFD (\ufffd REPLACEMENT CHARACTER) ignore ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged"},{"location":"api/basic_json/error_handler_t/#examples","title":"Examples","text":"Example
The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence.
[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
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 error
invalid_iterator for exceptions indicating errors with iterators
type_error for exceptions indicating executing a member function with a wrong type
out_of_range for exceptions indicating access out of the defined range
other_error for exceptions indicating other library errors
To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.
Finds an element in a JSON object with a key equivalent to key. If the element is not found or the JSON value is not an object, end() is returned.
See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/find/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/find/#parameters","title":"Parameters","text":"key (in) key value of the element to search for."},{"location":"api/basic_json/find/#return-value","title":"Return value","text":"
Iterator to an element with a key equivalent to key. If no such element is found or the JSON value is not an object, a past-the-end iterator (see end()) is returned.
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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Changed to consume input adapters, removed start_index parameter, and added strict parameter in version 3.0.0.
Added allow_exceptions parameter in version 3.2.0.
Added tag_handler parameter in version 3.9.0.
Deprecation
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Changed to consume input adapters, removed start_index parameter, and added strict parameter in version 3.0.0.
Added allow_exceptions parameter in version 3.2.0.
Deprecation
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
a pointer to a null-terminated string of single byte characters
an object obj 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.
Added allow_exceptions parameter in version 3.2.0.
Deprecation
Overload (2) replaces calls to 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, ...);.
Overload (2) replaces calls to 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.
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.
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.
json_serializer<ValueType> has a from_json() method of the form ValueType from_json(const basic_json&)
If json_serializer<ValueType> has both overloads of from_json(), the latter one is chosen.
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.
"},{"location":"api/basic_json/get/#template-parameters","title":"Template parameters","text":"ValueType the value type to return BasicJsonType a specialization of basic_jsonPointerType 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":"
copy of the JSON value, converted to ValueType
a copy of *this, converted into BasicJsonType
pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise
The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector<short>, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string, json>.
#include <iostream>\n#include <unordered_map>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value with different types\n json json_types =\n {\n {\"boolean\", true},\n {\n \"number\", {\n {\"integer\", 42},\n {\"floating-point\", 17.23}\n }\n },\n {\"string\", \"Hello, world!\"},\n {\"array\", {1, 2, 3, 4, 5}},\n {\"null\", nullptr}\n };\n\n // use explicit conversions\n auto v1 = json_types[\"boolean\"].template get<bool>();\n auto v2 = json_types[\"number\"][\"integer\"].template get<int>();\n auto v3 = json_types[\"number\"][\"integer\"].template get<short>();\n auto v4 = json_types[\"number\"][\"floating-point\"].template get<float>();\n auto v5 = json_types[\"number\"][\"floating-point\"].template get<int>();\n auto v6 = json_types[\"string\"].template get<std::string>();\n auto v7 = json_types[\"array\"].template get<std::vector<short>>();\n auto v8 = json_types.template get<std::unordered_map<std::string, json>>();\n\n // print the conversion results\n std::cout << v1 << '\\n';\n std::cout << v2 << ' ' << v3 << '\\n';\n std::cout << v4 << ' ' << v5 << '\\n';\n std::cout << v6 << '\\n';\n\n for (auto i : v7)\n {\n std::cout << i << ' ';\n }\n std::cout << \"\\n\\n\";\n\n for (auto i : v8)\n {\n std::cout << i.first << \": \" << i.second << '\\n';\n }\n}\n
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.
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
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.
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
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
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\".
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.
json_serializer<ValueType> has a from_json() method of the form void from_json(const basic_json&, ValueType&)
"},{"location":"api/basic_json/get_to/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/get_to/#return-value","title":"Return value","text":"
The 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
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.
"},{"location":"api/basic_json/insert/#parameters","title":"Parameters","text":"pos (in) iterator before which the content will be inserted; may be the end() iterator val (in) value to insert cnt (in) number of copies of val to insert first (in) begin of the range of elements to insert last (in) end of the range of elements to insert ilist (in) initializer list to insert the values from"},{"location":"api/basic_json/insert/#return-value","title":"Return value","text":"
iterator pointing to the inserted val.
iterator pointing to the first element inserted, or pos if cnt==0
iterator pointing to the first element inserted, or pos if first==last
iterator pointing to the first element inserted, or pos if ilist is empty
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
Throws invalid_iterator.211 if first or last are iterators into container for which insert is called; example: \"passed iterators may not belong to container\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than arrays; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
The function can throw the following exceptions:
Throws type_error.309 if called on JSON values other than objects; example: \"cannot use insert() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
Constant plus linear in the distance between pos and end of the container.
Linear in cnt plus linear in the distance between pos and end of the container.
Linear in std::distance(first, last) plus linear in the distance between pos and end of the container.
Linear in ilist.size() plus linear in the distance between pos and end of the container.
Logarithmic: O(N*log(size() + N)), where N is the number of elements to insert.
"},{"location":"api/basic_json/insert/#examples","title":"Examples","text":"Example (1): insert element into array
The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 10 before number 3\n auto new_pos = v.insert(v.begin() + 2, 10);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n
Output:
10\n[1,2,10,3,4]\n
Example (2): insert copies of element into array
The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // insert number 7 copies of number 7 before number 3\n auto new_pos = v.insert(v.begin() + 2, 7, 7);\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n
Output:
7\n[1,2,7,7,7,7,7,7,7,3,4]\n
Example (3): insert range of elements into array
The example shows how insert() is used.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json v = {1, 2, 3, 4};\n\n // create a JSON array to copy values from\n json v2 = {\"one\", \"two\", \"three\", \"four\"};\n\n // insert range from v2 before the end of array v\n auto new_pos = v.insert(v.end(), v2.begin(), v2.end());\n\n // output new array and result of insert call\n std::cout << *new_pos << '\\n';\n std::cout << v << '\\n';\n}\n
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
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.
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.
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
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.
Added items and deprecated iterator_wrapper in version 3.1.0.
Added structured binding support in version 3.5.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.
"},{"location":"api/basic_json/json_base_class_t/#template-parameters","title":"Template parameters","text":"CustomBaseClass the base class to be added to basic_json"},{"location":"api/basic_json/json_base_class_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/json_base_class_t/#default-type","title":"Default type","text":"
The default value for CustomBaseClass is void. In this case an empty base class is used and no additional functionality is injected.
The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.
"},{"location":"api/basic_json/json_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
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 null 0 (same as size()) boolean 1 (same as size()) string 1 (same as size()) number 1 (same as size()) binary 1 (same as size()) object result of function object_t::max_size() array result of function array_t::max_size()"},{"location":"api/basic_json/max_size/#exception-safety","title":"Exception safety","text":"
No-throw guarantee: this function never throws exceptions.
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 merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):
define MergePatch(Target, Patch):\n if Patch is an Object:\n if Target is not an Object:\n Target = {} // Ignore the contents and set it to an empty Object\n for each Name/Value pair in Patch:\n if Value is null:\n if Name exists in Target:\n remove the Name/Value pair from Target\n else:\n Target[Name] = MergePatch(Target[Name], Value)\n return Target\n else:\n return Patch\n
Thereby, Target is the current object; that is, the patch is applied to the current value.
"},{"location":"api/basic_json/merge_patch/#parameters","title":"Parameters","text":"apply_patch (in) the patch to apply"},{"location":"api/basic_json/merge_patch/#complexity","title":"Complexity","text":"
key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown. url The URL of the project as string. version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string)."},{"location":"api/basic_json/meta/#exception-safety","title":"Exception safety","text":"
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal 01.2 will be serialized to 1.2. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.
"},{"location":"api/basic_json/object/#parameters","title":"Parameters","text":"init (in) initializer list with JSON values to create an object from (optional)"},{"location":"api/basic_json/object/#return-value","title":"Return value","text":"
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.
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).
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:
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.
When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, {\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.
Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see 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}.
When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, {\"b\": 1, \"a\": 2} and {\"a\": 2, \"b\": 1} will be treated as equal.
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.
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.
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
the current value is an object,
the initializer list init contains only two elements, and
the first element of init is a string,
init is converted into an object element and added using operator+=(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using operator+=(basic_json&&).
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.
"},{"location":"api/basic_json/operator%2B%3D/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/operator%2B%3D/#return-value","title":"Return value","text":"
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\"
(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
"},{"location":"api/basic_json/operator%2B%3D/#examples","title":"Examples","text":"Example: (1) add element to array
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
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.
Copy assignment operator. Copies a JSON value via the \"copy and swap\" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function.
"},{"location":"api/basic_json/operator%3D/#parameters","title":"Parameters","text":"other (in) value to copy from"},{"location":"api/basic_json/operator%3D/#complexity","title":"Complexity","text":"
The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally, the copy of a (which is the null value after the swap) is destroyed.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json a = 23;\n json b = 42;\n\n // copy-assign a to b\n b = a;\n\n // serialize the JSON arrays\n std::cout << a << '\\n';\n std::cout << b << '\\n';\n}\n
Returns a reference to the array element at specified location idx.
Returns a reference to the object element with specified key key. The non-const qualified overload takes the key by value.
See 2. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
Returns a reference to the element with specified JSON pointer ptr.
"},{"location":"api/basic_json/operator%5B%5D/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/operator%5B%5D/#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.
"},{"location":"api/basic_json/operator%5B%5D/#parameters","title":"Parameters","text":"idx (in) index of the element to access key (in) object key of the element to access ptr (in) JSON pointer to the desired element"},{"location":"api/basic_json/operator%5B%5D/#return-value","title":"Return value","text":"
(const) reference to the element at index idx
(const) reference to the element at key key
(const) reference to the element at key key
(const) reference to the element pointed to by ptr
If the element with key idx does not exist, the behavior is undefined.
If the element with key 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:
If the JSON pointer points to an object key that does not exist, it is created and filled with a null value before a reference to it is returned.
If the JSON pointer points to an array index that does not exist, it is created and filled with a null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.
The special value - is treated as a synonym for the index past the end.
"},{"location":"api/basic_json/operator%5B%5D/#examples","title":"Examples","text":"Example: (1) access specified array element
The example below shows how array elements can be read and written using [] operator. Note the addition of null values.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json array = {1, 2, 3, 4, 5};\n\n // output element at index 3 (fourth element)\n std::cout << array[3] << '\\n';\n\n // change last element to 6\n array[array.size() - 1] = 6;\n\n // output changed array\n std::cout << array << '\\n';\n\n // write beyond array limit\n array[10] = 11;\n\n // output changed array\n std::cout << array << '\\n';\n}\n
Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get(). See Notes for the meaning of JSON_EXPLICIT.
"},{"location":"api/basic_json/operator_ValueType/#template-parameters","title":"Template parameters","text":"ValueType the value type to return"},{"location":"api/basic_json/operator_ValueType/#return-value","title":"Return value","text":"
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>.
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
Compares two JSON values for equality according to the following rules:
Two JSON values are equal if (1) neither value is discarded, or (2) they are of the same type and their stored values are the same according to their respective operator==.
Integer and floating-point numbers are automatically converted before comparison.
Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the scalar to a JSON value and comparing both JSON values according to 1.
"},{"location":"api/basic_json/operator_eq/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_eq/#return-value","title":"Return value","text":"
NaN values are unordered within the domain of numbers. The following comparisons all yield false:
Comparing a NaN with itself.
Comparing a NaN with another NaN.
Comparing a NaN and any other number.
JSON null values are all equal.
Discarded values never compare equal to themselves.
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:
Compares whether one JSON value lhs is greater than or equal to another JSON value rhs according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(lhs < rhs) (see operator<).
Compares whether a JSON value is greater than or equal to a scalar or a scalar is greater than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.
"},{"location":"api/basic_json/operator_ge/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ge/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ge/#return-value","title":"Return value","text":"
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<=>.
Compares whether one JSON value lhs is greater than another JSON value rhs according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(lhs <= rhs) (see operator<=).
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.
"},{"location":"api/basic_json/operator_gt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_gt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_gt/#return-value","title":"Return value","text":"
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<=>.
Compares whether one JSON value lhs is less than or equal to another JSON value rhs according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(rhs < lhs) (see operator<).
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.
"},{"location":"api/basic_json/operator_le/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_le/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_le/#return-value","title":"Return value","text":"
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<=>.
Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:
If either operand is discarded, the comparison yields false.
If both operands have the same type, the values are compared using their respective operator<.
Integer and floating-point numbers are automatically converted before comparison.
In case lhs and rhs have different types, the values are ignored and the order of the types is considered, which is:
null
boolean
number (all types)
object
array
string
binary For instance, any boolean value is considered less than any string.
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.
"},{"location":"api/basic_json/operator_lt/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_lt/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_lt/#return-value","title":"Return value","text":"
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<=>.
Compares two JSON values for inequality according to the following rules:
The comparison always yields false if (1) either operand is discarded, or (2) either operand is NaN and the other operand is either NaN or any other number.
Otherwise, returns the result of !(lhs == rhs) (until C++20) or !(*this == rhs) (since C++20).
Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1.
"},{"location":"api/basic_json/operator_ne/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/basic_json/operator_ne/#return-value","title":"Return value","text":"
whether the values lhs/*this and rhs are not equal
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.
3-way compares two JSON values producing a result of type std::partial_ordering according to the following rules:
Two JSON values compare with a result of std::partial_ordering::unordered if either value is discarded.
If both JSON values are of the same type, the result is produced by 3-way comparing their stored values using their respective operator<=>.
Integer and floating-point numbers are converted to their common type and then 3-way compared using their respective operator<=>. For instance, comparing an integer and a floating-point value will 3-way compare the first value converted to floating-point with the second value.
Otherwise, yields a result by comparing the type (see value_t).
3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way comparing both JSON values (see 1).
"},{"location":"api/basic_json/operator_spaceship/#template-parameters","title":"Template parameters","text":"ScalarType a scalar type according to std::is_scalar<ScalarType>::value"},{"location":"api/basic_json/operator_spaceship/#parameters","title":"Parameters","text":"rhs (in) second value to consider"},{"location":"api/basic_json/operator_spaceship/#return-value","title":"Return value","text":"
the std::partial_ordering of the 3-way comparison of *this and rhs
Value type return value nullvalue_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.
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
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.
a pointer to a null-terminated string of single byte characters (throws if null)
a std::string
an object obj for which begin(obj) and end(obj) produces a valid pair of iterators.
IteratorType
a compatible iterator type, for instance.
a pair of std::string::iterator or std::vector<std::uint8_t>::iterator
a pair of pointers such as ptr and ptr + len
"},{"location":"api/basic_json/parse/#parameters","title":"Parameters","text":"i (in) Input to parse from. cb (in) a parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) allow_exceptions (in) whether to throw exceptions in case of a parse error (optional, true by default) ignore_comments (in) whether comments should be ignored and treated like whitespace (true) or yield a parse error (false); (optional, false by default) first (in) iterator to start of character range last (in) iterator to end of character range"},{"location":"api/basic_json/parse/#return-value","title":"Return value","text":"
Deserialized JSON value; in case of a parse error and allow_exceptions set to false, the return value will be value_t::discarded. The latter can be checked with is_discarded.
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.
[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
Overload for contiguous containers (1) added in version 2.0.3.
Ignoring comments via ignore_comments added in version 3.9.0.
Changed runtime assertion in case of 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.
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
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.
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
With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
parameter event description parameter depth parameter parsedparse_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:
Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read.
In case a value outside a structured type is skipped, it is replaced with null. This case happens if the top-level element is skipped.
"},{"location":"api/basic_json/parser_callback_t/#parameters","title":"Parameters","text":"depth (in) the depth of the recursion during parsing event (in) an event of type parse_event_t indicating the context in the callback function has been called parsed (in, out) the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events"},{"location":"api/basic_json/parser_callback_t/#return-value","title":"Return value","text":"
Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.
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.
Throws parse_error.104 if the JSON patch does not consist of an array of objects.
Throws parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".
Throws out_of_range.401 if an array index is out of range.
Throws 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\".
Throws out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")
Throws 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.
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.
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.
Throws parse_error.104 if the JSON patch does not consist of an array of objects.
Throws parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: \"operation add must have member path\".
Throws out_of_range.401 if an array index is out of range.
Throws 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\".
Throws out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\", \"move\")
Throws 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.
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.
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
the current value is an object,
the initializer list init contains only two elements, and
the first element of init is a string,
init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(basic_json&&).
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.
"},{"location":"api/basic_json/push_back/#parameters","title":"Parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list"},{"location":"api/basic_json/push_back/#exceptions","title":"Exceptions","text":"
All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use push_back() with number\"
(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list<basic_json>, see #235 for more information.
"},{"location":"api/basic_json/push_back/#examples","title":"Examples","text":"Example: (1) add element to array
The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.
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 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
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.
#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
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.
a pointer to a null-terminated string of single byte characters
an object obj 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":"
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.
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
Ignoring comments via 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);.
The return value depends on the different types and is defined as follows:
Value type return value null 0 boolean 1 string 1 number 1 binary 1 object result of function object_t::size() array result of function array_t::size()"},{"location":"api/basic_json/size/#exception-safety","title":"Exception safety","text":"
No-throw guarantee: this function never throws exceptions.
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.
Returns the position of the first character in the JSON string from which the value was parsed from.
JSON type return value object position of the opening { array position of the opening [ string position of the opening \" number position of the first character boolean position of t for true and f for false null position of n"},{"location":"api/basic_json/start_pos/#return-value","title":"Return value","text":"
the position of the first character of the value in the parsed JSON string, if the value was created by the parse function, or std::string::npos if the value was constructed otherwise
Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc.
"},{"location":"api/basic_json/std_swap/#parameters","title":"Parameters","text":"j1 (in, out) value to be replaced by j2j2 (in, out) value to be replaced by j1"},{"location":"api/basic_json/std_swap/#possible-implementation","title":"Possible implementation","text":"
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.
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.
Exchanges the contents of the JSON value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of the JSON value from left with those of right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Implemented as a friend function callable via ADL.
Exchanges the contents of a JSON array with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a JSON object with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a JSON string with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a binary value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Exchanges the contents of a binary value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike version (6), no binary subtype is involved.
"},{"location":"api/basic_json/swap/#parameters","title":"Parameters","text":"other (in, out) value to exchange the contents with left (in, out) value to exchange the contents with right (in, out) value to exchange the contents with"},{"location":"api/basic_json/swap/#exceptions","title":"Exceptions","text":"
No-throw guarantee: this function never throws exceptions.
No-throw guarantee: this function never throws exceptions.
Throws type_error.310 if called on JSON values other than arrays; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than objects; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than strings; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
Throws type_error.310 if called on JSON values other than binaries; example: \"cannot use swap() with boolean\"
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.
Returns a byte vector containing the BJData serialization.
Writes the BJData serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bjdata/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default. version (in) which version of BJData to use (see note on \"Binary values\" on BJData); optional, bjdata_version_t::draft2 by default."},{"location":"api/basic_json/to_bjdata/#return-value","title":"Return value","text":"
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).
Returns a byte vector containing the BSON serialization.
Writes the BSON serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_bson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_bson/#return-value","title":"Return value","text":"
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.
Returns a byte vector containing the CBOR serialization.
Writes the CBOR serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_cbor/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_cbor/#return-value","title":"Return value","text":"
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.
Returns a byte vector containing the MessagePack serialization.
Writes the MessagePack serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_msgpack/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to"},{"location":"api/basic_json/to_msgpack/#return-value","title":"Return value","text":"
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
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.
Returns a byte vector containing the UBJSON serialization.
Writes the UBJSON serialization to an output adapter.
The exact mapping and its limitations is described on a dedicated page.
"},{"location":"api/basic_json/to_ubjson/#parameters","title":"Parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to use_size (in) whether to add size annotations to container types; optional, false by default. use_type (in) whether to add type annotations to container types (must be combined with use_size = true); optional, false by default."},{"location":"api/basic_json/to_ubjson/#return-value","title":"Return value","text":"
Value type return value nullvalue_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.
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
The following code exemplifies type_name() for all JSON types.
#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call type_name()\n std::cout << j_null << \" is a \" << j_null.type_name() << '\\n';\n std::cout << j_boolean << \" is a \" << j_boolean.type_name() << '\\n';\n std::cout << j_number_integer << \" is a \" << j_number_integer.type_name() << '\\n';\n std::cout << j_number_unsigned << \" is a \" << j_number_unsigned.type_name() << '\\n';\n std::cout << j_number_float << \" is a \" << j_number_float.type_name() << '\\n';\n std::cout << j_object << \" is an \" << j_object.type_name() << '\\n';\n std::cout << j_array << \" is an \" << j_array.type_name() << '\\n';\n std::cout << j_string << \" is a \" << j_string.type_name() << '\\n';\n}\n
Output:
null is a null\ntrue is a boolean\n-17 is a number\n42 is a number\n23.42 is a number\n{\"one\":1,\"two\":2} is an object\n[1,2,4,8,16] is an array\n\"Hello, world\" is a string\n
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:
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().
For ordered_json, adding a value to an object can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.
"},{"location":"api/basic_json/update/#parameters","title":"Parameters","text":"j (in) JSON object to read values from merge_objects (in) when true, existing keys are not overwritten, but contents of objects are merged recursively (default: false) first (in) begin of the range of elements to insert last (in) end of the range of elements to insert"},{"location":"api/basic_json/update/#exceptions","title":"Exceptions","text":"
The function can throw the following exceptions:
Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
The function can throw the following exceptions:
Throws type_error.312 if called on JSON values other than objects; example: \"cannot use update() with string\"
Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\"
Throws invalid_iterator.210 if first and last do not belong to the same JSON value; example: \"iterators do not fit\"
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.
Unlike at, this function does not throw if the given key/ptr was not found.
Unlike 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.
"},{"location":"api/basic_json/value/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17). ValueType type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key/ptr and the default value default_value must be compatible."},{"location":"api/basic_json/value/#parameters","title":"Parameters","text":"key (in) key of the element to access default_value (in) the value to return if key/ptr found no value ptr (in) a JSON pointer to the element to access"},{"location":"api/basic_json/value/#return-value","title":"Return value","text":"
copy of the element at key key or default_value if key is not found
copy of the element at key key or default_value if key is not found
copy of the element at JSON Pointer ptr or default_value if no value for ptr is found
The value function is a template, and the return type of the function is determined by the type of the provided default value unless otherwise specified. This can have unexpected effects. In the example below, we store a 64-bit unsigned integer. We get exactly that value when using operator[]. However, when we call value and provide 0 as default value, then -1 is returned. The occurs, because 0 has type int which overflows when handling the value 18446744073709551615.
To address this issue, either provide a correctly typed default value or use the template parameter to specify the desired return type. Note that this issue occurs even when a value is stored at the provided key, and the default value is not used as the return value.
operator[]: 18446744073709551615\ndefault value (int): -1\ndefault value (uint64_t): 18446744073709551615\nexplict return value type: 18446744073709551615\n
"},{"location":"api/basic_json/value/#examples","title":"Examples","text":"Example: (1) access specified object element with default value
The example below shows how object elements can be queried with a default value.
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.
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 integers
number_integer_t for signed integers
number_float_t for floating-point numbers or to approximate integers which do not fit into the limits of their respective type
Comparison operators
operator< and operator<=> (since C++20) are overloaded and compare according to the ordering described above. Until C++20 all other relational and equality operators yield results according to the integer value of each enumerator. Since C++20 some compilers consider the rewritten candidates generated from operator<=> during overload resolution, while others do not. For predictable and portable behavior use:
operator< or operator<=> when wanting to compare according to the order described above
operator== or operator!= when wanting to compare according to each enumerators integer value
template<typename BinaryType>\nclass byte_container_with_subtype : public BinaryType;\n
This type extends the template parameter BinaryType provided to basic_json with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type.
"},{"location":"api/byte_container_with_subtype/#template-parameters","title":"Template parameters","text":"BinaryType container to store bytes (std::vector<std::uint8_t> by default)"},{"location":"api/byte_container_with_subtype/#member-types","title":"Member types","text":"
container_type - the type of the underlying container (BinaryType)
subtype_type - the type of the subtype (std::uint64_t)
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.
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.
A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions at and operator[]. Furthermore, JSON pointers are the base for JSON patches.
"},{"location":"api/json_pointer/#template-parameters","title":"Template parameters","text":"RefStringType the string type used for the reference tokens making up the JSON pointer
Deprecation
For backwards compatibility RefStringType may also be a specialization of basic_json in which case string_t will be deduced as basic_json::string_t. This feature is deprecated and may be removed in a future major version.
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":"
Throws parse_error.107 if the given JSON pointer s is nonempty and does not begin with a slash (/); see example below.
Throws parse_error.108 if a tilde (~) in the given JSON pointer s is not followed by 0 (representing ~) or 1 (representing /); see example below.
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
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.
"},{"location":"api/json_pointer/operator_eq/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_eq/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_eq/#return-value","title":"Return value","text":"
\"\" == \"\": 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
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.
"},{"location":"api/json_pointer/operator_ne/#template-parameters","title":"Template parameters","text":"RefStringTypeLhs, RefStringTypeRhs the string type of the left-hand side or right-hand side JSON pointer, respectively StringType the string type derived from the json_pointer operand (json_pointer::string_t)"},{"location":"api/json_pointer/operator_ne/#parameters","title":"Parameters","text":"lhs (in) first value to consider rhs (in) second value to consider"},{"location":"api/json_pointer/operator_ne/#return-value","title":"Return value","text":"
whether the values lhs/*this and rhs are not equal
\"\" != \"\": 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
append another JSON pointer at the end of this JSON pointer
append an unescaped reference token at the end of this JSON pointer
append an array index at the end of this JSON pointer
"},{"location":"api/json_pointer/operator_slasheq/#parameters","title":"Parameters","text":"ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append"},{"location":"api/json_pointer/operator_slasheq/#return-value","title":"Return value","text":"
JSON pointer with ptr appended
JSON pointer with token appended without escaping token
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":"
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":"
number_integer_t - BasicJsonType's type for numbers (integer)
number_unsigned_t - BasicJsonType's type for numbers (unsigned)
number_float_t - BasicJsonType's type for numbers (floating-point)
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
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
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
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
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/#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":"
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
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
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/#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).
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/#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":"
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/#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":"
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
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
The library uses numerous assertions to guarantee invariants and to abort in case of otherwise undefined behavior (e.g., when calling operator[] with a missing object key on a const object). See page runtime assertions for more information.
Defining the macro to code that does not call std::abort may leave the library in an undefined state.
This macro enables position diagnostics for generated JSON objects.
When enabled, two new member functions start_pos() and end_pos() are added to basic_json values. If the value was created by calling theparse function, then these functions allow to query the byte positions of the value in the input it was parsed from. In case the value was constructed by other means, std::string::npos is returned.
start_pos() returns the position of the first character of a given value in the original JSON string, while end_pos() returns the position of the character following the last character. For objects and arrays, the first and last characters correspond to the opening or closing braces/brackets, respectively. For primitive values, the first and last character represent the opening and closing quotes (strings) or the first and last character of the field's numerical or predefined value (true, false, null), respectively.
JSON type return value start_pos() return value end_pos() object position of the opening { position after the closing } array position of the opening [ position after the closing ] string position of the opening \" position after the closing \" number position of the first character position after the last character boolean position of t for true and f for false position after e null position of n position after l
Given the above, end_pos()-start_pos() for a JSON value provides the length of the parsed JSON string for that value, including the opening or closing braces, brackets, or quotes.
Note that enabling this macro increases the size of every JSON value by two std::size_t fields and adds slight runtime overhead to parsing, copying JSON value objects, and the generation of error messages for exceptions. It also causes these values to be reported in those error messages.
Diagnostic positions can also be controlled with the CMake option JSON_Diagnostic_Positions (OFF by default) which defines JSON_DIAGNOSTIC_POSITIONS accordingly.
Availability
Diagnostic positions are only available if the value was created by the parse function. The sax_parse function or all other means to create a JSON value do not set the diagnostic positions and start_pos() and end_pos() will only return std::string::npos for these values.
Invalidation
The returned positions are only valid as long as the JSON value is not changed. The positions are not updated when the JSON value is changed.
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.
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.
#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.
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.
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.
#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>).
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.
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.
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)).
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.
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.
// (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.
This macro overrides catch calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches std::out_of_range exceptions internally to rethrow them as json::out_of_range exceptions. The macro is always followed by a scope.
This macro overrides throw calls inside the library. The argument is the exception to be thrown. Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
This macro overrides try calls inside the library. It has no arguments and is always followed by a scope.
"},{"location":"api/macros/json_throw_user/#parameters","title":"Parameters","text":"exception (in) an exception type"},{"location":"api/macros/json_throw_user/#default-definition","title":"Default definition","text":"
By default, the macros map to their respective C++ keywords:
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
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 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
#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.
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.
When targeting C++20 or above, enabling the legacy comparison behavior is strongly discouraged.
The 3-way comparison operator (<=>) will always give the correct result (std::partial_ordering::unordered) regardless of the value of JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON.
Overloads for the equality and relational operators emulate the legacy behavior.
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.
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.
Macros 1, 2 and 3 are to be defined inside the class/struct to create code for. Like NLOHMANN_DEFINE_TYPE_INTRUSIVE, they can access private members.
Macros 4, 5 and 6 are to be defined outside the class/struct to create code for, but inside its namespace. Like 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.
Macros 1 and 4 will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
Macros 2 and 5 will use value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.
Summary:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE"},{"location":"api/macros/nlohmann_define_derived_type/#parameters","title":"Parameters","text":"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:
In first two 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\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, const B& b) {\n nlohmann::to_json(j, static_cast<const A&>(b));\n // ...\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, B& b) {\n nlohmann::from_json(j, static_cast<A&>(b));\n // ...\n}\n
In the third case, only to_json will be called:
class A { /* ... */ };\nclass B : public A { /* ... */ };\n\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, const B& b) {\n nlohmann::to_json(j, static_cast<const A&>(b));\n // ...\n}\n
NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT / NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE for similar macros that can be defined inside a non-derived type.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT / NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for similar macros that can be defined outside a non-derived type.
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.
Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
Will use value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.
Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
Summary:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_TYPE_INTRUSIVE NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE"},{"location":"api/macros/nlohmann_define_type_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","title":"Default definition","text":"
The macros add two friend functions to the class which take care of the serialization and deserialization:
The type type must be default constructible (except (3)). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
The macro must be used inside the type (class/struct).
Implementation limits
The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the to_json/from_json functions manually.
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.
The macro NLOHMANN_DEFINE_TYPE_INTRUSIVE is used inside the class.
A missing key \"age\" in the deserialization yields an exception. To fall back to the default value, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT can be used.
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.
The macro NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT is used inside the class.
A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value -1 is used.
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.
The macro NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE is used inside the class.
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for a similar macro that can be defined outside the type.
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for similar macros for derived types
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.
Will use at during deserialization and will throw out_of_range.403 if a key is missing in the JSON object.
Will use value during deserialization and fall back to the default value for the respective type of the member variable if a key in the JSON object is missing. The generated from_json() function default constructs an object and uses its values as the defaults when calling the value function.
Only defines the serialization. Useful in cases when the type does not have a default constructor and only serialization in required.
Summary:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#parameters","title":"Parameters","text":"type (in) name of the type (class, struct) to serialize/deserialize member (in) name of the (public) member variable to serialize/deserialize; up to 64 members can be given as comma-separated list"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","title":"Default definition","text":"
The macros add two functions to the namespace which take care of the serialization and deserialization:
The type type must be default constructible (except (3). See How can I use get() for non-default constructible/non-copyable types? for how to overcome this limitation.
The macro must be used outside the type (class/struct).
The passed members must be public.
Implementation limits
The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the to_json/from_json functions manually.
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.
The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE is used outside the class, but inside its namespace ns.
A missing key \"age\" in the deserialization yields an exception. To fall back to the default value, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT can be used.
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.
The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE is used outside the class, but inside its namespace ns.
NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE for a similar macro that can be defined inside the type.
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE for similar macros for derived types
The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann, as well as how to output the value of NLOHMANN_JSON_NAMESPACE.
#include <iostream>\n#include <nlohmann/json.hpp>\n\n// possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann\nusing json = NLOHMANN_JSON_NAMESPACE::json;\n\n// macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal\n#define Q(x) #x\n#define QUOTE(x) Q(x)\n\nint main()\n{\n std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl;\n}\n
By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
The NLOHMANN_JSON_SERIALIZE_ENUM allows to define a user-defined serialization for every enumerator.
"},{"location":"api/macros/nlohmann_json_serialize_enum/#parameters","title":"Parameters","text":"type (in) name of the enum to serialize/deserialize conversion (in) a pair of an enumerator and a JSON serialization; arbitrary pairs can be given as a comma-separated list"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","title":"Default definition","text":"
The macro adds two functions to the namespace which take care of the serialization and deserialization:
The macro must be used inside the namespace of the enum.
Important notes
When using template get<ENUM_TYPE>(), undefined JSON values will default to the first specified conversion. Select this default pair carefully. See example 1 below.
If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the list will be returned when converting to or from JSON. See example 2 below.
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.
Code of Conduct - the rules and norms of this project
Contribution Guidelines - guidelines how to contribute to this project
Governance - the governance model of this project
Quality Assurance - how quality of this project is assured
Security Policy - the security policy of the project
"},{"location":"community/code_of_conduct/","title":"Contributor Covenant Code of Conduct","text":""},{"location":"community/code_of_conduct/#our-pledge","title":"Our Pledge","text":"
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders 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, and will communicate reasons for moderation decisions when appropriate.
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mail@nlohmann.me. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
Community Impact: A violation through a single incident or series of actions.
Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
Consequence: A permanent ban from any sort of public interaction within the community.
This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
Community Impact Guidelines were inspired by Mozilla's code of conduct enforcement ladder.
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
Thank you for your interest in contributing to this project! What began as an exercise to explore the exciting features of C++11 has evolved into a widely-used JSON library. I truly appreciate all the contributions from the community, whether it's proposing features, identifying bugs, or fixing mistakes! To ensure that our collaboration is efficient and effective, please follow these guidelines.
Feel free to discuss or suggest improvements to this document by submitting a pull request.
"},{"location":"community/contribution_guidelines/#ways-to-contribute","title":"Ways to Contribute","text":"
There are multiple ways to contribute.
"},{"location":"community/contribution_guidelines/#reporting-an-issue","title":"Reporting an issue","text":"
Please create an issue, assuming one does not already exist, and describe your concern. Note you need a GitHub account for this.
Clearly describe the issue:
If it is a bug, please describe how to reproduce it. If possible, attach a complete example which demonstrates the error. Please also state what you expected to happen instead of the error.
If you propose a change or addition, try to give an example how the improved code could look like or how to use it.
If you found a compilation error, please tell us which compiler (version and operating system) you used and paste the (relevant part of) the error messages to the ticket.
Please stick to the provided issue template bug report if possible.
"},{"location":"community/contribution_guidelines/#reporting-a-security-vulnerability","title":"Reporting a security vulnerability","text":"
You can report a security vulnerability according to our security policy.
"},{"location":"community/contribution_guidelines/#discussing-a-new-feature","title":"Discussing a new feature","text":"
For questions, feature or support requests, please open a discussion. If you find a proposed answer satisfactory, please use the \"Mark as answer\" button to make it easier for readers to see what helped and for the community to filter for open questions.
"},{"location":"community/contribution_guidelines/#proposing-a-fix-or-an-improvement","title":"Proposing a fix or an improvement","text":"
Join an ongoing discussion or comment on an existing issue before starting to code. This can help to avoid duplicate efforts or other frustration during the later review.
Create a pull request against the develop branch and follow the pull request template. In particular,
describe the changes in detail, both the what and why,
reference existing issues where applicable,
add tests to maintain 100% test coverage,
update the documentation as needed, and
ensure the source code is amalgamated.
We describe all points in detail below.
All contributions (including pull requests) must agree to the Developer Certificate of Origin (DCO) version 1.1. This is exactly the same one created and used by the Linux kernel developers and posted on http://developercertificate.org/. This is a developer's certification that he or she has the right to submit the patch for inclusion into the project.
"},{"location":"community/contribution_guidelines/#how-to","title":"How to...","text":""},{"location":"community/contribution_guidelines/#describe-your-changes","title":"Describe your changes","text":"
This library is primarily maintained as a spare-time project. As such, I can not make any guarantee how quickly changes are merged and released. Therefore, it is very important to make the review as smooth as possible by explaining not only what you changed, but why. This rationale can be very valuable down the road when improvements or bugs are discussed years later.
Link a pull request to an issue to clarify that a fix is forthcoming and which issue can be closed after merging. Only few cases (e.g., fixing typos) don\u2019t require prior discussions.
The library has an extensive test suite that currently covers 100 % of the library's code. These test are crucial to maintain API stability and give future contributors confidence that they do not accidentally break things. As Titus Winters aptly put it:
If you liked it, you should have put a test on it.
"},{"location":"community/contribution_guidelines/#run-the-tests","title":"Run the tests","text":"
First, ensure the test suite runs before making any changes:
The tests are located in tests/src/unit-*.cpp and contain doctest assertions like CHECK. The tests are structured along the features of the library or the nature of the tests. Usually, it should be clear from the context which existing file needs to be extended, and only very few cases require creating new test files.
When fixing a bug, edit unit-regression2.cpp and add a section referencing the fixed issue.
If test coverage decreases, an automatic warning comment will be posted on the pull request. You can access a code coverage report as artifact to the \u201cUbuntu\u201d workflow.
"},{"location":"community/contribution_guidelines/#update-the-documentation","title":"Update the documentation","text":"
The main documentation of the library is generated from the files docs/mkdocs/docs. This folder contains dedicated pages for certain features, a list of all exceptions, and an extensive API documentation with details on every public API function.
Build the documentation locally using:
make install_venv -C docs/mkdocs\nmake serve -C docs/mkdocs\n
The documentation will then available at http://127.0.0.1:8000/. See the documentation of mkdocs and Material for MkDocs for more information.
"},{"location":"community/contribution_guidelines/#amalgamate-the-source-code","title":"Amalgamate the source code","text":"
The single-header files single_include/nlohmann/json.hpp and single_include/nlohmann/json_fwd.hpp are generated from the source files in the include/nlohmann directory. Do not edit the files directly; instead, modify the include/nlohmann sources and regenerate the files by executing:
"},{"location":"community/contribution_guidelines/#break-the-public-api","title":"Break the public API","text":"
We take pride in the library being used by numerous customers across various industries. They all rely on the guarantees provided by semantic versioning. Please do not change the library such that the public API of the 3.x.y version is broken. This includes:
Changing function signatures (altering parameter types, return types, number of parameters) or changing the const-ness of member functions.
Removing functions.
Renaming functions or classes.
Changing exception handling.
Changing exception ids.
Changing access specifiers.
Changing default arguments.
Although these guidelines may seem restrictive, they are essential for maintaining the library\u2019s utility.
Breaking changes may be introduced when they are guarded with a feature macro such as JSON_USE_IMPLICIT_CONVERSIONS which allows to selectively change the behavior of the library. In next steps, the current behavior can then be deprecated. Using feature macros then allows users to test their code against the library in the next major release.
"},{"location":"community/contribution_guidelines/#break-c11-language-conformance","title":"Break C++11 language conformance","text":"
This library is designed to work with C++11 and later. This means that any supported C++11 compiler should compile the library without problems. Some compilers like GCC 4.7 (and earlier), Clang 3.3 (and earlier), or Microsoft Visual Studio 13.0 and earlier are known not to work due to missing or incomplete C++11 support.
Please do not add features that do not work with the mentioned supported compilers. Please guard features from C++14 and later against the respective JSON_HAS_CPP_14 macros.
Please refrain from proposing changes that would break JSON conformance. If you propose a conformant extension of JSON to be supported by the library, please motivate this extension.
The following areas really need contribution and are always welcomed:
Extending the continuous integration toward more exotic compilers such as Android NDK, Intel's Compiler, or the bleeding-edge versions Clang.
Improving the efficiency of the JSON parser. The current parser is implemented as a naive recursive descent parser with hand coded string handling. More sophisticated approaches like LALR parsers would be really appreciated. That said, parser generators like Bison or ANTLR do not play nice with single-header files -- I really would like to keep the parser inside the json.hpp header, and I am not aware of approaches similar to re2c for parsing.
Extending and updating existing benchmarks to include (the most recent version of) this library. Though efficiency is not everything, speed and memory consumption are very important characteristics for C++ developers, so having proper comparisons would be interesting.
We look forward to your contributions and collaboration to enhance the library!
The governance model for the JSON for Modern C++ project is a Benevolent Dictator for Life (BDFL) structure. As the sole maintainer, Niels Lohmann is responsible for all key aspects of the project. The project governance may evolve as the project grows, but any changes will be documented here and communicated to contributors.
This project is led by a benevolent dictator, Niels Lohmann, and managed by the community. That is, the community actively contributes to the day-to-day maintenance of the project, but the general strategic line is drawn by the benevolent dictator. In case of disagreement, they have the last word. It is the benevolent dictator\u2019s job to resolve disputes within the community and to ensure that the project is able to progress in a coordinated way. In turn, it is the community\u2019s job to guide the decisions of the benevolent dictator through active engagement and contribution.
"},{"location":"community/governance/#roles-and-responsibilities","title":"Roles and responsibilities","text":""},{"location":"community/governance/#benevolent-dictator-project-lead","title":"Benevolent dictator (project lead)","text":"
Typically, the benevolent dictator, or project lead, is self-appointed. However, because the community always has the ability to fork, this person is fully answerable to the community. The project lead\u2019s role is a difficult one: they set the strategic objectives of the project and communicate these clearly to the community. They also have to understand the community as a whole and strive to satisfy as many conflicting needs as possible, while ensuring that the project survives in the long term.
In many ways, the role of the benevolent dictator is less about dictatorship and more about diplomacy. The key is to ensure that, as the project expands, the right people are given influence over it and the community rallies behind the vision of the project lead. The lead\u2019s job is then to ensure that the committers (see below) make the right decisions on behalf of the project. Generally speaking, as long as the committers are aligned with the project\u2019s strategy, the project lead will allow them to proceed as they desire.
Committers are contributors who have made several valuable contributions to the project and are now relied upon to both write code directly to the repository and screen the contributions of others. In many cases they are programmers but it is also possible that they contribute in a different role. Typically, a committer will focus on a specific aspect of the project, and will bring a level of expertise and understanding that earns them the respect of the community and the project lead. The role of committer is not an official one, it is simply a position that influential members of the community will find themselves in as the project lead looks to them for guidance and support.
Committers have no authority over the overall direction of the project. However, they do have the ear of the project lead. It is a committer\u2019s job to ensure that the lead is aware of the community\u2019s needs and collective objectives, and to help develop or elicit appropriate contributions to the project. Often, committers are given informal control over their specific areas of responsibility, and are assigned rights to directly modify certain areas of the source code. That is, although committers do not have explicit decision-making authority, they will often find that their actions are synonymous with the decisions made by the lead.
Contributors are community members who either have no desire to become committers, or have not yet been given the opportunity by the benevolent dictator. They make valuable contributions, such as those outlined in the list below, but generally do not have the authority to make direct changes to the project code. Contributors engage with the project through communication tools, such as email lists, and via reports and patches attached to issues in the issue tracker, as detailed in our community tools document.
Anyone can become a contributor. There is no expectation of commitment to the project, no specific skill requirements and no selection process. To become a contributor, a community member simply has to perform one or more actions that are beneficial to the project.
Some contributors will already be engaging with the project as users, but will also find themselves doing one or more of the following:
supporting new users (current users often provide the most effective new user support)
reporting bugs
identifying requirements
supplying graphics and web design
programming
assisting with project infrastructure
writing documentation
fixing bugs
adding features
As contributors gain experience and familiarity with the project, they may find that the project lead starts relying on them more and more. When this begins to happen, they gradually adopt the role of committer, as described above.
Users are community members who have a need for the project. They are the most important members of the community: without them, the project would have no purpose. Anyone can be a user; there are no specific requirements.
Users should be encouraged to participate in the life of the project and the community as much as possible. User contributions enable the project team to ensure that they are satisfying the needs of those users. Common user activities include (but are not limited to):
evangelising about the project
informing developers of project strengths and weaknesses from a new user\u2019s perspective
providing moral support (a \u2018thank you\u2019 goes a long way)
providing financial support
Users who continue to engage with the project and its community will often find themselves becoming more and more involved. Such users may then go on to become contributors, as described above.
All participants in the community are encouraged to provide support for new users within the project management infrastructure. This support is provided as a way of growing the community. Those seeking support should recognise that all support activity within the project is voluntary and is therefore provided as and when time allows. A user requiring guaranteed response times or results should therefore seek to purchase a support contract from a vendor. (Of course, that vendor should be an active member of the community.) However, for those willing to engage with the project on its own terms, and willing to help support other users, the community support channels are ideal.
Anyone can contribute to the project, regardless of their skills, as there are many ways to contribute. For instance, a contributor might be active on the project mailing list and issue tracker, or might supply patches. The various ways of contributing are described in more detail in our roles in open source document.
The developer mailing list is the most appropriate place for a contributor to ask for help when making their first contribution.
The benevolent dictatorship model does not need a formal conflict resolution process, since the project lead\u2019s word is final. If the community chooses to question the wisdom of the actions of a committer, the project lead can review their decisions by checking the email archives, and either uphold or reverse them.
Source
The text was taken from http://oss-watch.ac.uk/resources/benevolentdictatorgovernancemodel.
Ensuring quality is paramount for this project, particularly because numerous other projects depend on it. Each commit to the library undergoes rigorous checks against the following requirements, and any violations will result in a failed build.
"},{"location":"community/quality_assurance/#c-language-compliance-and-compiler-compatibility","title":"C++ language compliance and compiler compatibility","text":"
Requirement: Compiler support
Any compiler with complete C++11 support can compile the library without warnings.
The library is compiled library with 50+ different C++ compilers with different operating systems and platforms, including the oldest versions known to compile the library.
The library is compiled with all C++ language revisions (C++11, C++14, C++17, C++20, C++23, and C++26) to detect and fix language deprecations early.
The library is checked for compiler warnings:
On Clang, -Weverything is used with 7 exceptions.
Clang warnings
# Ignored Clang warnings:\n# -Wno-c++98-compat The library targets C++11.\n# -Wno-c++98-compat-pedantic The library targets C++11.\n# -Wno-deprecated-declarations The library contains annotations for deprecated functions.\n# -Wno-extra-semi-stmt The library uses assert which triggers this warning.\n# -Wno-padded We do not care about padding warnings.\n# -Wno-covered-switch-default All switches list all cases and a default case.\n# -Wno-unsafe-buffer-usage Otherwise Doctest would not compile.\n\nset(CLANG_CXXFLAGS\n -Werror\n -Weverything\n -Wno-c++98-compat\n -Wno-c++98-compat-pedantic\n -Wno-deprecated-declarations\n -Wno-extra-semi-stmt\n -Wno-padded\n -Wno-covered-switch-default\n -Wno-unsafe-buffer-usage\n)\n
On GCC, 300+ warnings are enabled with 8 exceptions.
A common code style is used throughout all code files of the library.
The code is formatted with Artistic Style (astyle) against a style configuration that is also enforced in the CI.
Astyle configuration (tools/astyle/.astylerc)
# Configuration for Artistic Style\n# see https://astyle.sourceforge.net/astyle.html\n\n#######################\n# Brace Style Options #\n#######################\n\n# use Allman style for braces\n--style=allman\n\n###############\n# Tab Options #\n###############\n\n# indent using 4 spaces\n--indent=spaces=4\n\n#######################\n# Indentation Options #\n#######################\n\n# indent access modifiers one half indent\n--indent-modifiers\n\n# indent switch cases to the switch block\n--indent-switches\n\n# indent preprocessor blocks\n--indent-preproc-block\n\n# indent preprocessor defines\n--indent-preproc-define\n\n# indent C++ comments\n--indent-col1-comments\n\n###################\n# Padding Options #\n###################\n\n# insert space padding around operators\n--pad-oper\n\n# insert space between if/for/while... and the following parentheses\n--pad-header\n\n# attach the pointer to the variable type (left)\n--align-pointer=type\n\n# attach the reference to the variable type (left)\n--align-reference=type\n\n######################\n# Formatting Options #\n######################\n\n# add braces to unbraced one line conditional statements\n--add-braces\n\n# convert tabs to spaces\n--convert-tabs\n\n# closes whitespace between the ending angle brackets of template definitions\n--close-templates\n\n#################\n# Other Options #\n#################\n\n# do not create backup files\n--suffix=none\n\n# preserve the original file date\n--preserve-date\n\n# display only the files that have been formatted\n--formatted\n\n# for the linux (LF) line end style\n--lineend=linux\n
The code style is checked with cpplint with 61 enabled rules.
The library can be used by adding a single header to a C++ project.
An amalgamation script is used to check if the source code is exposed as self-contained single-header file.
The test suite is checked against the amalgamated source file as well as the individual source file.
Requirement: CMake as primary development tool
All library functions are exposed and usable by CMake.
All library options are exposed as CMake options and tested.
The library is tested against the earliest supported CMake version.
"},{"location":"community/security_policy/","title":"Security Policy","text":""},{"location":"community/security_policy/#reporting-a-vulnerability","title":"Reporting a Vulnerability","text":"
We value the security of our users and appreciate your efforts to responsibly disclose vulnerabilities. If you have identified a security vulnerability in this repository, please use the GitHub Security Advisory \"Report a Vulnerability\" tab.
Until it is published, this draft security advisory will only be visible to the maintainers of this project. Other users and teams may be added once the advisory is created.
We will send a response indicating the next steps in handling your report. After the initial reply to your report, we will keep you informed of the progress towards a fix and full announcement and may ask for additional information or guidance.
For vulnerabilities in third-party dependencies or modules, please report them directly to the respective maintainers.
Explore security-related topics and contribute to tools and projects through GitHub Security Lab.
Learn more about responsible disclosure and reporting vulnerabilities in GitHub at About coordinated disclosure of security vulnerabilities.
We sincerely thank you for contributing to the security and integrity of this project!
"},{"location":"features/arbitrary_types/","title":"Arbitrary Type Conversions","text":"
Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines:
namespace ns {\n // a simple struct to model a person\n struct person {\n std::string name;\n std::string address;\n int age;\n };\n} // namespace ns\n\nns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n// convert to JSON: copy each value into the JSON object\njson j;\nj[\"name\"] = p.name;\nj[\"address\"] = p.address;\nj[\"age\"] = p.age;\n\n// ...\n\n// convert from JSON: copy each value from the JSON object\nns::person p {\n j[\"name\"].template get<std::string>(),\n j[\"address\"].template get<std::string>(),\n j[\"age\"].template get<int>()\n};\n
It works, but that's quite a lot of boilerplate... Fortunately, there's a better way:
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:
Those methods MUST be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace ns, where person is defined).
Those methods MUST be available (e.g., proper headers must be included) everywhere you use these conversions. Look at #1108 for errors that may occur otherwise.
When using template get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)
In function 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.
You do not need to add serializers or deserializers for STL types like std::vector: the library already implements these.
"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","title":"Simplify your life with macros","text":"
If you just want to serialize/deserialize some structs, the to_json/from_json functions can be a lot of boilerplate.
There are six 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_NON_INTRUSIVE_ONLY_SERIALIZE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It does not define a from_json() function which is needed in case the type does not have a default constructor.
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.
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It does not define a from_json() function which is needed in case the type does not have a default constructor.
Furthermore, there exist versions to use in case of derived classes:
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_TYPE_INTRUSIVE NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE
For derived classes and structs, use the following macros
Need access to private members Need only de-serialization Allow missing values when de-serializing macro NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE
Implementation limits
The current macro implementations are limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the to_json/from_json functions manually.
Example
The to_json/from_json functions for the person struct above can be created with:
Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed:
namespace ns {\n class address {\n private:\n std::string street;\n int housenumber;\n int postcode;\n\n public:\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)\n };\n}\n
"},{"location":"features/arbitrary_types/#how-do-i-convert-third-party-types","title":"How do I convert third-party types?","text":"
This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
The library uses JSON Serializers to convert types to json. The default serializer for nlohmann::json is nlohmann::adl_serializer (ADL means Argument-Dependent Lookup).
It is implemented like this (simplified):
template <typename T>\nstruct adl_serializer {\n static void to_json(json& j, const T& value) {\n // calls the \"to_json\" method in T's namespace\n }\n\n static void from_json(const json& j, T& value) {\n // same thing, but with the \"from_json\" method\n }\n};\n
This serializer works fine when you have control over the type's namespace. However, what about boost::optional or std::filesystem::path (C++17)? Hijacking the boost namespace is pretty bad, and it's illegal to add something other than template specializations to std...
To solve this, you need to add a specialization of adl_serializer to the nlohmann namespace, here's an example:
// partial specialization (full specialization works too)\nNLOHMANN_JSON_NAMESPACE_BEGIN\ntemplate <typename T>\nstruct adl_serializer<boost::optional<T>> {\n static void to_json(json& j, const boost::optional<T>& opt) {\n if (opt == boost::none) {\n j = nullptr;\n } else {\n j = *opt; // this will call adl_serializer<T>::to_json which will\n // find the free function to_json in T's namespace!\n }\n }\n\n static void from_json(const json& j, boost::optional<T>& opt) {\n if (j.is_null()) {\n opt = boost::none;\n } else {\n opt = j.template get<T>(); // same as above, but with\n // adl_serializer<T>::from_json\n }\n }\n};\nNLOHMANN_JSON_NAMESPACE_END\n
ABI compatibility
Use NLOHMANN_JSON_NAMESPACE_BEGIN and NLOHMANN_JSON_NAMESPACE_END instead of namespace nlohmann { } in code which may be linked with different versions of this library.
"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types","title":"How can I use get() for non-default constructible/non-copyable types?","text":"
There is a way, if your type is MoveConstructible. You will need to specialize the adl_serializer as well, but with a special from_json overload:
struct move_only_type {\n move_only_type() = delete;\n move_only_type(int ii): i(ii) {}\n move_only_type(const move_only_type&) = delete;\n move_only_type(move_only_type&&) = default;\n\n int i;\n};\n\nnamespace nlohmann {\n template <>\n struct adl_serializer<move_only_type> {\n // note: the return type is no longer 'void', and the method only takes\n // one argument\n static move_only_type from_json(const json& j) {\n return {j.template get<int>()};\n }\n\n // Here's the catch! You must provide a to_json method! Otherwise, you\n // will not be able to convert move_only_type to json, since you fully\n // specialized adl_serializer on that type\n static void to_json(json& j, move_only_type t) {\n j = t.i;\n }\n };\n}\n
"},{"location":"features/arbitrary_types/#can-i-write-my-own-serializer-advanced-use","title":"Can I write my own serializer? (Advanced use)","text":"
Yes. You might want to take a look at unit-udt.cpp in the test suite, to see a few examples.
If you write your own serializer, you'll need to do a few things:
use a different basic_json alias than nlohmann::json (the last template parameter of basic_json is the JSONSerializer)
use your basic_json alias (or a template parameter) in all your to_json/from_json methods
use nlohmann::to_json and nlohmann::from_json when you need ADL
Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL.
// You should use void as a second template argument\n// if you don't need compile-time checks on T\ntemplate<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type>\nstruct less_than_32_serializer {\n template <typename BasicJsonType>\n static void to_json(BasicJsonType& j, T value) {\n // we want to use ADL, and call the correct to_json overload\n using nlohmann::to_json; // this method is called by adl_serializer,\n // this is where the magic happens\n to_json(j, value);\n }\n\n template <typename BasicJsonType>\n static void from_json(const BasicJsonType& j, T& value) {\n // same thing here\n using nlohmann::from_json;\n from_json(j, value);\n }\n};\n
Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention:
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.
"},{"location":"features/assertions/#function-with-runtime-assertions","title":"Function with runtime assertions","text":""},{"location":"features/assertions/#unchecked-object-access-to-a-const-value","title":"Unchecked object access to a const value","text":"
Function operator[] implements unchecked access for objects. Whereas a missing key is added in case of non-const objects, accessing a const object with a missing key is undefined behavior (think of a dereferenced null pointer) and yields a runtime assertion.
If you are not sure whether an element in an object exists, use checked access with the at function or call the contains function before.
See also the documentation on element access.
Example 1: Missing object key
The following code will trigger an assertion at runtime:
#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n const json j = {{\"key\", \"value\"}};\n auto v = j[\"missing\"];\n}\n
Output:
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.\n
"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","title":"Constructing from an uninitialized iterator range","text":"
Constructing a JSON value from an iterator range (see constructor) with an uninitialized iterator is undefined behavior and yields a runtime assertion.
Example 2: Uninitialized iterator range
The following code will trigger an assertion at runtime:
Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.\n
"},{"location":"features/assertions/#operations-on-uninitialized-iterators","title":"Operations on uninitialized iterators","text":"
Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion.
Example 3: Uninitialized iterator
The following code will trigger an assertion at runtime:
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.
Example 4: Reading from null pointer
The following code will trigger an assertion at runtime:
The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored.
JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.
"},{"location":"features/binary_values/#api-for-binary-values","title":"API for binary values","text":"
By default, binary values are stored as std::vector<std::uint8_t>. This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t:
JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: bytes holds an array of integers, and subtype is an integer or null.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// serialize to standard output\nstd::cout << j.dump(2) << std::endl;\n
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.
BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
Example
Code:
// create a binary value of subtype 42 (will be ignored in BJData)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BJData\nauto v = json::to_bjdata(j); \n
v is a std::vector<std::uint8t> with the following 20 elements:
BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to BSON\nauto v = json::to_bson(j); \n
v is a std::vector<std::uint8t> with the following 22 elements:
0x16 0x00 0x00 0x00 // number of bytes in the document\n 0x05 // binary value\n 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte\n 0x04 0x00 0x00 0x00 // number of bytes\n 0x2a // subtype\n 0xCA 0xFE 0xBA 0xBE // content\n0x00 // end of the document\n
Note that the serialization preserves the subtype, and deserializing v would yield the following value:
CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to CBOR\nauto v = json::to_cbor(j); \n
v is a std::vector<std::uint8t> with the following 15 elements:
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.
MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
Example
Code:
// create a binary value of subtype 42\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to MessagePack\nauto v = json::to_msgpack(j); \n
v is a std::vector<std::uint8t> with the following 14 elements:
UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
Example
Code:
// create a binary value of subtype 42 (will be ignored in UBJSON)\njson j;\nj[\"binary\"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);\n\n// convert to UBJSON\nauto v = json::to_ubjson(j); \n
v is a std::vector<std::uint8t> with the following 20 elements:
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:
This library does not support comments by default. It does so for three reasons:
Comments are not part of the JSON specification. You may argue that // 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.
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:
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
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.
It MUST be available (e.g., proper headers must be included) everywhere you use the conversions.
Other Important points:
When using template get<ENUM_TYPE>(), undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.
If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.
To disable the default serialization of enumerators as integers and force a compiler error instead, see 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().
"},{"location":"features/iterators/#iteration-order-for-objects","title":"Iteration order for objects","text":"
When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.
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.
"},{"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.
Example
json j = {1, 2, 3, 4};\n\nfor (auto it = j.rbegin(); it != j.rend(); ++it)\n{\n std::cout << *it << std::endl;\n}\n
Output:
4\n3\n2\n1\n
"},{"location":"features/iterators/#iterating-strings-and-binary-values","title":"Iterating strings and binary values","text":"
Note that \"value\" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe the underlying string or binary array is empty.
Example
json j = \"Hello, world\";\nfor (auto it = j.begin(); it != j.end(); ++it)\n{\n std::cout << *it << std::endl;\n}\n
Output:
\"Hello, world\"\n
"},{"location":"features/iterators/#iterator-invalidation","title":"Iterator invalidation","text":"Operations invalidated iterators clear all"},{"location":"features/json_patch/","title":"JSON Patch and Diff","text":""},{"location":"features/json_patch/#patches","title":"Patches","text":"
JSON Patch (RFC 6902) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch.
Example
The following code shows how a JSON patch is applied to a value.
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.
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
Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.
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.
When enabled, two new member functions start_pos() and end_pos() are added to basic_json values. If the value was created by calling theparse function, then these functions allow to query the byte positions of the value in the input it was parsed from. The byte positions are also used in exceptions to help locate errors.
The diagnostics positions can also be controlled with the CMake option JSON_Diagnostic_Positions (OFF by default) which sets JSON_DIAGNOSTIC_POSITIONS accordingly.
See full documentation of JSON_DIAGNOSTIC_POSITIONS
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.
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.
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.
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)).
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.
The library defines 12 macros to simplify the serialization/deserialization of types. See the page on arbitrary type conversion for a detailed discussion.
The library supports JSON Merge Patch (RFC 7386) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.
Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified.
Example
The following code shows how a JSON Merge Patch is applied to a JSON document.
#include <iostream>\n#include <nlohmann/json.hpp>\n#include <iomanip> // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}\n
Output:
{\n \"author\": {\n \"givenName\": \"John\"\n },\n \"content\": \"This will be unchanged\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"tags\": [\n \"example\"\n ],\n \"title\": \"Hello!\"\n}\n
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.
The complete default namespace name is derived as follows:
The root namespace is always nlohmann.
The inline namespace starts with 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.
The inline namespace ends with the suffix _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:
Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS. This is illustrated in the diagram below.
In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.
Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types.
There is an exception when forward declarations are used (i.e., when including json_fwd.hpp) in which case the linker may complain about undefined references.
"},{"location":"features/namespace/#disabling-the-version-component","title":"Disabling the version component","text":"
Different versions are not necessarily ABI-incompatible, but the project does not actively track changes in the ABI and recommends that all parts of a codebase exchanging library types be built with the same version. Users can, at their own risk, disable the version component of the linline namespace, allowing different versions \u2013 but not configurations \u2013 to be used in cases where the linker would otherwise output undefined reference errors.
To do so, define NLOHMANN_JSON_NAMESPACE_NO_VERSION to 1.
This applies to version 3.11.2 and above only, versions 3.11.0 and 3.11.1 can apply the technique described in the next section to emulate the effect of the NLOHMANN_JSON_NAMESPACE_NO_VERSION macro.
Use at your own risk
Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!
"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","title":"Disabling the inline namespace completely","text":"
When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows:
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.
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.
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
BJData (Binary JData),
BSON (Binary JSON),
CBOR (Concise Binary Object Representation),
MessagePack, and
UBJSON (Universal Binary JSON)
to efficiently encode JSON values to byte vectors and to decode such vectors.
"},{"location":"features/binary_formats/#comparison","title":"Comparison","text":""},{"location":"features/binary_formats/#completeness","title":"Completeness","text":"Format Serialization Deserialization BJData complete complete BSON incomplete: top-level value must be an object incomplete, but all JSON types are supported CBOR complete incomplete, but all JSON types are supported MessagePack complete complete UBJSON complete complete"},{"location":"features/binary_formats/#binary-values","title":"Binary values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported
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 5 new type markers - [u] - uint16, [m] - uint32, [M] - uint64, [h] - float16 and [B] - byte - 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.
The library uses the following mapping from JSON values types to BJData types according to the BJData specification:
JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { binary see notes on binary values array [$B
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:
strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 bytes (theoretical)
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:
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 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
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 UiuImlMLhdDCB. 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
BJData provides a dedicated B marker (defined in the BJData specification (Draft 3)) that is used in optimized arrays to designate binary data. This means that, unlike UBJSON, binary data can be both serialized and deserialized.
To preserve compatibility with BJData Draft 2, the Draft 3 optimized binary array must be explicitly enabled using the version parameter of to_bjdata.
In Draft2 mode (default), if the JSON data contains the binary type, the value stored as 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
The library maps BJData types to JSON value types as follows:
BJData type JSON value type marker no-op no value, next value is read N null nullZ false falseF true trueT 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 byte number_unsigned B 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) { binary binary (strongly-typed byte array) [$B
Complete mapping
The mapping is complete in the sense that any BJData value can be converted to a JSON value.
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.
The library uses the following mapping from JSON values types to BSON types:
JSON value type value/range BSON type marker null null null 0x0A boolean true, false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 uint64 0x11 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, 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
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 uint64(Timestamp) 0x11 number_unsigned 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported
Incomplete mapping
The mapping is incomplete. The unsupported mappings are indicated in the table above.
Handling of BSON type 0x11
BSON type 0x11 is used to represent uint64 numbers. This library treats these values purely as uint64 numbers and does not parse them into date-related formats.
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
CBOR Website - the main source on CBOR
CBOR Playground - an interactive webpage to translate between JSON and CBOR
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:
UTF-8 strings terminated by \"break\" (0x7F)
arrays terminated by \"break\" (0x9F)
maps terminated by \"break\" (0xBF)
byte strings terminated by \"break\" (0x5F)
date/time (0xC0..0xC1)
bignum (0xC2..0xC3)
decimal fraction (0xC4)
bigfloat (0xC5)
expected conversions (0xD5..0xD7)
simple values (0xE0..0xF3, 0xF8)
undefined (0xF7)
half-precision floats (0xF9)
break (0xFF)
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
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:
date/time (0xC0..0xC1)
bignum (0xC2..0xC3)
decimal fraction (0xC4)
bigfloat (0xC5)
expected conversions (0xD5..0xD7)
simple values (0xE0..0xF3, 0xF8)
undefined (0xF7)
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.
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.
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:
strings with more than 4294967295 bytes
byte strings with more than 4294967295 bytes
arrays with more than 4294967295 elements
objects with more than 4294967295 elements
NaN/infinity handling
If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the dump function which serializes NaN or Infinity to null.
Example
#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to MessagePack\n std::vector<std::uint8_t> v = json::to_msgpack(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}\n
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.
The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification:
JSON value type value/range UBJSON type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map {
Complete mapping
The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value.
Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson.
Size constraints
The following values can not be converted to a UBJSON value:
strings with more than 9223372036854775807 bytes (theoretical)
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
The library maps UBJSON types to JSON value types as follows:
UBJSON type JSON value type marker no-op no value, next value is read N null nullZ false falseF true trueT 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.
The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise.
When accessing an invalid index (i.e., an index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown.
Accessing via invalid index or missing key
j.at(\"hobbies\").at(3) = \"cooking\";\n
This code produces the following exception:
[json.exception.out_of_range.401] array index 3 is out of range\n
When you extended diagnostic messages are enabled by defining JSON_DIAGNOSTICS, the exception further gives information where the key or index is missing or out of range.
[json.exception.out_of_range.401] (/hobbies) array index 3 is out of range\n
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.
"},{"location":"features/element_access/checked_access/#summary","title":"Summary","text":"scenario non-const value const value access to existing object key reference to existing value is returned const reference to existing value is returned access to valid array index reference to existing value is returned const reference to existing value is returned access to non-existing object key basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown access to invalid array index basic_json::out_of_range exception is thrown basic_json::out_of_range exception is thrown"},{"location":"features/element_access/default_value/","title":"Access with default value: value","text":""},{"location":"features/element_access/default_value/#overview","title":"Overview","text":"
In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. For this case, use value(key, default_value) which takes the key you want to access and a default value in case there is no value stored with that key.
expression value j{\"logOutput\": \"result.log\", \"append\": true}j.value(\"logOutput\", \"logfile.log\")\"result.log\"j.value(\"append\", true)truej.value(\"append\", false)truej.value(\"logLevel\", \"verbose\")\"verbose\""},{"location":"features/element_access/default_value/#notes","title":"Notes","text":"
Exceptions
value can only be used with objects. For other types, a basic_json::type_error is thrown.
Return type
The value function is a template, and the return type of the function is determined by the type of the provided default value unless otherwise specified. This can have unexpected effects. In the example below, we store a 64-bit unsigned integer. We get exactly that value when using operator[]. However, when we call value and provide 0 as default value, then -1 is returned. The occurs, because 0 has type int which overflows when handling the value 18446744073709551615.
To address this issue, either provide a correctly typed default value or use the template parameter to specify the desired return type. Note that this issue occurs even when a value is stored at the provided key, and the default value is not used as the return value.
operator[]: 18446744073709551615\ndefault value (int): -1\ndefault value (uint64_t): 18446744073709551615\nexplict return value type: 18446744073709551615\n
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.
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.
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
It is undefined behavior to access a const object with a non-existing key.
It is undefined behavior to access a const array with an invalid index.
In debug mode, an assertion will fire in both cases. You can disable assertions by defining the preprocessor symbol 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.
"},{"location":"features/element_access/unchecked_access/#summary","title":"Summary","text":"scenario non-const value const value access to existing object key reference to existing value is returned const reference to existing value is returned access to valid array index reference to existing value is returned const reference to existing value is returned access to non-existing object key reference to newly inserted null value is returned undefined behavior; runtime assertion in debug mode access to invalid array index reference to newly inserted null value is returned; any index between previous maximal index and passed index are filled with null undefined behavior; runtime assertion in debug mode"},{"location":"features/parsing/","title":"Parsing","text":"
Note
This page is under construction.
"},{"location":"features/parsing/#input","title":"Input","text":""},{"location":"features/parsing/#sax-vs-dom-parsing","title":"SAX vs. DOM parsing","text":""},{"location":"features/parsing/#exceptions","title":"Exceptions","text":"
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.
{\"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
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
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).
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
With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse, it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.
parameter event description parameter depth parameter parsedparse_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
// 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:
Implement the SAX interface in a class. You can use class nlohmann::json_sax<json> as base class, but you can also use any class where the functions described above are implemented and public.
Create an object of your SAX interface class, e.g. my_sax.
Call bool json::sax_parse(input, &my_sax); where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface.
Note the sax_parse function only returns a bool indicating the result of the last executed SAX event. It does not return json value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error - it is up to you what to do with the exception object passed to your parse_error implementation. Internally, the SAX interface is used for the DOM parser (class json_sax_dom_parser) as well as the acceptor (json_sax_acceptor), see file json_sax.hpp.
JSON type C++ type object std::map<std::string, basic_json> array std::vector<basic_json> null std::nullptr_t string std::string boolean bool number std::int64_t, std::uint64_t, and double
Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen.
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:
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.
The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:
When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.
When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, {\"key\": 2, \"key\": 1} could be equal to either {\"key\": 1} or {\"key\": 2}.
Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see 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}.
When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, {\"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.
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.
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.
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.
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.
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.
The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
Not-a-number (NaN) values will be serialized to null.
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.
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:
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.
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
Numbers with a decimal digit or scientific notation are always stored as double.
The number types can be changed, see Template number types.
As of version 3.9.1, the conversion is realized by std::strtoull, std::strtoll, and std::strtod, respectively.
Examples
Integer -12345678912345789123456789 is smaller than INT64_MIN and will be stored as floating-point number -1.2345678912345788e+25.
Integer 1E3 will be stored as floating-point number 1000.0.
Any 64-bit signed or unsigned integer can be stored without loss of precision.
Numbers exceeding the limits of 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.
Floating-point numbers are rounded to the next number representable as double. For instance 3.141592653589793238462643383279 is stored as 0x400921fb54442d18. This is the same behavior as the code double x = 3.141592653589793238462643383279;.
Interoperability
The library interoperable with respect to the specification, because its supported range [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1].
All integers outside the range [-2^{63}, 2^{64}-1], as well as floating-point numbers are stored as 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 Serialization 0std::uint64_t(0)0-0std::int64_t(0)00.0double(0.0)0.0-0.0double(-0.0)-0.00E0double(0.0)0.0-0E0double(-0.0)-0.0
That is, -0 is stored as a signed integer, but the serialization does not reproduce the -.
Integer numbers are serialized as is; that is, no scientific notation is used.
Floating-point numbers are serialized as specified by 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:
The serialization can have fewer decimal places than the input: 2555.5599999999999 will be serialized as 2555.56. The reverse can also be true.
The serialization can be in scientific notation even if the input is not: 0.0000972439793401814 will be serialized as 9.72439793401814e-05. The reverse can also be true: 12345E-5 will be serialized as 0.12345.
Conversions from float to double can also introduce rounding errors:
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.
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:
JSON does not define a number type or precision (see above).
C++ also allows to silently convert between number types.
Conditional number conversion
The code above can be solved by explicitly checking the nature of the value with members such as is_number_integer() or is_number_unsigned():
// check if jd is really integer-valued\nif (jd.is_number_integer())\n{\n // if so, do the conversion and use i\n std::int64_t i = jd.template get<std::int64_t>();\n // ...\n}\nelse\n{\n // otherwise, take appropriate action\n // ...\n}\n
Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings.
(Example taken from #777.)
"},{"location":"features/types/number_handling/#determine-number-types","title":"Determine number types","text":"
As the example in Number conversion shows, there are different functions to determine the type of the stored number:
is_number() returns true for any number type
is_number_integer() returns true for signed and unsigned integers
is_number_unsigned() returns true for unsigned integers only
is_number_float() returns true for floating-point numbers
type_name() returns \"number\" for any number type
type() returns a different enumerator of value_t for all number types
function unsigned integer signed integer floating-point string is_number()truetruetruefalseis_number_integer()truetruefalsefalseis_number_unsigned()truefalsefalsefalseis_number_float()falsefalsetruefalsetype_name()\"number\"\"number\"\"number\"\"string\"type()number_unsignednumber_integernumber_floatstring"},{"location":"features/types/number_handling/#template-number-types","title":"Template number types","text":"
The number types can be changed with template parameters.
position number type default type possible values 5 signed integers std::int64_tstd::int32_t, std::int16_t, etc. 6 unsigned integers std::uint64_tstd::uint32_t, std::uint16_t, etc. 7 floating-point doublefloat, long double
Constraints on number types
The type for signed integers must be convertible from long long. The type for floating-point numbers is used in case of overflow.
The type for unsigned integers must be convertible from unsigned long long. The type for floating-point numbers is used in case of overflow.
The types for signed and unsigned integers must be distinct, see #2573.
Only 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.
This page is still under construction. Its goal is to provide a high-level overview of the library's architecture. This should help new contributors to get an idea of the used concepts and where to make changes.
Values are stored as a tagged union of value_t and json_value.
/// the type of the current element\nvalue_t m_type = value_t::null;\n\n/// the value of the current element\njson_value m_value = {};\n
with
enum class value_t : std::uint8_t\n{\n null, ///< null value\n object, ///< object (unordered set of name/value pairs)\n array, ///< array (ordered collection of values)\n string, ///< string value\n boolean, ///< boolean value\n number_integer, ///< number value (signed integer)\n number_unsigned, ///< number value (unsigned integer)\n number_float, ///< number value (floating-point)\n binary, ///< binary array (ordered collection of bytes)\n discarded ///< discarded by the parser callback function\n};\n\nunion json_value {\n /// object (stored with pointer to save storage)\n object_t *object;\n /// array (stored with pointer to save storage)\n array_t *array;\n /// string (stored with pointer to save storage)\n string_t *string;\n /// binary (stored with pointer to save storage)\n binary_t *binary;\n /// boolean\n boolean_t boolean;\n /// number (integer)\n number_integer_t number_integer;\n /// number (unsigned integer)\n number_unsigned_t number_unsigned;\n /// number (floating-point)\n number_float_t number_float;\n};\n
Input is read via input adapters that abstract a source with a common interface:
/// read a single character\nstd::char_traits<char>::int_type get_character() noexcept;\n\n/// read multiple characters to a destination buffer and\n/// returns the number of characters successfully read\ntemplate<class T>\nstd::size_t get_elements(T* dest, std::size_t count = 1);\n
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.
Peregrine Lunar Lander Flight 01 - The library was utilized for payload management in the Peregrine Moon Lander, developed by Astrobotic Technology and launched as part of NASA's Commercial Lunar Payload Services (CLPS) program. After six days in orbit, the spacecraft was intentionally redirected into Earth's atmosphere, where it burned up over the Pacific Ocean on January 18, 2024.
Alexa Auto SDK, a software development kit enabling the integration of Alexa into automotive systems
Apollo, a framework for building autonomous driving systems
Automotive Grade Linux (AGL): a collaborative open-source platform for automotive software development
Genesis Motor (infotainment), a luxury automotive brand
Hyundai (infotainment), a global automotive brand
Kia (infotainment), a global automotive brand
Mercedes-Benz Operating System (MB.OS), a core component of the vehicle software ecosystem from Mercedes-Benz
Rivian (infotainment), an electric vehicle manufacturer
Suzuki (infotainment), a global automotive and motorcycle manufacturer
"},{"location":"home/customers/#gaming-and-entertainment","title":"Gaming and Entertainment","text":"
Assassin's Creed: Mirage: a stealth-action game set in the Middle East, focusing on the journey of a young assassin with classic parkour and stealth mechanics
Chasm: The Rift: a first-person shooter blending horror and adventure, where players navigate dark realms and battle monsters
College Football 25: a college football simulation game featuring gameplay that mimics real-life college teams and competitions
Concepts: a digital sketching app designed for creative professionals, offering flexible drawing tools for illustration, design, and brainstorming
Depthkit: a tool for creating and capturing volumetric video, enabling immersive 3D experiences and interactive content
immersivetech: a technology company focused on immersive experiences, providing tools and solutions for virtual and augmented reality applications
LOOT, a tool for optimizing the load order of game plugins, commonly used in The Elder Scrolls and Fallout series
Madden NFL 25: a sports simulation game capturing the excitement of American football with realistic gameplay and team management features
Marne, an unofficial private server platform for hosting custom Battlefield 1 game experiences
Minecraft, a popular sandbox video game
NHL 22: a hockey simulation game offering realistic gameplay, team management, and various modes to enhance the hockey experience
Pixelpart: a 2D animation and video compositing software that allows users to create animated graphics and visual effects with a focus on simplicity and ease of use
Red Dead Redemption II: an open-world action-adventure game following an outlaw's story in the late 1800s, emphasizing deep storytelling and immersive gameplay
Tactics Ogre: Reborn, a tactical role-playing game featuring strategic battles and deep storytelling elements
Throne and Liberty, an MMORPG that offers an expansive fantasy world with dynamic gameplay and immersive storytelling
Unity Vivox, a communication service that enables voice and text chat functionality in multiplayer games developed with Unity
Zool: Redimensioned: a modern reimagining of the classic platformer featuring fast-paced gameplay and vibrant environments
Audinate: a provider of networked audio solutions specializing in Dante technology, which facilitates high-quality digital audio transport over IP networks
Cisco Webex Desk Camera, a video camera designed for professional-quality video conferencing and remote collaboration
Philips Hue Personal Wireless Lighting: a smart lighting system for customizable and wireless home illumination
Ray-Ban Meta Smart glasses, a pair of smart glasses designed for capturing photos and videos with integrated connectivity and social features
Siemens SINEMA Remote Connect, a remote connectivity solution for monitoring and managing industrial networks and devices securely
Sony PlayStation 4, a gaming console developed by Sony that offers a wide range of games and multimedia entertainment features
Sony Virtual Webcam Driver for Remote Camera, a software driver that enables the use of Sony cameras as virtual webcams for video conferencing and streaming
Apple iOS and macOS, a family of operating systems developed by Apple, including iOS for mobile devices and macOS for desktop computers
Google Fuchsia, an open-source operating system developed by Google, designed to be secure, updatable, and adaptable across various devices
SerenityOS, an open-source operating system that aims to provide a simple and beautiful user experience with a focus on simplicity and elegance
Yocto: a Linux-based build system for creating custom operating systems and software distributions, tailored for embedded devices and IoT applications
"},{"location":"home/customers/#development-tools-and-ides","title":"Development Tools and IDEs","text":"
Accentize SpectralBalance, an adaptive speech analysis tool designed to enhance audio quality by optimizing frequency balance in recordings
Arm Compiler for Linux, a software development toolchain for compiling and optimizing applications on Arm-based Linux systems
BBEdit, a professional text and code editor for macOS
CoderPad, a collaborative coding platform that enables real-time code interviews and assessments for developers; the library is included in every CoderPad instance and can be accessed with a simple #include \"json.hpp\"
Compiler Explorer, a web-based tool that allows users to write, compile, and visualize the assembly output of code in various programming languages; the library is readily available and accessible with the directive #include <nlohmann/json.hpp>.
GitHub CodeQL, a code analysis tool used for identifying security vulnerabilities and bugs in software through semantic queries
Hex-Rays: a reverse engineering toolset for analyzing and decompiling binaries, primarily used for security research and vulnerability analysis
ImHex, a hex editor designed for reverse engineering, providing advanced features for data analysis and manipulation
Intel GPA Framework, a suite of cross-platform tools for capturing, analyzing, and optimizing graphics applications across different APIs
Meta Yoga, a layout engine that facilitates flexible and efficient user interface design across multiple platforms
MKVToolNix, a set of tools for creating, editing, and inspecting MKV (Matroska) multimedia container files
NVIDIA Nsight Compute, a performance analysis tool for CUDA applications that provides detailed insights into GPU performance metrics
Notepad++, a free source code editor that supports various programming languages
OpenRGB, an open source RGB lighting control that doesn't depend on manufacturer software
OpenTelemetry C++: a library for collecting and exporting observability data in C++, enabling developers to implement distributed tracing and metrics in their application
Qt Creator, an IDE for developing applications using the Qt application framework
Scanbot SDK: a software development kit (SDK) that provides tools for integrating advanced document scanning and barcode scanning capabilities into applications
"},{"location":"home/customers/#machine-learning-and-ai","title":"Machine Learning and AI","text":"
Apple Core ML Tools, a set of tools for converting and configuring machine learning models for deployment in Apple's Core ML framework
Avular Mobile Robotics: a platform for developing and deploying mobile robotics solutions
Google gemma.cpp, a lightweight C++ inference engine designed for running AI models from the Gemma family
llama.cpp, a C++ library designed for efficient inference of large language models (LLMs), enabling streamlined integration into applications
MLX, an array framework for machine learning on Apple silicon
Mozilla llamafile, a tool designed for distributing and executing large language models (LLMs) efficiently using a single file format
NVIDIA ACE, a suite of real-time AI solutions designed for the development of interactive avatars and digital human applications, enabling scalable and sophisticated user interactions
Peer: a platform offering personalized AI assistants for interactive learning and creative collaboration
stable-diffusion.cpp: a C++ implementation of the Stable Diffusion image generation model
TanvasTouch: a software development kit (SDK) that enables developers to create tactile experiences on touchscreens, allowing users to feel textures and physical sensations in a digital environment
TensorFlow, a machine learning framework that facilitates the development and training of models, supporting data serialization and efficient data exchange between components
"},{"location":"home/customers/#scientific-research-and-analysis","title":"Scientific Research and Analysis","text":"
BLACK, a bounded linear temporal logic (LTL) satisfiability checker
CERN Atlas Athena, a software framework used in the ATLAS experiment at the Large Hadron Collider (LHC) for performance monitoring
KAMERA: a platform for synchronized data collection and real-time deep learning to map marine species like polar bears and seals, aiding Arctic ecosystem research
KiCad: a free and open-source software suite for electronic design automation
MeVisLab: a software framework for medical image processing and visualization.
OpenPMD API: a versatile programming interface for accessing and managing scientific data, designed to facilitate the efficient storage, retrieval, and sharing of simulation data across various applications and platforms
ParaView: an open-source tool for large-scale data visualization and analysis across various scientific domains
QGIS: a free and open-source geographic information system (GIS) application that allows users to create, edit, visualize, and analyze geospatial data across a variety of formats
VTK: a software library for 3D computer graphics, image processing, and visualization
VolView: a lightweight application for interactive visualization and analysis of 3D medical imaging data.
"},{"location":"home/customers/#business-and-productivity-software","title":"Business and Productivity Software","text":"
ArcGIS PRO, a desktop geographic information system (GIS) application developed by Esri for mapping and spatial analysis
Autodesk Desktop, a software platform developed by Autodesk for creating and managing desktop applications and services
Check Point: a cybersecurity company specializing in threat prevention and network security solutions, offering a range of products designed to protect enterprises from cyber threats and ensure data integrity
Microsoft Office for Mac, a suite of productivity applications developed by Microsoft for macOS, including tools for word processing, spreadsheets, and presentations
Nexthink Infinity: a digital employee experience management platform for monitoring and improving IT performance
Sophos Connect Client: a secure VPN client from Sophos that allows remote users to connect to their corporate network, ensuring secure access to resources and data
Stonebranch: a cloud-based cybersecurity solution that integrates backup, disaster recovery, and cybersecurity features to protect data and ensure business continuity for organizations
Tablecruncher: a data analysis tool that allows users to import, analyze, and visualize spreadsheet data, offering interactive features for better insights and decision-making
magicplan, a mobile application for creating floor plans and interior designs using augmented reality
"},{"location":"home/customers/#databases-and-big-data","title":"Databases and Big Data","text":"
ADIOS2: a data management framework designed for high-performance input and output operations
Cribl Stream: a real-time data processing platform that enables organizations to collect, route, and transform observability data, enhancing visibility and insights into their systems
DB Browser for SQLite, a visual open-source tool for creating, designing, and editing SQLite database files
MySQL Connector/C++, a C++ library for connecting and interacting with MySQL databases
MySQL NDB Cluster, a distributed database system that provides high availability and scalability for MySQL databases
PrestoDB, a distributed SQL query engine designed for large-scale data analytics, originally developed by Facebook
ROOT Data Analysis Framework, an open-source data analysis framework widely used in high-energy physics and other fields for data processing and visualization
"},{"location":"home/customers/#simulation-and-modeling","title":"Simulation and Modeling","text":"
Arcturus HoloSuite, a software toolset for capturing, editing, and streaming volumetric video, featuring advanced compression technologies for high-quality 3D content creation
azul, a fast and efficient 3D city model viewer designed for visualizing urban environments and spatial data
Blender, a free and open-source 3D creation suite for modeling, animation, rendering, and more
cpplot, a library for creating interactive graphs and charts in C++, which can be viewed in web browsers
NVIDIA Omniverse, a platform for 3D content creation and collaboration that enables real-time simulations and interactive experiences across various industries
Pixar Renderman, a photorealistic 3D rendering software developed by Pixar, widely used in the film industry for creating high-quality visual effects and animations
ROS - Robot Operating System, a set of software libraries and tools that assist in developing robot applications
UBS, a multinational financial services and banking company
GAMS: a high-performance mathematical modeling system for optimization and decision support
M-Star: a computational fluid dynamics software for simulating and analyzing fluid flow
MapleSim CAD Toolbox: a software extension for MapleSim that integrates CAD models, allowing users to import, manipulate, and analyze 3D CAD data within the MapleSim environment for enhanced modeling and simulation
Kitware SMTK: a software toolkit for managing simulation models and workflows in scientific and engineering applications
"},{"location":"home/customers/#enterprise-and-cloud-applications","title":"Enterprise and Cloud Applications","text":"
Acronis Cyber Protect Cloud: an all-in-one data protection solution that combines backup, disaster recovery, and cybersecurity to safeguard business data from threats like ransomware
Baereos: a backup solution that provides data protection and recovery options for various environments, including physical and virtual systems
Bitdefender Home Scanner, a tool from Bitdefender that scans devices for malware and security threats, providing a safeguard against potential online dangers
Citrix Provisioning: a solution that streamlines the delivery of virtual desktops and applications by allowing administrators to manage and provision resources efficiently across multiple environments
Citrix Virtual Apps and Desktops, a solution from Citrix that delivers virtual apps and desktops
Cyberarc: a security solution that specializes in privileged access management, enabling organizations to control and monitor access to critical systems and data, thereby enhancing overall cybersecurity posture
Elster: a digital platform developed by German tax authorities for secure and efficient electronic tax filing and management using secunet protect4use
Egnyte Desktop: a secure cloud storage solution designed for businesses, enabling file sharing, collaboration, and data management across teams while ensuring compliance and data protection
Ethereum Solidity, a high-level, object-oriented programming language designed for implementing smart contracts on the Ethereum platform
Inciga: a monitoring tool for IT infrastructure, designed to provide insights into system performance and availability through customizable dashboards and alerts
Intel Accelerator Management Daemon for VMware ESXi: a management tool designed for monitoring and controlling Intel hardware accelerators within VMware ESXi environments, optimizing performance and resource allocation
Juniper Identity Management Service
Microsoft Azure IoT SDK, a collection of tools and libraries to help developers connect, build, and deploy Internet of Things (IoT) solutions on the Azure cloud platform
Microsoft WinGet, a command-line utility included in the Windows Package Manager
Pointr: a platform for indoor positioning and navigation solutions, offering tools and SDKs for developers to create location-based applications
secunet protect4use: a secure, passwordless multi-factor authentication solution that transforms smartphones into digital keyrings, ensuring high security for online services and digital identities
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.
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.
Example
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
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.
[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.
This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.
Exceptions have ids 1xx.
Byte index
Member byte holds the byte index of the last read character in the input file.
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).
Example
The following code shows how a parse_error exception can be caught.
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
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
Make sure the input is correctly read. Try to write the input to standard output to check if, for instance, the input file was successfully opened.
Paste the input to a JSON validator like http://jsonlint.com or a tool like jq.
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.
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
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
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
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
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
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
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
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
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
This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx.
Example
The following code shows how a type_error exception can be caught.
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
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
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
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
The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON)
Example messages
Serializing null to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null\n
Serializing [1,2,3] to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array\n
Tip
Encapsulate the JSON value in an object. That is, instead of serializing true, serialize {\"value\": true}
"},{"location":"home/exceptions/#out-of-range","title":"Out of range","text":"
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx.
Example
The following code shows how an out_of_range exception can be caught.
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.
This exception previously indicated that the UBJSON and BSON binary formats did not support integer numbers greater than 9223372036854775807 due to limitations in the implemented mapping. However, these limitations have since been resolved, and this exception no longer occurs.
Exception cannot occur any more
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers.
Since version 3.12.0, integer numbers beyond int64 are serialized as uint64 BSON numbers.
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.
Why is the parser complaining about a Chinese character?
Does the library support Unicode?
I get an exception [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:
Only UTF-8 encoded input is supported which is the default encoding for JSON according to RFC 8259.
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.
Other encodings such as Latin-1 or ISO 8859-1 are not supported and will yield parse or serialization errors.
Unicode noncharacters will not be replaced by the library.
Invalid surrogates (e.g., incomplete pairs such as \\uDEAD) will yield parse errors.
The strings stored in the library are UTF-8 encoded. When using the default string type (std::string), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.
When you store strings with different encodings in the library, calling 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/#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.
It seems that precision is lost when serializing a double.
Can I change the precision for floating-point serialization?
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.
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.
Why do I get a compilation error 'to_string' is not a member of 'std' (or similarly, for strtod or strtof)?
Why does the code not compile with MinGW or Android SDK?
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.
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.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
Fixed a bug that lead to stack overflow for deeply nested JSON values (objects, array) by changing the implementation of the destructor from a recursive to an iterative approach. #832, #1419, #1835
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.
Add overload of the contains function to check if a JSON pointer is valid without throwing exceptions, just like its counterpart for object keys. #1600
Add a function to_string to allow for generic conversion to strings. #916 #1585
Add return value for the emplace_back function, returning a reference to the added element just like C++17 is introducing this for std::vector. #1609
Add info how to use the library with the pacman package manager on MSYS2. #1670
Use GNUInstallDirs to set library install directories. #1673
Fix links in the README. #1620 #1621 #1622 #1623 #1625
Mention json type on the documentation start page. #1616
Complete documentation of value() function with respect to type_error.302 exception. #1601
Fix links in the documentation. #1598
Add regression tests for MSVC. #1543 #1570
Use CircleCI for continuous integration.
Use Doozer for continuous integration on Linux (CentOS, Raspbian, Fedora)
Add tests to check each CMake flag (JSON_BuildTests, JSON_Install, JSON_MultipleHeaders, JSON_Sanitizer, JSON_Valgrind, JSON_NoExceptions, JSON_Coverage).
Use Hedley to avoid re-inventing several compiler-agnostic feature macros like 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.
Build and run tests on AppVeyor in DEBUG and RELEASE mode.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
Overworked the public interface for JSON Pointers. The creation of JSON Pointers is simplified with operator/ and operator/=. JSON Pointers can be inspected with empty, back, and parent_pointer, and manipulated with push_back and pop_back. #1434
Added a boolean method contains to check whether an element exists in a JSON object with a given key. Returns false when called on non-object types. #1471 #1474
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
This release introduces the support for structured bindings and reading from FILE*. Besides, a few bugs have been fixed. All changes are backward-compatible.
Added a warning for implicit conversions to the documentation: It is not recommended to use implicit conversions when reading from a JSON value. Details about this recommendation can be found here. #1363
Fixed typos in the documentation. #1329 #1380 #1382
Fixed a C4800 warning. #1364
Fixed a -Wshadow warning #1346
Wrapped std::snprintf calls to avoid error in MSVC. #1337
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
BSON (Binary JSON) is next to CBOR, MessagePack, and UBJSON the fourth binary (de)serialization format supported by the library.
Adjustable error handlers for invalid Unicode allows to specify the behavior when invalid byte sequences are serialized.
Simplified enum/JSON mapping with a macro in case the default mapping to integers is not desired.
Furthermore, some effort has been invested in improving the parse error messages. Besides, a few bugs have been fixed. All changes are backward-compatible.
The library can read and write a subset of BSON (Binary JSON). All data types known from JSON are supported, whereas other types more tied to MongoDB such as timestamps, object ids, or binary data are currently not implemented. See the README for examples. #1244 #1320
The behavior when the library encounters an invalid Unicode sequence during serialization can now be controlled by defining one of three Unicode error handlers: (1) throw an exception (default behavior), (2) replace invalid sequences by the Unicode replacement character (U+FFFD), or (3) ignore/filter invalid sequences. See the documentation of the dump function for examples. #1198 #1314
To easily specify a user-defined enum/JSON mapping, a macro NLOHMANN_JSON_SERIALIZE_ENUM has been introduced. See the README section for more information. #1208 #1323
The diagnosis messages for parse errors have been improved: error messages now indicated line/column positions where possible (in addition to a byte count) and also the context in which the error occurred (e.g., \"while parsing a JSON string\"). Example: error parse 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 #1303
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
The library can now also built with GCC 4.8. Though this compiler does not fully support C++11, it can successfully compile and run the test suite. Note that bug 57824 in GCC 4.8 still forbids to use multiline raw strings in arguments to macros. #1257
Added new function 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 #1231
Added documentation on CMake integration of the library. #1270
Changed the CMake file to use find_package(nlohmann_json) without installing the library. #1202
Improved error messages in case operator[] is used with the wrong combination (json.exception.type_error.305) of JSON container type and argument type. Example: \"cannot use operator[] with a string argument\". #1220 #1221
Added a license and version information to the Meson build file. #1252
Removed static assertions to indicated missing to_json or from_json functions as such assertions do not play well with SFINAE. These assertions also led to problems with GMock. #960 #1212 #1228
The test suite now does not wait forever if run in a wrong directory and input files are not found. #1262
The test suite does not show deprecation warnings for deprecated functions which frequently led to confusion. #1271
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
support to parse from wide string types std::wstring, std::u16string, and std::u32string; the input will be converted to UTF-8 (#1031)
added support for std::string_view when using C++17 (#1028)
allow to roundtrip 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)
improved continuous integration: added builders for Xcode 9.3 and 9.4, added builders for GCC 8 and Clang 6, added builder for MinGW, added builders for MSVC targeting x86
required CMake version is now at least 3.8 (#1040)
overworked CMake file wrt. packaging (#1048)
added package managers: Spack (#1041) and CocoaPods (#1148)
fixed Meson include directory (#1142)
preprocessor macro JSON_SKIP_UNSUPPORTED_COMPILER_CHECK can skip the rejection of unsupported compilers - use at your own risk! (#1128)
preprocessor macro JSON_INTERNAL_CATCH/JSON_INTERNAL_CATCH_USER allows to control the behavior of exception handling inside the library (#1187)
added note on char to JSON conversion
added note how to send security-related issue via encrypted email
removed dependency to std::stringstream (#1117)
added SPDX-License-Identifier
added updated JSON Parsing Test Suite, described in Parsing JSON is a Minefield \ud83d\udca3
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
Fixed a memory leak occurring in the parser callback (#1001).
Different specializations of basic_json (e.g., using different template arguments for strings or objects) can now be used in assignments (#972, #977, #986).
Fixed a logical error in an iterator range check (#992).
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
Fixed parsing of CBOR strings with indefinite length (#961). Earlier versions of this library misinterpreted the CBOR standard and rejected input with the 0x7F start byte.
Fixed user-defined conversion to vector type (#924, #969). A wrong SFINAE check rejected code though a user-defined conversion was provided.
Fixed documentation of the parser behavior for objects with duplicate keys (#963). The exact behavior is not specified by RFC 8259 and the library now also provides no guarantee which object key is stored.
Added check to detect memory overflow when parsing UBJSON containers (#962). The optimized UBJSON format allowed for specifying an array with billions of null elements with a few bytes and the library did not check whether this size exceeded max_size().
Code coverage is now calculated for the individual header files, allowing to find uncovered lines more quickly than by browsing through the single header version (#953, #957).
A Makefile target run_benchmarks was added to quickly build and run the benchmark suite.
The documentation was harmonized with respect to the header inclusion (#955). Now all examples and the README use #include <nlohmann/json.hpp> to allow for selecting single_include or include or whatever installation folder as include directory.
Added note on how to use the library with the cget package manager (#954).
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):
Function iterator_wrapper are deprecated. Please use the member function items() instead.
Functions 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.
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.
The library now supports UBJSON (Universal Binary JSON Specification) as binary format to read and write JSON values space-efficiently. See the documentation overview for a comparison of the different formats CBOR, MessagePack, and UBJSON.
JSON Merge Patch (RFC 7386) offers an intuitive means to describe patches between JSON values (#876, #877). See the documentation of merge_patch for more information.
The library now uses the Grisu2 algorithm for printing floating-point numbers (based on the reference implementation by Florian Loitsch) which produces a short representation which is guaranteed to round-trip (#360, #935, #936).
The UTF-8 handling was further simplified by using the decoder of Bj\u00f6rn Hoehrmann in more scenarios.
Though the library is released as a single header, its development got more and more complicated. With this release, the header is split into several files and the single-header file 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).
The split further allowed for a forward declaration header include/nlohmann/json_fwd.hpp to speed up compilation times (#314).
Google Benchmark is now used for micro benchmarks (see benchmarks folder, #921).
The serialization (JSON and binary formats) now properly work with the libraries string template parameter, allowing for optimized string implementations to be used in constraint environments such as embedded software (#941, #950).
The exceptional behavior can now be overridden by defining macros 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).
To facilitate the interplay with flex and Bison, the library does not use the variable name yytext any more as it could clash with macro definitions (#933).
The library now defines 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).
A compilation error with ICC has been fixed (#947).
Typos and links in the documentation have been fixed (#900, #930).
A compiler error related to incomplete types has been fixed (#919).
The tests form the UTF-8 decoder stress test have been added to the test suite.
Function 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):
The \"copy\" operation of JSON Patch (RFC 6902) requests that it is an error if the target path points into a non-existing array or object (see #894 for a detailed description). This release fixes the implementation to detect such invalid target paths and throw an exception.
An array index in a JSON Pointer (RFC 6901) must be an integer. This release fixes the implementation to throw an exception in case invalid array indices such as 10e2 are used.
Added the JSON Patch tests from Byron Ruth and Mike McCabe.
Fixed the documentation of the at(ptr) function with JSON Pointers to list all possible exceptions (see #888).
Updated the container overview documentation (see #883).
The CMake files now respect the 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):
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.
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.
The library now uses user-defined exceptions instead of re-using those defined in <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).
When strings with a different encoding as UTF-8 were stored in JSON values, their serialization could not be parsed by the library itself, as only UTF-8 is supported. To enforce this library limitation and improve consistency, non-UTF-8 encoded strings now yield a json::type_error exception during serialization (#838). The check for valid UTF-8 is realized with code from Bj\u00f6rn Hoehrmann.
NaN and infinity values can now be stored inside the JSON value without throwing an exception. They are, however, still serialized as null (#388).
The library's iterator tag was changed from RandomAccessIterator to BidirectionalIterator (#593). Supporting RandomAccessIterator was incorrect as it assumed an ordering of values in a JSON objects which are unordered by definition.
The library does not include the standard headers <iostream>, <ctype>, and <stdexcept> any more. You may need to add these headers to code relying on them.
Removed constructor 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):
With all this breaking and deprecation out of the way, let's talk about features!
We improved the diagnostic information for syntax errors (#301). Now, an exception 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.
We added a non-throwing syntax check (#458): The new 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.
An update function was added to merge two JSON objects (#428). In case you are wondering: the name was inspired by Python.
The insert function now also supports an iterator range to add elements to an object.
The binary exchange formats CBOR and MessagePack can now be parsed from input streams and written to output streams (#477).
Input streams are now only read until the end of a JSON value instead of the end of the input (#367).
The serialization function 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).
Added built-in type support for C arrays (#502), 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:
Replaced the re2c generated scanner by a self-coded version which allows for a better modularization of the parser and better diagnostics. To test the new scanner, we added millions (8,860,608 to be exact) of unit tests to check all valid and invalid byte sequences of the Unicode standard.
Google's OSS-Fuzz is still constantly fuzz-testing the library and found several issues that were fixed in this release (#497, #504, #514, #516, #518, #519, #575).
We now also ignore UTF-8 byte order marks when parsing from an iterator range (#602).
Values can be now moved from initializer lists (#663).
Updated to Catch 1.9.7. Unfortunately, Catch2 currently has some performance issues.
The non-exceptional paths of the library are now annotated with __builtin_expect to optimize branch prediction as long as no error occurs.
MSVC now produces a stack trace in MSVC if a 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).
Overworked the documentation and added even more examples.
The build workflow now relies on CMake and CTest. Special flags can be chosen with CMake, including coverage (JSON_Coverage), compilation without exceptions (JSON_NoExceptions), LLVM sanitizers (JSON_Sanitizer), or execution with Valgrind (JSON_Valgrind).
Added support for package managers Meson (#576), Conan (#566), Hunter (#671, #829), and vcpkg (#753).
Added CI builders: Xcode 8.3, 9.0, 9.1, and 9.2; GCC 7.2; Clang 3.8, 3.9, 4.0, and 5.0; Visual Studio 2017. The library is further built with C++17 settings on the latest Clang, GCC, and MSVC version to quickly detect new issues.
"},{"location":"home/releases/#moving-from-2xx-to-300","title":"Moving from 2.x.x to 3.0.0","text":""},{"location":"home/releases/#user-defined-exceptions","title":"User-defined Exceptions","text":"
There are five different exceptions inheriting from json::exception:
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, and
json::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.
"},{"location":"home/releases/#removal-of-deprecated-functions","title":"Removal of deprecated functions","text":"
Function explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) should be replaced by the parse function: Let ss be a stream and cb be a parse callback function.
Old code:
json j(ss, cb);\n
New code:
json j = json::parse(ss, cb);\n
If no callback function is used, also the following code works:
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.
Locales that have a different character than . 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.
Numbers like 1.0 were correctly parsed as floating-point number, but serialized as integer (1). Now, floating-point numbers correctly round trip.
Parsing incorrect JSON numbers with leading 0 (0123) could yield a buffer overflow. This is fixed now by detecting such errors directly by the lexer.
Constructing a JSON value from a pointer was incorrectly interpreted as a Boolean; such code will now yield a compiler error.
Comparing a JSON number with 0 led to a comparison with null. This is fixed now.
All throw calls are now wrapped in macros.
Starting during the preparation of this release (since 8 February 2017), commits and released files are cryptographically signed with this GPG key. Previous releases have also been signed.
The parser for MessagePack and CBOR now supports an optional start index parameter to define a byte offset for the parser.
Some more warnings have been fixed. With Clang, the code compiles without warnings with -Weverything (well, it needs -Wno-documentation-unknown-command and -Wno-deprecated-declarations, but you get the point).
The code can be compiled easier with many Android NDKs by avoiding macros like UINT8_MAX which previously required defining a preprocessor macro for compilation.
The unit tests now compile two times faster.
Cotire is used to speed up the build.
Fixed a lot of typos in the documentation.
Added a section to the README file that lists all used third-party code/tools.
Added a note on constructing a string value vs. parsing.
The test suite now contains 11202597 unit tests.
Improved the Doxygen documentation by shortening the template parameters of class basic_json.
The library now offers an elegant way to convert from and to arbitrary value types. All you need to do is to implement two functions: to_json and from_json. Then, a conversion is as simple as putting a = between variables. See the README for more information and examples.
Exceptions can now be switched off. This can be done by defining the preprocessor symbol JSON_NOEXCEPTION or by passing -fno-exceptions to your compiler. In case the code would usually thrown an exception, abort() is now called.
Information on the library can be queried with the new (static) function meta() which returns a JSON object with information on the version, compiler, and platform. See the documentation for an example.
A bug in the CBOR parser was fixed which led to a buffer overflow.
The function type_name() is now public. It allows to query the type of a JSON value as string.
Added the Big List of Naughty Strings as test case.
Fixed a lot of bugs in the CBOR and MesssagePack parsers. These bugs occurred if invalid input was parsed and then could lead in buffer overflows. These bugs were found with Google's OSS-Fuzz, see #405, #407, #408, #409, #411, and #412 for more information.
We now also use the Doozer continuous integration platform.
The complete test suite is now also run with Clang's address sanitizer and undefined-behavior sanitizer.
Overworked fuzz testing; CBOR and MessagePack implementations are now fuzz-tested. Furthermore, all fuzz tests now include a round trip which ensures created output can again be properly parsed and yields the same JSON value.
Clarified documentation of find() function to always return end() when called on non-object value types.
Moved thirdparty test code to test/thirdparty directory.
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.
The library can now read and write the binary formats CBOR (Concise Binary Object Representation) and MessagePack. Both formats are aimed to produce a very compact representation of JSON which can be parsed very efficiently. See the README file for more information and examples.
simplified the iteration implementation allowing to remove dozens of lines of code
fixed an integer overflow error detected by Google's OSS-Fuzz
suppressed documentation warnings inside the library to facilitate compilation with -Wdocumentation
fixed an overflow detection error in the number parser
updated contribution guidelines to a list of frequentely asked features that will most likely be never added to the library
added a table of contents to the README file to add some structure
mentioned the many examples and the documentation in the README file
split unit tests into individual independent binaries to speed up compilation and testing
The article Parsing JSON is a Minefield \ud83d\udca3 discusses a lot of pitfalls of the JSON specification. When investigating the published test cases, a few bugs in the library were found and fixed:
Files with less than 5 bytes can now be parsed without error.
The library now properly rejects any file encoding other than UTF-8. Furthermore, incorrect surrogate pairs are properly detected and rejected.
The library now accepts all but one \"yes\" test (y_string_utf16.json): UTF-16 is not supported.
The library rejects all but one \"no\" test (n_number_then_00.json): Null bytes are treated as end of file instead of an error. This allows to parse input from null-terminated strings.
The string length passed to a user-defined string literal is now exploited to choose a more efficient constructor.
A few grammar mistakes in the README file have been fixed.
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.
overworked a helper SFINAE function
fixed some documentation issues
fixed the CMake files to allow to run the test suite outside the main project directory
Bug fix: The end of a file stream was not detected properly which led to parse errors. This bug should have been fixed with 2.0.4, but there was still a flaw in the code.
The parser/deserialization functions have been generalized to process any contiguous sequence of 1-byte elements (e.g., 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.
As a general remark on assertions: The library uses assertions to preclude undefined behavior. A prominent example for this is the 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.
In the course of cleaning up the parser/deserialization functions, the constructor 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.
Minor improvements:
Improved the performance of the serialization by avoiding the re-creation of a locale object.
Fixed two MSVC warnings. Compiling the test suite with /Wall now only warns about non-inlined functions (C4710) and the deprecation of the constructor from input-stream (C4996).
Some project internals:
The project has qualified for the Core Infrastructure Initiative Best Practices Badge. While most requirements where already satisfied, some led to a more explicit documentation of quality-ensuring procedures. For instance, static analysis is now executed with every commit on the build server. Furthermore, the contribution guidelines document how to communicate security issues privately.
The test suite has been overworked and split into several files to allow for faster compilation and analysis. The execute the test suite, simply execute make check.
The continuous integration with Travis was extended with Clang versions 3.6.0 to 3.8.1 and now includes 18 different compiler/OS combinations.
An 11-day run of American fuzzy lop checked 962 million inputs on the parser and found no issue.
The parser has been overworked, and a lot of small issues have been fixed:
Improved parser performance by avoiding recursion and using move semantics for the return value.
Unescaped control characters \\x10-\\x1f are not accepted any more.
Fixed a bug in the parser when reading from an input stream.
Improved test case coverage for UTF-8 parsing: now, all valid Unicode code points are tested both escaped and unescaped.
The precision of output streams is now preserved by the parser.
Started to check the code correctness by proving termination of important loops. Furthermore, individual assertions have been replaced by a more systematic function which checks the class invariants. Note that assertions should be switched off in production by defining the preprocessor macro NDEBUG, see the documentation of assert.
A lot of code cleanup: removed unused headers, fixed some compiler warnings, and fixed a build error for Windows-based Clang builds.
Added some compile-time checks:
Unsupported compilers are rejected during compilation with an #error command.
Static assertion prohibits code with incompatible pointer types used in get_ptr().
Improved the documentation, and adjusted the documentation script to choose the correct version of sed.
Replaced a lot of \"raw loops\" by STL functions like 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.
Implemented a value() function for JSON pointers (similar to at function).
The Homebrew formula (see Integration) is now tested for all Xcode builds (6.1 - 8.x) with Travis.
The locale of the output stream (or the internal string stream if a JSON value is serialized to a string) is now adjusted once for the whole serialization instead of for each floating-point number.
The locale of an output stream is now correctly reset to the previous value by the JSON library.
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.
\ud83d\udd1f A JSON value now uses 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.
\ud83d\udc49 JSON Pointer (RFC 6901) support: A JSON Pointer is a string (similar to an XPath expression) to address a value inside a structured JSON value. JSON Pointers can be used in 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().
\ud83c\udfe5 JSON Patch (RFC 6902) support. A JSON Patch is a JSON value that describes the required edit operations (add, change, remove, \u2026) to transform a JSON value into another one. A JSON Patch can be created with function 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.
\ud83c\uddea\ud83c\uddfa The code is now locale-independent: Floating-point numbers are always serialized with a period (.) as decimal separator and ignores different settings from the locale.
\ud83c\udf7a Homebrew support: Install the library with brew tap nlohmann/json && brew install nlohmann_json.
Added constructor to create a JSON value by parsing a std::istream (e.g., std::stringstream or std::ifstream).
Parser error messages are still very vague and contain no information on the error location.
The implemented diff function is rather primitive and does not create minimal diffs.
The name of function iteration_wrapper may change in the future and the function will be deprecated in the next release.
Roundtripping (i.e., parsing a JSON value from a string, serializing it, and comparing the strings) of floating-point numbers is not 100% accurate. Note that RFC 8259 defines no format to internally represent numbers and states not requirement for roundtripping. Nevertheless, benchmarks like Native JSON Benchmark treat roundtripping deviations as conformance errors.
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:
Fixed: Floating-point numbers are now serialized and deserialized properly such that rountripping works in more cases. [#185, #186, #190, #191, #194]
Added: The code now contains assertions to detect undefined behavior during development. As the standard function assert is used, the assertions can be switched off by defining the preprocessor symbol NDEBUG during compilation. [#168]
Added: It is now possible to get a reference to the stored values via the newly added function get_ref(). [#128, #184]
Fixed: Access to object values via keys (operator[]) now works with all kind of string representations. [#171, #189]
Fixed: The code now compiles again with Microsoft Visual Studio 2015. [#144, #167, #188]
Fixed: All required headers are now included.
Fixed: Typos and other small issues. [#162, #166, #175, #177, #179, #180]
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.
Changed: A UTF-8 byte order mark is silently ignored.
Changed: sprintf is no longer used.
Changed: iterator_wrapper also works for const objects; note: the name may change!
Changed: Error messages during deserialization have been improved.
Added: The parse function now also works with type std::istream&&.
Added: Function 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.
Added: Public functions are tagged with the version they were introduced. This shall allow for better versioning in the future.
Added: All public functions and types are documented (see http://nlohmann.github.io/json/doxygen/) including executable examples.
Added: Allocation of all types (in particular arrays, strings, and objects) is now exception-safe.
Added: They descriptions of thrown exceptions have been overworked and are part of the tests suite and documentation.
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.txt
cmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\nfind_package(nlohmann_json 3.11.3 REQUIRED)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n
The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.
To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.
Example
CMakeLists.txt
cmake_minimum_required(VERSION 3.1)\nproject(ExampleProject LANGUAGES CXX)\n\n# If you only include this third party in PRIVATE source files, you do not need to install it\n# when your main project gets installed.\nset(JSON_Install OFF CACHE INTERNAL \"\")\n\nadd_subdirectory(nlohmann_json)\n\nadd_executable(example example.cpp)\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n
Note
Do not use include(nlohmann_json/CMakeLists.txt), since that carries with it unintended consequences that will break the build. It is generally discouraged (although not necessarily well documented as such) to use include(...) for pulling in other CMake projects anyways.
To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.
Example
CMakeLists.txt
project(ExampleProject LANGUAGES CXX)\n\noption(EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF)\n\nadd_subdirectory(thirdparty)\n\nadd_executable(example example.cpp)\n\n# Note that the namespaced target will always be available regardless of the import method\ntarget_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)\n
thirdparty/CMakeLists.txt
if(EXAMPLE_USE_EXTERNAL_JSON)\n find_package(nlohmann_json 3.11.3 REQUIRED)\nelse()\n set(JSON_BuildTests OFF CACHE INTERNAL \"\")\n add_subdirectory(nlohmann_json)\nendif()\n
thirdparty/nlohmann_json is then a complete copy of this source tree.
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.
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.
Enable the (incorrect) legacy comparison behavior of discarded JSON values by defining macro JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON. This option is OFF by default.
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.
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.
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}).
DeprecatedFuture-proof
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_pointerp with a string s, convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!=.
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.
DeprecatedFuture-proof
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.
DeprecatedFuture-proof
using my_json = nlohmann::basic_json<std::map, std::vector, my_string_type>;\nnlohmann::json_pointer<my_json> 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.
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.
DeprecatedFuture-proof
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.
Implicit conversions via operator ValueType will be switched off by default in the next major release of the library.
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get, get_to, get_ref, or get_ptr.
DeprecatedFuture-proofFuture-proof (alternative)
nlohmann::json j = \"Hello, world!\";\nstd::string s = j;\n
nlohmann::json j = \"Hello, world!\";\nauto s = j.template get<std::string>();\n
You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get.
"},{"location":"integration/migration_guide/#import-namespace-literals-for-udls","title":"Import namespace literals for UDLs","text":"
The user-defined string literals operator\"\"_json and operator\"\"_json_pointer will be removed from the global namespace in the next major release of the library.
DeprecatedFuture-proof
nlohmann::json j = \"[1,2,3]\"_json;\n
using namespace nlohmann::literals;\nnlohmann::json j = \"[1,2,3]\"_json;\n
To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.
"},{"location":"integration/migration_guide/#do-not-hard-code-the-complete-library-namespace","title":"Do not hard-code the complete library namespace","text":"
The nlohmann namespace contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use nlohmann as namespace or, when the exact version and configuration is relevant, use macro NLOHMANN_JSON_NAMESPACE to denote the namespace.
"},{"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.
Availalbe versions: current version and select older versions (see WrapDB)
The package is update automatically from file meson.build.
File issues at the library issue tracker
Meson website
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 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, 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.
use bazel_dep, git_override, or local_path_override
Any version, that is available via Bazel Central Registry
File issues at the library issue tracker
Bazel website
This repository provides a Bazel MODULE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced within a MODULE.bazel by rules such as archive_override, git_override, or local_path_override. To use the library you need to depend on the target @nlohmann_json//:json (i.e., via deps attribute).
Example
Create the following files:
BUILD
cc_binary(\n name = \"main\",\n srcs = [\"example.cpp\"],\n deps = [\"@nlohmann_json//:json\"],\n)\n
WORKSPACE
bazel_dep(name = \"nlohmann_json\", version = \"3.11.3.bcr.1\")\n
Availalbe versions: current version and older versions (see Conan Center)
The package is update automatically via this recipe.
File issues at the Conan Center issue tracker
Conan website
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.
Availalbe versions: current version and older versions
The package is updated with every release.
File issues at the cget issue tracker
cget website
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).
If you are using NuGet, you can use the package nlohmann.json with
dotnet add package nlohmann.json\n
Example
Probably the easiest way to use NuGet packages is through Visual Studio graphical interface. Just right-click on a project (any C++ project would do) in \u201cSolution Explorer\u201d and select \u201cManage NuGet Packages\u2026\u201d
Now you can click on \u201cBrowse\u201d tab and find the package you like to install.
Most of the packages in NuGet gallery are .NET packages and would not be useful in a C++ project. Microsoft recommends adding \u201cnative\u201d and \u201cnativepackage\u201d tags to C++ NuGet packages to distinguish them, but even adding \u201cnative\u201d to search query would still show many .NET-only packages in the list.
Nevertheless, after finding the package you want, click on \u201cInstall\u201d button and accept confirmation dialogs. After the package is successfully added to the projects, you should be able to build and execute the project without the need for making any more changes to build settings.
Note
A few notes:
NuGet packages are installed per project and not system-wide. The header and binaries for the package are only available to the project it is added to, and not other projects (obviously unless we add the package to those projects as well)
One of the many great things about your elegant work is that it is a header-only library, which makes deployment very straightforward. In case of libraries which need binary deployment (.lib, .dll and .pdb for debug info) the different binaries for each supported compiler version must be added to the NuGet package. Some library creators cram binary versions for all supported Visual C++ compiler versions in the same package, so a single package will support all compilers. Some others create a different package for each compiler version (and you usually see things like \u201cv140\u201d or \u201cvc141\u201d in package name to clarify which VC++ compiler this package supports).
Packages can have dependency to other packages, and in this case, NuGet will install all dependencies as well as the requested package recursively.
What happens behind the scenes
After you add a NuGet package, three changes occur in the project source directory. Of course, we could make these changes manually instead of using GUI:
A packages.config file will be created (or updated to include the package name if one such file already exists). This file contains a list of the packages required by this project (name and minimum version) and must be added to the project source code repository, so if you move the source code to a new machine, MSBuild/NuGet knows which packages it has to restore (which it does automatically before each build).
A packages folder which contains actual files in the packages (these are header and binary files required for a successful build, plus a few metadata files). In case of this library for example, it contains json.hpp:
Note
This directory should not be added to the project source code repository, as it will be restored before each build by MSBuild/NuGet. If you go ahead and delete this folder, then build the project again, it will magically re-appear!
Project MSBuild makefile (which for Visual C++ projects has a .vcxproj extension) will be updated to include settings from the package.
The important bit for us here is line 170, which tells MSBuild to import settings from packages\\nlohmann.json.3.5.0\\build\\native\\nlohmann.json.targets file. This is a file the package creator created and added to the package (you can see it is one of the two files I created in this repository, the other just contains package attributes like name and version number). What does it contain?
For our header-only repository, the only setting we need is to add our include directory to the list of AdditionalIncludeDirectories:
For libraries with binary files, we will need to add .lib files to linker inputs and add settings to copy .dll and other redistributable files to output directory, if needed.
There are other changes to the makefile as well:
Lines 165-167 add the packages.config as one of project files (so it is shown in Solution Explorer tree view). It is added as None (no build action) and removing it wouldn\u2019t affect build.
Lines 172-177 check to ensure the required packages are present. This will display a build error if package directory is empty (for example when NuGet cannot restore packages because Internet connection is down). Again, if you omit this section, the only change in build would be a more cryptic error message if build fails.
Note
Changes to .vcxproj makefile should also be added to project source code repository.
As you can see, the mechanism NuGet uses to modify project settings is through MSBuild makefiles, so using NuGet with other build systems and compilers (like CMake) as a dependency manager is either impossible or more problematic than useful.
Please refer to this extensive description for more information.
If you are using MSYS2, you can use the mingw-w64-nlohmann-json package, 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.
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, 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.
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.
Warning
The module is outdated as the respective pod has not been updated in years.