diff --git a/api/macros/json_has_static_rtti/index.html b/api/macros/json_has_static_rtti/index.html new file mode 100644 index 000000000..aeda43ed3 --- /dev/null +++ b/api/macros/json_has_static_rtti/index.html @@ -0,0 +1,6 @@ + JSON_HAS_STATIC_RTTI - JSON for Modern C++
Skip to content

JSON_HAS_STATIC_RTTI

#define JSON_HAS_STATIC_RTTI /* value */
+

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.

Default definition

The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI.

When the macro is not defined, the library will define it to its default value.

Examples

Example

The code below forces the library to enable support for libraries with RTTI dependence:

#define JSON_HAS_STATIC_RTTI 1
+#include <nlohmann/json.hpp>
+
+...
+

Version history

  • Added in version ?.

Last update: September 24, 2023
\ No newline at end of file diff --git a/api/operator_literal_json/index.html b/api/operator_literal_json/index.html index 2b6e62d10..b162a793a 100644 --- a/api/operator_literal_json/index.html +++ b/api/operator_literal_json/index.html @@ -1,5 +1,5 @@ - operator""_json - JSON for Modern C++
Skip to content

nlohmann::operator""_json

json operator "" _json(const char* s, std::size_t n);
-

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

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

using nlohmann::literals::operator "" _json;
+ operator""_json - JSON for Modern C++       

nlohmann::operator""_json

json operator ""_json(const char* s, std::size_t n);
+

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

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

using nlohmann::literals::operator ""_json;
 using namespace nlohmann::literals;
 using namespace nlohmann::json_literals;
 using namespace nlohmann::literals::json_literals;
@@ -21,4 +21,4 @@
   "answer": 42,
   "hello": "world"
 }
-

Version history

  • Added in version 1.0.0.
  • Moved to namespace nlohmann::literals::json_literals in 3.11.0.

Last update: August 5, 2022
\ No newline at end of file +

Version history

  • Added in version 1.0.0.
  • Moved to namespace nlohmann::literals::json_literals in 3.11.0.

Last update: September 23, 2023
\ No newline at end of file diff --git a/api/operator_literal_json_pointer/index.html b/api/operator_literal_json_pointer/index.html index d050d5d2a..7a6e57713 100644 --- a/api/operator_literal_json_pointer/index.html +++ b/api/operator_literal_json_pointer/index.html @@ -1,5 +1,5 @@ - operator""_json_pointer - JSON for Modern C++
Skip to content

nlohmann::operator""_json_pointer

json_pointer operator "" _json_pointer(const char* s, std::size_t n);
-

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

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

using nlohmann::literals::operator "" _json_pointer;
+ operator""_json_pointer - JSON for Modern C++       

nlohmann::operator""_json_pointer

json_pointer operator ""_json_pointer(const char* s, std::size_t n);
+

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

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

using nlohmann::literals::operator ""_json_pointer;
 using namespace nlohmann::literals;
 using namespace nlohmann::json_literals;
 using namespace nlohmann::literals::json_literals;
@@ -19,4 +19,4 @@
     std::cout << std::setw(2) << val << '\n';
 }
 

Output:

"world"
-

See also

Version history

  • Added in version 2.0.0.
  • Moved to namespace nlohmann::literals::json_literals in 3.11.0.

Last update: August 5, 2022
\ No newline at end of file +

See also

Version history

  • Added in version 2.0.0.
  • Moved to namespace nlohmann::literals::json_literals in 3.11.0.

Last update: September 23, 2023
\ No newline at end of file diff --git a/search/search_index.json b/search/search_index.json index faf6a88ce..aaf003fe2 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-\\.]"},"docs":[{"location":"","text":"JSON for Modern C++ \u00b6","title":"JSON for Modern C++"},{"location":"#json-for-modern-c","text":"","title":"JSON for Modern C++"},{"location":"api/json/","text":"nlohmann:: json \u00b6 using json = basic_json <> ; This type is the default specialization of the basic_json class which uses the standard template types. Examples \u00b6 Example The example below demonstrates how to use the type nlohmann::json . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 } Version history \u00b6 Since version 1.0.0.","title":"json"},{"location":"api/json/#nlohmannjson","text":"using json = basic_json <> ; This type is the default specialization of the basic_json class which uses the standard template types.","title":"nlohmann::json"},{"location":"api/json/#examples","text":"Example The example below demonstrates how to use the type nlohmann::json . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 }","title":"Examples"},{"location":"api/json/#version-history","text":"Since version 1.0.0.","title":"Version history"},{"location":"api/operator_gtgt/","text":"nlohmann:: operator>>(basic_json) \u00b6 std :: istream & operator >> ( std :: istream & i , basic_json & j ); Deserializes an input stream to a JSON value. Parameters \u00b6 i (in, out) input stream to read a serialized JSON value from j (in, out) JSON value to write the deserialized input to Return value \u00b6 the stream i Exceptions \u00b6 Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails. Complexity \u00b6 Linear in the length of the input. The parser is a predictive LL(1) parser. Notes \u00b6 A UTF-8 byte order mark is silently ignored. Deprecation This function replaces function std :: istream & operator << ( basic_json & j , std :: istream & i ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i ; with i >> j ; . Examples \u00b6 Example The example below shows how a JSON value is constructed by reading a serialization from a stream. #include #include #include #include using json = nlohmann :: json ; int main () { // create stream with serialized JSON std :: stringstream ss ; ss << R \" ( { \"number\": 23, \"string\": \"Hello, world!\", \"array\": [1, 2, 3, 4, 5], \"boolean\": false, \"null\": null } ) \" ; // create JSON value and read the serialization from the stream json j ; ss >> j ; // serialize JSON std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"array\" : [ 1 , 2 , 3 , 4 , 5 ], \"boolean\" : false , \"null\" : null , \"number\" : 23 , \"string\" : \"Hello, world!\" } See also \u00b6 accept - check if the input is valid JSON parse - deserialize from a compatible input Version history \u00b6 Added in version 1.0.0. Deprecated in version 3.0.0.","title":"operator>>(basic_json)"},{"location":"api/operator_gtgt/#nlohmannoperatorbasic_json","text":"std :: istream & operator >> ( std :: istream & i , basic_json & j ); Deserializes an input stream to a JSON value.","title":"nlohmann::operator>>(basic_json)"},{"location":"api/operator_gtgt/#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","title":"Parameters"},{"location":"api/operator_gtgt/#return-value","text":"the stream i","title":"Return value"},{"location":"api/operator_gtgt/#exceptions","text":"Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails.","title":"Exceptions"},{"location":"api/operator_gtgt/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser.","title":"Complexity"},{"location":"api/operator_gtgt/#notes","text":"A UTF-8 byte order mark is silently ignored. Deprecation This function replaces function std :: istream & operator << ( basic_json & j , std :: istream & i ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i ; with i >> j ; .","title":"Notes"},{"location":"api/operator_gtgt/#examples","text":"Example The example below shows how a JSON value is constructed by reading a serialization from a stream. #include #include #include #include using json = nlohmann :: json ; int main () { // create stream with serialized JSON std :: stringstream ss ; ss << R \" ( { \"number\": 23, \"string\": \"Hello, world!\", \"array\": [1, 2, 3, 4, 5], \"boolean\": false, \"null\": null } ) \" ; // create JSON value and read the serialization from the stream json j ; ss >> j ; // serialize JSON std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"array\" : [ 1 , 2 , 3 , 4 , 5 ], \"boolean\" : false , \"null\" : null , \"number\" : 23 , \"string\" : \"Hello, world!\" }","title":"Examples"},{"location":"api/operator_gtgt/#see-also","text":"accept - check if the input is valid JSON parse - deserialize from a compatible input","title":"See also"},{"location":"api/operator_gtgt/#version-history","text":"Added in version 1.0.0. Deprecated in version 3.0.0.","title":"Version history"},{"location":"api/operator_literal_json/","text":"nlohmann:: operator\"\"_json \u00b6 json operator \"\" _json ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details. Parameters \u00b6 s (in) a string representation of a JSON object n (in) length of string s Return value \u00b6 json value parsed from s Exceptions \u00b6 The function can throw anything that parse(s, s+n) would throw. Complexity \u00b6 Linear. Examples \u00b6 Example The following code shows how to create JSON values from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"answer\" : 42 , \"hello\" : \"world\" } Version history \u00b6 Added in version 1.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"operator\"\"_json"},{"location":"api/operator_literal_json/#nlohmannoperator_json","text":"json operator \"\" _json ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.","title":"nlohmann::operator\"\"_json"},{"location":"api/operator_literal_json/#parameters","text":"s (in) a string representation of a JSON object n (in) length of string s","title":"Parameters"},{"location":"api/operator_literal_json/#return-value","text":"json value parsed from s","title":"Return value"},{"location":"api/operator_literal_json/#exceptions","text":"The function can throw anything that parse(s, s+n) would throw.","title":"Exceptions"},{"location":"api/operator_literal_json/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/operator_literal_json/#examples","text":"Example The following code shows how to create JSON values from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"answer\" : 42 , \"hello\" : \"world\" }","title":"Examples"},{"location":"api/operator_literal_json/#version-history","text":"Added in version 1.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"Version history"},{"location":"api/operator_literal_json_pointer/","text":"nlohmann:: operator\"\"_json_pointer \u00b6 json_pointer operator \"\" _json_pointer ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json_pointer ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details. Parameters \u00b6 s (in) a string representation of a JSON Pointer n (in) length of string s Return value \u00b6 json_pointer value parsed from s Exceptions \u00b6 The function can throw anything that json_pointer::json_pointer would throw. Complexity \u00b6 Linear. Examples \u00b6 Example The following code shows how to create JSON Pointers from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; auto val = j [ \"/hello\" _json_pointer ]; std :: cout << std :: setw ( 2 ) << val << '\\n' ; } Output: \"world\" See also \u00b6 json_pointer - type to represent JSON Pointers Version history \u00b6 Added in version 2.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"operator\"\"_json_pointer"},{"location":"api/operator_literal_json_pointer/#nlohmannoperator_json_pointer","text":"json_pointer operator \"\" _json_pointer ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json_pointer ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.","title":"nlohmann::operator\"\"_json_pointer"},{"location":"api/operator_literal_json_pointer/#parameters","text":"s (in) a string representation of a JSON Pointer n (in) length of string s","title":"Parameters"},{"location":"api/operator_literal_json_pointer/#return-value","text":"json_pointer value parsed from s","title":"Return value"},{"location":"api/operator_literal_json_pointer/#exceptions","text":"The function can throw anything that json_pointer::json_pointer would throw.","title":"Exceptions"},{"location":"api/operator_literal_json_pointer/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/operator_literal_json_pointer/#examples","text":"Example The following code shows how to create JSON Pointers from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; auto val = j [ \"/hello\" _json_pointer ]; std :: cout << std :: setw ( 2 ) << val << '\\n' ; } Output: \"world\"","title":"Examples"},{"location":"api/operator_literal_json_pointer/#see-also","text":"json_pointer - type to represent JSON Pointers","title":"See also"},{"location":"api/operator_literal_json_pointer/#version-history","text":"Added in version 2.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"Version history"},{"location":"api/operator_ltlt/","text":"nlohmann:: operator<<(basic_json), nlohmann:: operator<<(json_pointer) \u00b6 std :: ostream & operator << ( std :: ostream & o , const basic_json & j ); // (1) std :: ostream & operator << ( std :: ostream & o , const json_pointer & ptr ); // (2) 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. Parameters \u00b6 o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write Return value \u00b6 the stream o Exceptions \u00b6 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. None. Complexity \u00b6 Linear. Notes \u00b6 Deprecation Function std :: ostream & operator << ( std :: ostream & o , const basic_json & j ) replaces function std :: ostream & operator >> ( const basic_json & j , std :: ostream & o ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o ; with o << j ; . Examples \u00b6 Example: (1) serialize JSON value to stream The example below shows the serialization with different parameters to width to adjust the indentation level. #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // serialize without indentation std :: cout << j_object << \" \\n\\n \" ; std :: cout << j_array << \" \\n\\n \" ; // serialize with indentation std :: cout << std :: setw ( 4 ) << j_object << \" \\n\\n \" ; std :: cout << std :: setw ( 2 ) << j_array << \" \\n\\n \" ; std :: cout << std :: setw ( 1 ) << std :: setfill ( '\\t' ) << j_object << \" \\n\\n \" ; } Output: { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } Example: (2) write JSON pointer to stream The example below shows how to write a JSON pointer to a stream. #include #include using json = nlohmann :: json ; int main () { // create JSON poiner json :: json_pointer ptr ( \"/foo/bar/baz\" ); // write string representation to stream std :: cout << ptr << std :: endl ; } Output: / f oo/bar/baz Version history \u00b6 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. Added in version 3.11.0.","title":"operator<<(json_pointer)"},{"location":"api/operator_ltlt/#nlohmannoperatorbasic_json-nlohmannoperatorjson_pointer","text":"std :: ostream & operator << ( std :: ostream & o , const basic_json & j ); // (1) std :: ostream & operator << ( std :: ostream & o , const json_pointer & ptr ); // (2) 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.","title":"nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)"},{"location":"api/operator_ltlt/#parameters","text":"o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write","title":"Parameters"},{"location":"api/operator_ltlt/#return-value","text":"the stream o","title":"Return value"},{"location":"api/operator_ltlt/#exceptions","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. None.","title":"Exceptions"},{"location":"api/operator_ltlt/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/operator_ltlt/#notes","text":"Deprecation Function std :: ostream & operator << ( std :: ostream & o , const basic_json & j ) replaces function std :: ostream & operator >> ( const basic_json & j , std :: ostream & o ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o ; with o << j ; .","title":"Notes"},{"location":"api/operator_ltlt/#examples","text":"Example: (1) serialize JSON value to stream The example below shows the serialization with different parameters to width to adjust the indentation level. #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // serialize without indentation std :: cout << j_object << \" \\n\\n \" ; std :: cout << j_array << \" \\n\\n \" ; // serialize with indentation std :: cout << std :: setw ( 4 ) << j_object << \" \\n\\n \" ; std :: cout << std :: setw ( 2 ) << j_array << \" \\n\\n \" ; std :: cout << std :: setw ( 1 ) << std :: setfill ( '\\t' ) << j_object << \" \\n\\n \" ; } Output: { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } Example: (2) write JSON pointer to stream The example below shows how to write a JSON pointer to a stream. #include #include using json = nlohmann :: json ; int main () { // create JSON poiner json :: json_pointer ptr ( \"/foo/bar/baz\" ); // write string representation to stream std :: cout << ptr << std :: endl ; } Output: / f oo/bar/baz","title":"Examples"},{"location":"api/operator_ltlt/#version-history","text":"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. Added in version 3.11.0.","title":"Version history"},{"location":"api/ordered_json/","text":"nlohmann:: ordered_json \u00b6 using ordered_json = basic_json < ordered_map > ; This type preserves the insertion order of object keys. Examples \u00b6 Example The example below demonstrates how ordered_json preserves the insertion order of object keys. #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } See also \u00b6 ordered_map Object Order Version history \u00b6 Since version 3.9.0.","title":"ordered_json"},{"location":"api/ordered_json/#nlohmannordered_json","text":"using ordered_json = basic_json < ordered_map > ; This type preserves the insertion order of object keys.","title":"nlohmann::ordered_json"},{"location":"api/ordered_json/#examples","text":"Example The example below demonstrates how ordered_json preserves the insertion order of object keys. #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 }","title":"Examples"},{"location":"api/ordered_json/#see-also","text":"ordered_map Object Order","title":"See also"},{"location":"api/ordered_json/#version-history","text":"Since version 3.9.0.","title":"Version history"},{"location":"api/ordered_map/","text":"nlohmann:: ordered_map \u00b6 template < class Key , class T , class IgnoredLess = std :: less < Key > , class Allocator = std :: allocator < std :: pair < const Key , T >>> struct ordered_map : std :: vector < std :: pair < const Key , T > , Allocator > ; A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json ( nlohmann::basic_json ). Template parameters \u00b6 Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std :: map ) Allocator allocator type Member types \u00b6 key_type - key type ( Key ) mapped_type - mapped type ( T ) Container - base container type ( std :: vector < std :: pair < const Key , T > , Allocator > ) iterator const_iterator size_type value_type key_compare - key comparison function std :: equal_to < Key > // until C++14 std :: equal_to <> // since C++14 Member functions \u00b6 (constructor) (destructor) emplace operator[] at erase count find insert Examples \u00b6 Example The example shows the different behavior of std::map and nlohmann::ordered_map . #include #include // simple output function template < typename Map > void output ( const char * prefix , const Map & m ) { std :: cout << prefix << \" = { \" ; for ( auto & element : m ) { std :: cout << element . first << \":\" << element . second << ' ' ; } std :: cout << \"}\" << std :: endl ; } int main () { // create and fill two maps nlohmann :: ordered_map < std :: string , std :: string > m_ordered ; m_ordered [ \"one\" ] = \"eins\" ; m_ordered [ \"two\" ] = \"zwei\" ; m_ordered [ \"three\" ] = \"drei\" ; std :: map < std :: string , std :: string > m_std ; m_std [ \"one\" ] = \"eins\" ; m_std [ \"two\" ] = \"zwei\" ; m_std [ \"three\" ] = \"drei\" ; // output: m_ordered is ordered by insertion order, m_std is ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); // erase and re-add \"one\" key m_ordered . erase ( \"one\" ); m_ordered [ \"one\" ] = \"eins\" ; m_std . erase ( \"one\" ); m_std [ \"one\" ] = \"eins\" ; // output: m_ordered shows newly added key at the end; m_std is again ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); } Output: m_ordered = { o ne : ei ns t wo : zwei t hree : drei } m_s t d = { o ne : ei ns t hree : drei t wo : zwei } m_ordered = { t wo : zwei t hree : drei o ne : ei ns } m_s t d = { o ne : ei ns t hree : drei t wo : zwei } See also \u00b6 ordered_json Version history \u00b6 Added in version 3.9.0 to implement nlohmann::ordered_json . Added key_compare member in version 3.11.0.","title":"ordered_map"},{"location":"api/ordered_map/#nlohmannordered_map","text":"template < class Key , class T , class IgnoredLess = std :: less < Key > , class Allocator = std :: allocator < std :: pair < const Key , T >>> struct ordered_map : std :: vector < std :: pair < const Key , T > , Allocator > ; A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json ( nlohmann::basic_json ).","title":"nlohmann::ordered_map"},{"location":"api/ordered_map/#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","title":"Template parameters"},{"location":"api/ordered_map/#member-types","text":"key_type - key type ( Key ) mapped_type - mapped type ( T ) Container - base container type ( std :: vector < std :: pair < const Key , T > , Allocator > ) iterator const_iterator size_type value_type key_compare - key comparison function std :: equal_to < Key > // until C++14 std :: equal_to <> // since C++14","title":"Member types"},{"location":"api/ordered_map/#member-functions","text":"(constructor) (destructor) emplace operator[] at erase count find insert","title":"Member functions"},{"location":"api/ordered_map/#examples","text":"Example The example shows the different behavior of std::map and nlohmann::ordered_map . #include #include // simple output function template < typename Map > void output ( const char * prefix , const Map & m ) { std :: cout << prefix << \" = { \" ; for ( auto & element : m ) { std :: cout << element . first << \":\" << element . second << ' ' ; } std :: cout << \"}\" << std :: endl ; } int main () { // create and fill two maps nlohmann :: ordered_map < std :: string , std :: string > m_ordered ; m_ordered [ \"one\" ] = \"eins\" ; m_ordered [ \"two\" ] = \"zwei\" ; m_ordered [ \"three\" ] = \"drei\" ; std :: map < std :: string , std :: string > m_std ; m_std [ \"one\" ] = \"eins\" ; m_std [ \"two\" ] = \"zwei\" ; m_std [ \"three\" ] = \"drei\" ; // output: m_ordered is ordered by insertion order, m_std is ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); // erase and re-add \"one\" key m_ordered . erase ( \"one\" ); m_ordered [ \"one\" ] = \"eins\" ; m_std . erase ( \"one\" ); m_std [ \"one\" ] = \"eins\" ; // output: m_ordered shows newly added key at the end; m_std is again ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); } Output: m_ordered = { o ne : ei ns t wo : zwei t hree : drei } m_s t d = { o ne : ei ns t hree : drei t wo : zwei } m_ordered = { t wo : zwei t hree : drei o ne : ei ns } m_s t d = { o ne : ei ns t hree : drei t wo : zwei }","title":"Examples"},{"location":"api/ordered_map/#see-also","text":"ordered_json","title":"See also"},{"location":"api/ordered_map/#version-history","text":"Added in version 3.9.0 to implement nlohmann::ordered_json . Added key_compare member in version 3.11.0.","title":"Version history"},{"location":"api/adl_serializer/","text":"nlohmann:: adl_serializer \u00b6 template < typename , typename > struct adl_serializer ; Serializer that uses ADL ( Argument-Dependent Lookup ) to choose to_json / from_json functions from the types' namespaces. It is implemented similar to template < typename ValueType > struct adl_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // calls the \"to_json\" method in T's namespace } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing, but with the \"from_json\" method } }; Member functions \u00b6 from_json - convert a JSON value to any value type to_json - convert any value type to a JSON value Version history \u00b6 Added in version 2.1.0.","title":"Overview"},{"location":"api/adl_serializer/#nlohmannadl_serializer","text":"template < typename , typename > struct adl_serializer ; Serializer that uses ADL ( Argument-Dependent Lookup ) to choose to_json / from_json functions from the types' namespaces. It is implemented similar to template < typename ValueType > struct adl_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // calls the \"to_json\" method in T's namespace } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing, but with the \"from_json\" method } };","title":"nlohmann::adl_serializer"},{"location":"api/adl_serializer/#member-functions","text":"from_json - convert a JSON value to any value type to_json - convert any value type to a JSON value","title":"Member functions"},{"location":"api/adl_serializer/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/adl_serializer/from_json/","text":"nlohmann::adl_serializer:: from_json \u00b6 // (1) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j , TargetType & val ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ), void ()) // (2) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {}))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {})) 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. Parameters \u00b6 j (in) JSON value to read from val (out) value to write to Return value \u00b6 Copy of the JSON value, converted to ValueType Examples \u00b6 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() is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace 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 #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace See also \u00b6 to_json Version history \u00b6 Added in version 2.1.0.","title":"from_json"},{"location":"api/adl_serializer/from_json/#nlohmannadl_serializerfrom_json","text":"// (1) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j , TargetType & val ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ), void ()) // (2) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {}))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {})) 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.","title":"nlohmann::adl_serializer::from_json"},{"location":"api/adl_serializer/from_json/#parameters","text":"j (in) JSON value to read from val (out) value to write to","title":"Parameters"},{"location":"api/adl_serializer/from_json/#return-value","text":"Copy of the JSON value, converted to ValueType","title":"Return value"},{"location":"api/adl_serializer/from_json/#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() is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace 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 #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace","title":"Examples"},{"location":"api/adl_serializer/from_json/#see-also","text":"to_json","title":"See also"},{"location":"api/adl_serializer/from_json/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/adl_serializer/to_json/","text":"nlohmann::adl_serializer:: to_json \u00b6 template < typename BasicJsonType , typename TargetType = ValueType > static auto to_json ( BasicJsonType & j , TargetType && val ) noexcept ( noexcept ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )))) -> decltype ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )), void ()) This function is usually called by the constructors of the basic_json class. Parameters \u00b6 j (out) JSON value to write to val (in) value to read from Examples \u00b6 Example The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; json j = p ; std :: cout << j << std :: endl ; } Output: { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } See also \u00b6 from_json Version history \u00b6 Added in version 2.1.0.","title":"to_json"},{"location":"api/adl_serializer/to_json/#nlohmannadl_serializerto_json","text":"template < typename BasicJsonType , typename TargetType = ValueType > static auto to_json ( BasicJsonType & j , TargetType && val ) noexcept ( noexcept ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )))) -> decltype ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )), void ()) This function is usually called by the constructors of the basic_json class.","title":"nlohmann::adl_serializer::to_json"},{"location":"api/adl_serializer/to_json/#parameters","text":"j (out) JSON value to write to val (in) value to read from","title":"Parameters"},{"location":"api/adl_serializer/to_json/#examples","text":"Example The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; json j = p ; std :: cout << j << std :: endl ; } Output: { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" }","title":"Examples"},{"location":"api/adl_serializer/to_json/#see-also","text":"from_json","title":"See also"},{"location":"api/adl_serializer/to_json/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/basic_json/","text":"nlohmann:: basic_json \u00b6 Defined in header template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > , class CustomBaseClass = void > class basic_json ; Template parameters \u00b6 Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t Specializations \u00b6 json - default specialization ordered_json - specialization that maintains the insertion order of object keys Iterator invalidation \u00b6 Todo Requirements \u00b6 The class satisfies the following concept requirements: Basic \u00b6 DefaultConstructible : JSON values can be default constructed. The result will be a JSON null value. MoveConstructible : A JSON value can be constructed from an rvalue argument. CopyConstructible : A JSON value can be copy-constructed from an lvalue expression. MoveAssignable : A JSON value can be assigned from an rvalue argument. CopyAssignable : A JSON value can be copy-assigned from an lvalue expression. Destructible : JSON values can be destructed. Layout \u00b6 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. Library-wide \u00b6 EqualityComparable : JSON values can be compared with == , see operator== . LessThanComparable : JSON values can be compared with < , see operator< . Swappable : Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function swap . NullablePointer : JSON values can be compared against std::nullptr_t objects which are used to model the null value. Container \u00b6 Container : JSON values can be used like STL containers and provide iterator access. ReversibleContainer : JSON values can be used like STL containers and provide reverse iterator access. Member types \u00b6 adl_serializer - the default serializer value_t - the JSON type enumeration json_pointer - JSON Pointer implementation json_serializer - type of the serializer to for conversions from/to JSON error_handler_t - type to choose behavior on decoding errors cbor_tag_handler_t - type to choose how to handle CBOR tags initializer_list_t - type for initializer lists of basic_json values input_format_t - type to choose the format to parse json_sax_t - type for SAX events Exceptions \u00b6 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 Container types \u00b6 Type Definition value_type basic_json reference value_type & const_reference const value_type & difference_type std :: ptrdiff_t size_type std :: size_t allocator_type AllocatorType < basic_json > pointer std :: allocator_traits < allocator_type >:: pointer const_pointer std :: allocator_traits < allocator_type >:: const_pointer iterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iterator const_reverse_iterator reverse iterator, derived from const_iterator iteration_proxy helper type for items function JSON value data types \u00b6 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) number_integer_t - type for numbers (integer) number_unsigned_t - type for numbers (unsigned) object_comparator_t - comparator for objects object_t - type for objects string_t - type for strings Parser callback \u00b6 parse_event_t - parser event types parser_callback_t - per-element parser callback type Member functions \u00b6 (constructor) (destructor) operator= - copy assignment array ( static ) - explicitly create an array binary ( static ) - explicitly create a binary array object ( static ) - explicitly create an object Object inspection \u00b6 Functions to inspect the type of a JSON value. type - return the type of the JSON value operator value_t - return the type of the JSON value type_name - return the type as string is_primitive - return whether type is primitive is_structured - return whether type is structured is_null - return whether value is null is_boolean - return whether value is a boolean is_number - return whether value is a number is_number_integer - return whether value is an integer number is_number_unsigned - return whether value is an unsigned integer number is_number_float - return whether value is a floating-point number is_object - return whether value is an object is_array - return whether value is an array is_string - return whether value is a string is_binary - return whether value is a binary array is_discarded - return whether value is discarded Value access \u00b6 Direct access to the stored value of a JSON value. get - get a value get_to - get a value and write it to a destination get_ptr - get a pointer value get_ref - get a reference value operator ValueType - get a value get_binary - get a binary value Element access \u00b6 Access to the JSON value at - access specified element with bounds checking operator[] - access specified element value - access specified object element with default value front - access the first element back - access the last element Lookup \u00b6 find - find an element in a JSON object count - returns the number of occurrences of a key in a JSON object contains - check the existence of an element in a JSON object Iterators \u00b6 begin - returns an iterator to the first element cbegin - returns a const iterator to the first element end - returns an iterator to one past the last element cend - returns a const iterator to one past the last element rbegin - returns an iterator to the reverse-beginning rend - returns an iterator to the reverse-end crbegin - returns a const iterator to the reverse-beginning crend - returns a const iterator to the reverse-end items - wrapper to access iterator member functions in range-based for Capacity \u00b6 empty - checks whether the container is empty size - returns the number of elements max_size - returns the maximum possible number of elements Modifiers \u00b6 clear - clears the contents push_back - add a value to an array/object operator+= - add a value to an array/object emplace_back - add a value to an array emplace - add a value to an object if key does not exist erase - remove elements insert - inserts elements update - updates a JSON object from another object, overwriting existing keys swap - exchanges the values Lexicographical comparison operators \u00b6 operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator> - comparison: greater than operator<= - comparison: less than or equal operator>= - comparison: greater than or equal operator<=> - comparison: 3-way Serialization / Dumping \u00b6 dump - serialization Deserialization / Parsing \u00b6 parse ( static ) - deserialize from a compatible input accept ( static ) - check if the input is valid JSON sax_parse ( static ) - generate SAX events JSON Pointer functions \u00b6 flatten - return flattened JSON value unflatten - unflatten a previously flattened JSON value JSON Patch functions \u00b6 patch - applies a JSON patch patch_inplace - applies a JSON patch in place diff ( static ) - creates a diff as a JSON patch JSON Merge Patch functions \u00b6 merge_patch - applies a JSON Merge Patch Static functions \u00b6 meta - returns version information on the library get_allocator - returns the allocator associated with the container Binary formats \u00b6 from_bjdata ( static ) - create a JSON value from an input in BJData format from_bson ( static ) - create a JSON value from an input in BSON format from_cbor ( static ) - create a JSON value from an input in CBOR format from_msgpack ( static ) - create a JSON value from an input in MessagePack format from_ubjson ( static ) - create a JSON value from an input in UBJSON format to_bjdata ( static ) - create a BJData serialization of a given JSON value to_bson ( static ) - create a BSON serialization of a given JSON value to_cbor ( static ) - create a CBOR serialization of a given JSON value to_msgpack ( static ) - create a MessagePack serialization of a given JSON value to_ubjson ( static ) - create a UBJSON serialization of a given JSON value Non-member functions \u00b6 operator<<(std::ostream&) - serialize to stream operator>>(std::istream&) - deserialize from stream to_string - user-defined to_string function for JSON values Literals \u00b6 operator\"\"_json - user-defined string literal for JSON values Helper classes \u00b6 std::hash - return a hash value for a JSON object std::swap - exchanges the values of two JSON objects Examples \u00b6 Example The example shows how the library is used. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 } See also \u00b6 RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format Version history \u00b6 Added in version 1.0.0.","title":"Overview"},{"location":"api/basic_json/#nlohmannbasic_json","text":"Defined in header template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > , class CustomBaseClass = void > class basic_json ;","title":"nlohmann::basic_json"},{"location":"api/basic_json/#template-parameters","text":"Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t","title":"Template parameters"},{"location":"api/basic_json/#specializations","text":"json - default specialization ordered_json - specialization that maintains the insertion order of object keys","title":"Specializations"},{"location":"api/basic_json/#iterator-invalidation","text":"Todo","title":"Iterator invalidation"},{"location":"api/basic_json/#requirements","text":"The class satisfies the following concept requirements:","title":"Requirements"},{"location":"api/basic_json/#basic","text":"DefaultConstructible : JSON values can be default constructed. The result will be a JSON null value. MoveConstructible : A JSON value can be constructed from an rvalue argument. CopyConstructible : A JSON value can be copy-constructed from an lvalue expression. MoveAssignable : A JSON value can be assigned from an rvalue argument. CopyAssignable : A JSON value can be copy-assigned from an lvalue expression. Destructible : JSON values can be destructed.","title":"Basic"},{"location":"api/basic_json/#layout","text":"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.","title":"Layout"},{"location":"api/basic_json/#library-wide","text":"EqualityComparable : JSON values can be compared with == , see operator== . LessThanComparable : JSON values can be compared with < , see operator< . Swappable : Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function swap . NullablePointer : JSON values can be compared against std::nullptr_t objects which are used to model the null value.","title":"Library-wide"},{"location":"api/basic_json/#container","text":"Container : JSON values can be used like STL containers and provide iterator access. ReversibleContainer : JSON values can be used like STL containers and provide reverse iterator access.","title":"Container"},{"location":"api/basic_json/#member-types","text":"adl_serializer - the default serializer value_t - the JSON type enumeration json_pointer - JSON Pointer implementation json_serializer - type of the serializer to for conversions from/to JSON error_handler_t - type to choose behavior on decoding errors cbor_tag_handler_t - type to choose how to handle CBOR tags initializer_list_t - type for initializer lists of basic_json values input_format_t - type to choose the format to parse json_sax_t - type for SAX events","title":"Member types"},{"location":"api/basic_json/#exceptions","text":"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","title":"Exceptions"},{"location":"api/basic_json/#container-types","text":"Type Definition value_type basic_json reference value_type & const_reference const value_type & difference_type std :: ptrdiff_t size_type std :: size_t allocator_type AllocatorType < basic_json > pointer std :: allocator_traits < allocator_type >:: pointer const_pointer std :: allocator_traits < allocator_type >:: const_pointer iterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iterator const_reverse_iterator reverse iterator, derived from const_iterator iteration_proxy helper type for items function","title":"Container types"},{"location":"api/basic_json/#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) number_integer_t - type for numbers (integer) number_unsigned_t - type for numbers (unsigned) object_comparator_t - comparator for objects object_t - type for objects string_t - type for strings","title":"JSON value data types"},{"location":"api/basic_json/#parser-callback","text":"parse_event_t - parser event types parser_callback_t - per-element parser callback type","title":"Parser callback"},{"location":"api/basic_json/#member-functions","text":"(constructor) (destructor) operator= - copy assignment array ( static ) - explicitly create an array binary ( static ) - explicitly create a binary array object ( static ) - explicitly create an object","title":"Member functions"},{"location":"api/basic_json/#object-inspection","text":"Functions to inspect the type of a JSON value. type - return the type of the JSON value operator value_t - return the type of the JSON value type_name - return the type as string is_primitive - return whether type is primitive is_structured - return whether type is structured is_null - return whether value is null is_boolean - return whether value is a boolean is_number - return whether value is a number is_number_integer - return whether value is an integer number is_number_unsigned - return whether value is an unsigned integer number is_number_float - return whether value is a floating-point number is_object - return whether value is an object is_array - return whether value is an array is_string - return whether value is a string is_binary - return whether value is a binary array is_discarded - return whether value is discarded","title":"Object inspection"},{"location":"api/basic_json/#value-access","text":"Direct access to the stored value of a JSON value. get - get a value get_to - get a value and write it to a destination get_ptr - get a pointer value get_ref - get a reference value operator ValueType - get a value get_binary - get a binary value","title":"Value access"},{"location":"api/basic_json/#element-access","text":"Access to the JSON value at - access specified element with bounds checking operator[] - access specified element value - access specified object element with default value front - access the first element back - access the last element","title":"Element access"},{"location":"api/basic_json/#lookup","text":"find - find an element in a JSON object count - returns the number of occurrences of a key in a JSON object contains - check the existence of an element in a JSON object","title":"Lookup"},{"location":"api/basic_json/#iterators","text":"begin - returns an iterator to the first element cbegin - returns a const iterator to the first element end - returns an iterator to one past the last element cend - returns a const iterator to one past the last element rbegin - returns an iterator to the reverse-beginning rend - returns an iterator to the reverse-end crbegin - returns a const iterator to the reverse-beginning crend - returns a const iterator to the reverse-end items - wrapper to access iterator member functions in range-based for","title":"Iterators"},{"location":"api/basic_json/#capacity","text":"empty - checks whether the container is empty size - returns the number of elements max_size - returns the maximum possible number of elements","title":"Capacity"},{"location":"api/basic_json/#modifiers","text":"clear - clears the contents push_back - add a value to an array/object operator+= - add a value to an array/object emplace_back - add a value to an array emplace - add a value to an object if key does not exist erase - remove elements insert - inserts elements update - updates a JSON object from another object, overwriting existing keys swap - exchanges the values","title":"Modifiers"},{"location":"api/basic_json/#lexicographical-comparison-operators","text":"operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator> - comparison: greater than operator<= - comparison: less than or equal operator>= - comparison: greater than or equal operator<=> - comparison: 3-way","title":"Lexicographical comparison operators"},{"location":"api/basic_json/#serialization-dumping","text":"dump - serialization","title":"Serialization / Dumping"},{"location":"api/basic_json/#deserialization-parsing","text":"parse ( static ) - deserialize from a compatible input accept ( static ) - check if the input is valid JSON sax_parse ( static ) - generate SAX events","title":"Deserialization / Parsing"},{"location":"api/basic_json/#json-pointer-functions","text":"flatten - return flattened JSON value unflatten - unflatten a previously flattened JSON value","title":"JSON Pointer functions"},{"location":"api/basic_json/#json-patch-functions","text":"patch - applies a JSON patch patch_inplace - applies a JSON patch in place diff ( static ) - creates a diff as a JSON patch","title":"JSON Patch functions"},{"location":"api/basic_json/#json-merge-patch-functions","text":"merge_patch - applies a JSON Merge Patch","title":"JSON Merge Patch functions"},{"location":"api/basic_json/#static-functions","text":"meta - returns version information on the library get_allocator - returns the allocator associated with the container","title":"Static functions"},{"location":"api/basic_json/#binary-formats","text":"from_bjdata ( static ) - create a JSON value from an input in BJData format from_bson ( static ) - create a JSON value from an input in BSON format from_cbor ( static ) - create a JSON value from an input in CBOR format from_msgpack ( static ) - create a JSON value from an input in MessagePack format from_ubjson ( static ) - create a JSON value from an input in UBJSON format to_bjdata ( static ) - create a BJData serialization of a given JSON value to_bson ( static ) - create a BSON serialization of a given JSON value to_cbor ( static ) - create a CBOR serialization of a given JSON value to_msgpack ( static ) - create a MessagePack serialization of a given JSON value to_ubjson ( static ) - create a UBJSON serialization of a given JSON value","title":"Binary formats"},{"location":"api/basic_json/#non-member-functions","text":"operator<<(std::ostream&) - serialize to stream operator>>(std::istream&) - deserialize from stream to_string - user-defined to_string function for JSON values","title":"Non-member functions"},{"location":"api/basic_json/#literals","text":"operator\"\"_json - user-defined string literal for JSON values","title":"Literals"},{"location":"api/basic_json/#helper-classes","text":"std::hash - return a hash value for a JSON object std::swap - exchanges the values of two JSON objects","title":"Helper classes"},{"location":"api/basic_json/#examples","text":"Example The example shows how the library is used. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 }","title":"Examples"},{"location":"api/basic_json/#see-also","text":"RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format","title":"See also"},{"location":"api/basic_json/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/accept/","text":"nlohmann::basic_json:: accept \u00b6 // (1) template < typename InputType > static bool accept ( InputType && i , const bool ignore_comments = false ); // (2) template < typename IteratorType > static bool accept ( IteratorType first , IteratorType last , const bool ignore_comments = false ); Checks whether the input is valid JSON. Reads from a compatible input. Reads from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information. Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len Parameters \u00b6 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 Return value \u00b6 Whether the input is valid JSON. Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the length of the input. The parser is a predictive LL(1) parser. Notes \u00b6 (1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion . Examples \u00b6 Example The example below demonstrates the accept() function reading from a string. #include #include #include using json = nlohmann :: json ; int main () { // a valid JSON text auto valid_text = R \" ( { \"numbers\": [1, 2, 3] } ) \" ; // an invalid JSON text auto invalid_text = R \" ( { \"strings\": [\"extra\", \"comma\", ] } ) \" ; std :: cout << std :: boolalpha << json :: accept ( valid_text ) << ' ' << json :: accept ( invalid_text ) << '\\n' ; } Output: true false See also \u00b6 parse - deserialize from a compatible input operator>> - deserialize from stream Version history \u00b6 Added in version 3.0.0. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"accept"},{"location":"api/basic_json/accept/#nlohmannbasic_jsonaccept","text":"// (1) template < typename InputType > static bool accept ( InputType && i , const bool ignore_comments = false ); // (2) template < typename IteratorType > static bool accept ( IteratorType first , IteratorType last , const bool ignore_comments = false ); Checks whether the input is valid JSON. Reads from a compatible input. Reads from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.","title":"nlohmann::basic_json::accept"},{"location":"api/basic_json/accept/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len","title":"Template parameters"},{"location":"api/basic_json/accept/#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","title":"Parameters"},{"location":"api/basic_json/accept/#return-value","text":"Whether the input is valid JSON.","title":"Return value"},{"location":"api/basic_json/accept/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/accept/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser.","title":"Complexity"},{"location":"api/basic_json/accept/#notes","text":"(1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion .","title":"Notes"},{"location":"api/basic_json/accept/#examples","text":"Example The example below demonstrates the accept() function reading from a string. #include #include #include using json = nlohmann :: json ; int main () { // a valid JSON text auto valid_text = R \" ( { \"numbers\": [1, 2, 3] } ) \" ; // an invalid JSON text auto invalid_text = R \" ( { \"strings\": [\"extra\", \"comma\", ] } ) \" ; std :: cout << std :: boolalpha << json :: accept ( valid_text ) << ' ' << json :: accept ( invalid_text ) << '\\n' ; } Output: true false","title":"Examples"},{"location":"api/basic_json/accept/#see-also","text":"parse - deserialize from a compatible input operator>> - deserialize from stream","title":"See also"},{"location":"api/basic_json/accept/#version-history","text":"Added in version 3.0.0. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"Version history"},{"location":"api/basic_json/array/","text":"nlohmann::basic_json:: array \u00b6 static basic_json array ( initializer_list_t init = {}); 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. Parameters \u00b6 init (in) initializer list with JSON values to create an array from (optional) Return value \u00b6 JSON array value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of init . Notes \u00b6 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 Examples \u00b6 Example The following code shows an example for the array function. #include #include using json = nlohmann :: json ; int main () { // create JSON arrays json j_no_init_list = json :: array (); json j_empty_init_list = json :: array ({}); json j_nonempty_init_list = json :: array ({ 1 , 2 , 3 , 4 }); json j_list_of_pairs = json :: array ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON arrays std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_nonempty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; } Output: [] [] [ 1 , 2 , 3 , 4 ] [[ \"one\" , 1 ],[ \"two\" , 2 ]] See also \u00b6 basic_json(initializer_list_t) - create a JSON value from an initializer list object - create a JSON object value from an initializer list Version history \u00b6 Added in version 1.0.0.","title":"array"},{"location":"api/basic_json/array/#nlohmannbasic_jsonarray","text":"static basic_json array ( initializer_list_t init = {}); 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.","title":"nlohmann::basic_json::array"},{"location":"api/basic_json/array/#parameters","text":"init (in) initializer list with JSON values to create an array from (optional)","title":"Parameters"},{"location":"api/basic_json/array/#return-value","text":"JSON array value","title":"Return value"},{"location":"api/basic_json/array/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/array/#complexity","text":"Linear in the size of init .","title":"Complexity"},{"location":"api/basic_json/array/#notes","text":"This function is only needed to express two edge cases that cannot be realized with the initializer list constructor ( basic_json(initializer_list_t, bool, value_t) ). These cases are: 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","title":"Notes"},{"location":"api/basic_json/array/#examples","text":"Example The following code shows an example for the array function. #include #include using json = nlohmann :: json ; int main () { // create JSON arrays json j_no_init_list = json :: array (); json j_empty_init_list = json :: array ({}); json j_nonempty_init_list = json :: array ({ 1 , 2 , 3 , 4 }); json j_list_of_pairs = json :: array ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON arrays std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_nonempty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; } Output: [] [] [ 1 , 2 , 3 , 4 ] [[ \"one\" , 1 ],[ \"two\" , 2 ]]","title":"Examples"},{"location":"api/basic_json/array/#see-also","text":"basic_json(initializer_list_t) - create a JSON value from an initializer list object - create a JSON object value from an initializer list","title":"See also"},{"location":"api/basic_json/array/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/array_t/","text":"nlohmann::basic_json:: array_t \u00b6 using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; 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. Template parameters \u00b6 ArrayType container type to store arrays (e.g., std::vector or std::list ) AllocatorType the allocator to use for objects (e.g., std::allocator ) Notes \u00b6 Default type \u00b6 With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type > Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array. Storage \u00b6 Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t * must be dereferenced. Examples \u00b6 Example The following code shows that array_t is by default, a typedef to std :: vector < nlohmann :: json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: vector < json > , json :: array_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"array_t"},{"location":"api/basic_json/array_t/#nlohmannbasic_jsonarray_t","text":"using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; 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.","title":"nlohmann::basic_json::array_t"},{"location":"api/basic_json/array_t/#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 )","title":"Template parameters"},{"location":"api/basic_json/array_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/array_t/#default-type","text":"With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type >","title":"Default type"},{"location":"api/basic_json/array_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.","title":"Limits"},{"location":"api/basic_json/array_t/#storage","text":"Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t * must be dereferenced.","title":"Storage"},{"location":"api/basic_json/array_t/#examples","text":"Example The following code shows that array_t is by default, a typedef to std :: vector < nlohmann :: json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: vector < json > , json :: array_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/array_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/at/","text":"nlohmann::basic_json:: at \u00b6 // (1) reference at ( size_type idx ); const_reference at ( size_type idx ) const ; // (2) reference at ( const typename object_t :: key_type & key ); const_reference at ( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference at ( KeyType && key ); template < typename KeyType > const_reference at ( KeyType && key ) const ; // (4) reference at ( const json_pointer & ptr ); const_reference at ( const json_pointer & ptr ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 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 Return value \u00b6 reference to the element at index idx reference to the element at key key reference to the element at key key reference to the element pointed to by ptr Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below. Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size() . See example below. 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. Complexity \u00b6 Constant. Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container. Examples \u00b6 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 #include using json = nlohmann :: json ; int main () { // create JSON array json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // change element at index 1 (second element) to \"second\" array . at ( 1 ) = \"second\" ; // output changed array std :: cout << array << '\\n' ; // exception type_error.304 try { // use at() on a non-array type json str = \"I am a string\" ; str . at ( 0 ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write beyond the array limit array . at ( 5 ) = \"sixth\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ \"first\" , \"second\" , \"third\" , \"fourth\" ] [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge 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 #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // exception type_error.304 try { // use at() on a non-array type const json str = \"I am a string\" ; std :: cout << str . at ( 0 ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read beyond the array limit std :: cout << array . at ( 5 ) << '\\n' ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge Example: (2) access specified object element with bounds checking The example below shows how object elements can be read and written using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // change element with key \"the bad\" object . at ( \"the bad\" ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key object . at ( \"the fast\" ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d Example: (2) access specified object element with bounds checking The example below shows how object elements can be read using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // exception type_error.304 try { // use at() on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key std :: cout << object . at ( \"the fast\" ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // change element with key \"the bad\" using string_view object . at ( \"the bad\" sv ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" sv ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key using string_view object . at ( \"the fast\" sv ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" sv ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key using string_view std :: cout << object . at ( \"the fast\" sv ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // writing access // change the string j . at ( \"/string\" _json_pointer ) = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // change an array element j . at ( \"/array/1\" _json_pointer ) = 21 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // out_of_range.106 try { // try to use an array index with leading '0' json :: reference ref = j . at ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.109 try { // try to use an array index that is not a number json :: reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" [ 1 , 21 ] [ jso n .excep t io n .parse_error. 106 ] parse error : array i n dex ' 01 ' mus t n o t begi n wi t h ' 0 ' [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo' 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // out_of_range.109 try { // try to use an array index that is not a number json :: const_reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: const_reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: const_reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: const_reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo' See also \u00b6 documentation on checked access see operator[] for unchecked access by reference see value for access with default value Version history \u00b6 Added in version 1.0.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 2.0.0.","title":"at"},{"location":"api/basic_json/at/#nlohmannbasic_jsonat","text":"// (1) reference at ( size_type idx ); const_reference at ( size_type idx ) const ; // (2) reference at ( const typename object_t :: key_type & key ); const_reference at ( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference at ( KeyType && key ); template < typename KeyType > const_reference at ( KeyType && key ) const ; // (4) reference at ( const json_pointer & ptr ); const_reference at ( const json_pointer & ptr ) const ; 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.","title":"nlohmann::basic_json::at"},{"location":"api/basic_json/at/#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).","title":"Template parameters"},{"location":"api/basic_json/at/#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","title":"Parameters"},{"location":"api/basic_json/at/#return-value","text":"reference to the element at index idx reference to the element at key key reference to the element at key key reference to the element pointed to by ptr","title":"Return value"},{"location":"api/basic_json/at/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/at/#exceptions","text":"The function can throw the following exceptions: Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below. Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size() . See example below. 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.","title":"Exceptions"},{"location":"api/basic_json/at/#complexity","text":"Constant. Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container.","title":"Complexity"},{"location":"api/basic_json/at/#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 #include using json = nlohmann :: json ; int main () { // create JSON array json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // change element at index 1 (second element) to \"second\" array . at ( 1 ) = \"second\" ; // output changed array std :: cout << array << '\\n' ; // exception type_error.304 try { // use at() on a non-array type json str = \"I am a string\" ; str . at ( 0 ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write beyond the array limit array . at ( 5 ) = \"sixth\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ \"first\" , \"second\" , \"third\" , \"fourth\" ] [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge 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 #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // exception type_error.304 try { // use at() on a non-array type const json str = \"I am a string\" ; std :: cout << str . at ( 0 ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read beyond the array limit std :: cout << array . at ( 5 ) << '\\n' ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge Example: (2) access specified object element with bounds checking The example below shows how object elements can be read and written using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // change element with key \"the bad\" object . at ( \"the bad\" ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key object . at ( \"the fast\" ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d Example: (2) access specified object element with bounds checking The example below shows how object elements can be read using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // exception type_error.304 try { // use at() on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key std :: cout << object . at ( \"the fast\" ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // change element with key \"the bad\" using string_view object . at ( \"the bad\" sv ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" sv ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key using string_view object . at ( \"the fast\" sv ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" sv ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key using string_view std :: cout << object . at ( \"the fast\" sv ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // writing access // change the string j . at ( \"/string\" _json_pointer ) = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // change an array element j . at ( \"/array/1\" _json_pointer ) = 21 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // out_of_range.106 try { // try to use an array index with leading '0' json :: reference ref = j . at ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.109 try { // try to use an array index that is not a number json :: reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" [ 1 , 21 ] [ jso n .excep t io n .parse_error. 106 ] parse error : array i n dex ' 01 ' mus t n o t begi n wi t h ' 0 ' [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo' 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // out_of_range.109 try { // try to use an array index that is not a number json :: const_reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: const_reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: const_reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: const_reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo'","title":"Examples"},{"location":"api/basic_json/at/#see-also","text":"documentation on checked access see operator[] for unchecked access by reference see value for access with default value","title":"See also"},{"location":"api/basic_json/at/#version-history","text":"Added in version 1.0.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/back/","text":"nlohmann::basic_json:: back \u00b6 reference back (); const_reference back () const ; Returns a reference to the last element in the container. For a JSON container c , the expression c.back() is equivalent to auto tmp = c . end (); -- tmp ; return * tmp ; Return value \u00b6 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. Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 If the JSON value is null , exception invalid_iterator.214 is thrown. Complexity \u00b6 Constant. Notes \u00b6 Precondition The array or object must not be empty. Calling back on an empty array or object yields undefined behavior. Examples \u00b6 Example The following code shows an example for back() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call back() std :: cout << j_boolean . back () << '\\n' ; std :: cout << j_number_integer . back () << '\\n' ; std :: cout << j_number_float . back () << '\\n' ; std :: cout << j_object . back () << '\\n' ; //std::cout << j_object_empty.back() << '\\n'; // undefined behavior std :: cout << j_array . back () << '\\n' ; //std::cout << j_array_empty.back() << '\\n'; // undefined behavior std :: cout << j_string . back () << '\\n' ; // back() called on a null value try { json j_null ; j_null . back (); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: true 17 23.42 2 16 \"Hello, world\" [ jso n .excep t io n .i n valid_i terat or. 214 ] ca nn o t ge t value See also \u00b6 front to access the first element Version history \u00b6 Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"back"},{"location":"api/basic_json/back/#nlohmannbasic_jsonback","text":"reference back (); const_reference back () const ; Returns a reference to the last element in the container. For a JSON container c , the expression c.back() is equivalent to auto tmp = c . end (); -- tmp ; return * tmp ;","title":"nlohmann::basic_json::back"},{"location":"api/basic_json/back/#return-value","text":"In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.","title":"Return value"},{"location":"api/basic_json/back/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/back/#exceptions","text":"If the JSON value is null , exception invalid_iterator.214 is thrown.","title":"Exceptions"},{"location":"api/basic_json/back/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/back/#notes","text":"Precondition The array or object must not be empty. Calling back on an empty array or object yields undefined behavior.","title":"Notes"},{"location":"api/basic_json/back/#examples","text":"Example The following code shows an example for back() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call back() std :: cout << j_boolean . back () << '\\n' ; std :: cout << j_number_integer . back () << '\\n' ; std :: cout << j_number_float . back () << '\\n' ; std :: cout << j_object . back () << '\\n' ; //std::cout << j_object_empty.back() << '\\n'; // undefined behavior std :: cout << j_array . back () << '\\n' ; //std::cout << j_array_empty.back() << '\\n'; // undefined behavior std :: cout << j_string . back () << '\\n' ; // back() called on a null value try { json j_null ; j_null . back (); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: true 17 23.42 2 16 \"Hello, world\" [ jso n .excep t io n .i n valid_i terat or. 214 ] ca nn o t ge t value","title":"Examples"},{"location":"api/basic_json/back/#see-also","text":"front to access the first element","title":"See also"},{"location":"api/basic_json/back/#version-history","text":"Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/basic_json/","text":"nlohmann::basic_json:: basic_json \u00b6 // (1) basic_json ( const value_t v ); // (2) basic_json ( std :: nullptr_t = nullptr ) noexcept ; // (3) template < typename CompatibleType > basic_json ( CompatibleType && val ) noexcept ( noexcept ( JSONSerializer < U >:: to_json ( std :: declval < basic_json_t &> (), std :: forward < CompatibleType > ( val )))); // (4) template < typename BasicJsonType > basic_json ( const BasicJsonType & val ); // (5) basic_json ( initializer_list_t init , bool type_deduction = true , value_t manual_type = value_t :: array ); // (6) basic_json ( size_type cnt , const basic_json & val ); // (7) basic_json ( iterator first , iterator last ); basic_json ( const_iterator first , const_iterator last ); // (8) basic_json ( const basic_json & other ); // (9) basic_json ( basic_json && other ) noexcept ; 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::to_json method with U = uncvref_t , 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 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. Template parameters \u00b6 CompatibleType a type such that: CompatibleType is not derived from std::istream , CompatibleType is not basic_json (to avoid hijacking copy/move constructors), CompatibleType is not a different basic_json type (i.e. with different template arguments) CompatibleType is not a basic_json nested type (e.g., json_pointer , iterator , etc.) json_serializer (with U = uncvref_t ) 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 Parameters \u00b6 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 Exception safety \u00b6 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. Exceptions \u00b6 (none) The function does not throw exceptions. (none) (none) The function can throw the following exceptions: Throws type_error.301 if type_deduction is false , manual_type is value_t::object , but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true , an array would have been created. See object(initializer_list_t) for an example. (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. (none) The function does not throw exceptions. Complexity \u00b6 Constant. Constant. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Linear in the size of the initializer list init . Linear in cnt . Linear in distance between first and last . Linear in the size of other . Constant. Notes \u00b6 Overload 5: Empty initializer list When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value. Overload 7: Preconditions 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 Examples \u00b6 Example: (1) create an empty value with a given type The following code shows the constructor for different value_t values. #include #include using json = nlohmann :: json ; int main () { // create the different JSON values with default values json j_null ( json :: value_t :: null ); json j_boolean ( json :: value_t :: boolean ); json j_number_integer ( json :: value_t :: number_integer ); json j_number_float ( json :: value_t :: number_float ); json j_object ( json :: value_t :: object ); json j_array ( json :: value_t :: array ); json j_string ( json :: value_t :: string ); // serialize the JSON values std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\" Example: (2) create a null object The following code shows the constructor with and without a null pointer parameter. #include #include using json = nlohmann :: json ; int main () { // implicitly create a JSON null value json j1 ; // explicitly create a JSON null value json j2 ( nullptr ); // serialize the JSON null value std :: cout << j1 << '\\n' << j2 << '\\n' ; } Output: null null Example: (3) create a JSON value from compatible types The following code shows the constructor with several compatible types. #include #include #include #include #include #include #include #include #include using json = nlohmann :: json ; int main () { // ============ // object types // ============ // create an object from an object_t value json :: object_t object_value = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_object_t ( object_value ); // create an object from std::map std :: map < std :: string , int > c_map { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 3 } }; json j_map ( c_map ); // create an object from std::unordered_map std :: unordered_map < const char * , double > c_umap { { \"one\" , 1.2 }, { \"two\" , 2.3 }, { \"three\" , 3.4 } }; json j_umap ( c_umap ); // create an object from std::multimap std :: multimap < std :: string , bool > c_mmap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_mmap ( c_mmap ); // only one entry for key \"three\" is used // create an object from std::unordered_multimap std :: unordered_multimap < std :: string , bool > c_ummap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_ummap ( c_ummap ); // only one entry for key \"three\" is used // serialize the JSON objects std :: cout << j_object_t << '\\n' ; std :: cout << j_map << '\\n' ; std :: cout << j_umap << '\\n' ; std :: cout << j_mmap << '\\n' ; std :: cout << j_ummap << \" \\n\\n \" ; // =========== // array types // =========== // create an array from an array_t value json :: array_t array_value = { \"one\" , \"two\" , 3 , 4.5 , false }; json j_array_t ( array_value ); // create an array from std::vector std :: vector < int > c_vector { 1 , 2 , 3 , 4 }; json j_vec ( c_vector ); // create an array from std::valarray std :: valarray < short > c_valarray { 10 , 9 , 8 , 7 }; json j_valarray ( c_valarray ); // create an array from std::deque std :: deque < double > c_deque { 1.2 , 2.3 , 3.4 , 5.6 }; json j_deque ( c_deque ); // create an array from std::list std :: list < bool > c_list { true , true , false , true }; json j_list ( c_list ); // create an array from std::forward_list std :: forward_list < std :: int64_t > c_flist { 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 }; json j_flist ( c_flist ); // create an array from std::array std :: array < unsigned long , 4 > c_array {{ 1 , 2 , 3 , 4 }}; json j_array ( c_array ); // create an array from std::set std :: set < std :: string > c_set { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_set ( c_set ); // only one entry for \"one\" is used // create an array from std::unordered_set std :: unordered_set < std :: string > c_uset { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_uset ( c_uset ); // only one entry for \"one\" is used // create an array from std::multiset std :: multiset < std :: string > c_mset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_mset ( c_mset ); // both entries for \"one\" are used // create an array from std::unordered_multiset std :: unordered_multiset < std :: string > c_umset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_umset ( c_umset ); // both entries for \"one\" are used // serialize the JSON arrays std :: cout << j_array_t << '\\n' ; std :: cout << j_vec << '\\n' ; std :: cout << j_valarray << '\\n' ; std :: cout << j_deque << '\\n' ; std :: cout << j_list << '\\n' ; std :: cout << j_flist << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_set << '\\n' ; std :: cout << j_uset << '\\n' ; std :: cout << j_mset << '\\n' ; std :: cout << j_umset << \" \\n\\n \" ; // ============ // string types // ============ // create string from a string_t value json :: string_t string_value = \"The quick brown fox jumps over the lazy dog.\" ; json j_string_t ( string_value ); // create a JSON string directly from a string literal json j_string_literal ( \"The quick brown fox jumps over the lazy dog.\" ); // create string from std::string std :: string s_stdstring = \"The quick brown fox jumps over the lazy dog.\" ; json j_stdstring ( s_stdstring ); // serialize the JSON strings std :: cout << j_string_t << '\\n' ; std :: cout << j_string_literal << '\\n' ; std :: cout << j_stdstring << \" \\n\\n \" ; // ============ // number types // ============ // create a JSON number from number_integer_t json :: number_integer_t value_integer_t = -42 ; json j_integer_t ( value_integer_t ); // create a JSON number from number_unsigned_t json :: number_integer_t value_unsigned_t = 17 ; json j_unsigned_t ( value_unsigned_t ); // create a JSON number from an anonymous enum enum { enum_value = 17 }; json j_enum ( enum_value ); // create values of different integer types short n_short = 42 ; int n_int = -23 ; long n_long = 1024 ; int_least32_t n_int_least32_t = -17 ; uint8_t n_uint8_t = 8 ; // create (integer) JSON numbers json j_short ( n_short ); json j_int ( n_int ); json j_long ( n_long ); json j_int_least32_t ( n_int_least32_t ); json j_uint8_t ( n_uint8_t ); // create values of different floating-point types json :: number_float_t v_ok = 3.141592653589793 ; json :: number_float_t v_nan = NAN ; json :: number_float_t v_infinity = INFINITY ; // create values of different floating-point types float n_float = 42.23 ; float n_float_nan = 1.0f / 0.0f ; double n_double = 23.42 ; // create (floating point) JSON numbers json j_ok ( v_ok ); json j_nan ( v_nan ); json j_infinity ( v_infinity ); json j_float ( n_float ); json j_float_nan ( n_float_nan ); json j_double ( n_double ); // serialize the JSON numbers std :: cout << j_integer_t << '\\n' ; std :: cout << j_unsigned_t << '\\n' ; std :: cout << j_enum << '\\n' ; std :: cout << j_short << '\\n' ; std :: cout << j_int << '\\n' ; std :: cout << j_long << '\\n' ; std :: cout << j_int_least32_t << '\\n' ; std :: cout << j_uint8_t << '\\n' ; std :: cout << j_ok << '\\n' ; std :: cout << j_nan << '\\n' ; std :: cout << j_infinity << '\\n' ; std :: cout << j_float << '\\n' ; std :: cout << j_float_nan << '\\n' ; std :: cout << j_double << \" \\n\\n \" ; // ============= // boolean types // ============= // create boolean values json j_truth = true ; json j_falsity = false ; // serialize the JSON booleans std :: cout << j_truth << '\\n' ; std :: cout << j_falsity << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"one\" : 1.2 , \"three\" : 3.4 , \"two\" : 2.3 } { \"one\" : true , \"three\" : false , \"two\" : true } { \"one\" : true , \"three\" : false , \"two\" : true } [ \"one\" , \"two\" , 3 , 4.5 , false ] [ 1 , 2 , 3 , 4 ] [ 10 , 9 , 8 , 7 ] [ 1.2 , 2.3 , 3.4 , 5.6 ] [ true , true , false , true ] [ 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 ] [ 1 , 2 , 3 , 4 ] [ \"four\" , \"one\" , \"three\" , \"two\" ] [ \"four\" , \"three\" , \"two\" , \"one\" ] [ \"four\" , \"one\" , \"one\" , \"two\" ] [ \"four\" , \"two\" , \"one\" , \"one\" ] \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" -42 17 17 42 -23 1024 -17 8 3.141592653589793 null null 42.22999954223633 null 23.42 true false Note the output is platform-dependent. Example: (5) create a container (array or object) from an initializer list The example below shows how JSON values are created from initializer lists. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_empty_init_list = json ({}); json j_object = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_array = { 1 , 2 , 3 , 4 }; json j_nested_object = { { \"one\" , { 1 }}, { \"two\" , { 1 , 2 }} }; json j_nested_array = { {{ 1 }, \"one\" }, {{ 1 , 2 }, \"two\" } }; // serialize the JSON value std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_nested_object << '\\n' ; std :: cout << j_nested_array << '\\n' ; } Output: {} { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 3 , 4 ] { \"one\" :[ 1 ], \"two\" :[ 1 , 2 ]} [[[ 1 ], \"one\" ],[[ 1 , 2 ], \"two\" ]] Example: (6) construct an array with count copies of given value The following code shows examples for creating arrays with several copies of a given value. #include #include using json = nlohmann :: json ; int main () { // create an array by creating copies of a JSON value json value = \"Hello\" ; json array_0 = json ( 0 , value ); json array_1 = json ( 1 , value ); json array_5 = json ( 5 , value ); // serialize the JSON arrays std :: cout << array_0 << '\\n' ; std :: cout << array_1 << '\\n' ; std :: cout << array_5 << '\\n' ; } Output: [] [ \"Hello\" ] [ \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" ] Example: (7) construct a JSON container given an iterator range The example below shows several ways to create JSON values by specifying a subrange with iterators. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_array = { \"alpha\" , \"bravo\" , \"charly\" , \"delta\" , \"easy\" }; json j_number = 42 ; json j_object = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; // create copies using iterators json j_array_range ( j_array . begin () + 1 , j_array . end () - 2 ); json j_number_range ( j_number . begin (), j_number . end ()); json j_object_range ( j_object . begin (), j_object . find ( \"two\" )); // serialize the values std :: cout << j_array_range << '\\n' ; std :: cout << j_number_range << '\\n' ; std :: cout << j_object_range << '\\n' ; // example for an exception try { json j_invalid ( j_number . begin () + 1 , j_number . end ()); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ \"bravo\" , \"charly\" ] 42 { \"one\" : \"eins\" } [ jso n .excep t io n .i n valid_i terat or. 204 ] i terat ors ou t o f ra n ge Example: (8) copy constructor The following code shows an example for the copy constructor. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j1 = { \"one\" , \"two\" , 3 , 4.5 , false }; // create a copy json j2 ( j1 ); // serialize the JSON array std :: cout << j1 << \" = \" << j2 << '\\n' ; std :: cout << std :: boolalpha << ( j1 == j2 ) << '\\n' ; } Output: [ \"one\" , \"two\" , 3 , 4.5 , false ] = [ \"one\" , \"two\" , 3 , 4.5 , false ] true Example: (9) move constructor The code below shows the move constructor explicitly called via std::move . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json a = 23 ; // move contents of a to b json b ( std :: move ( a )); // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: null 23 Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 2.1.0. Since version 3.2.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0.","title":"(Constructor)"},{"location":"api/basic_json/basic_json/#nlohmannbasic_jsonbasic_json","text":"// (1) basic_json ( const value_t v ); // (2) basic_json ( std :: nullptr_t = nullptr ) noexcept ; // (3) template < typename CompatibleType > basic_json ( CompatibleType && val ) noexcept ( noexcept ( JSONSerializer < U >:: to_json ( std :: declval < basic_json_t &> (), std :: forward < CompatibleType > ( val )))); // (4) template < typename BasicJsonType > basic_json ( const BasicJsonType & val ); // (5) basic_json ( initializer_list_t init , bool type_deduction = true , value_t manual_type = value_t :: array ); // (6) basic_json ( size_type cnt , const basic_json & val ); // (7) basic_json ( iterator first , iterator last ); basic_json ( const_iterator first , const_iterator last ); // (8) basic_json ( const basic_json & other ); // (9) basic_json ( basic_json && other ) noexcept ; 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::to_json method with U = uncvref_t , 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 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.","title":"nlohmann::basic_json::basic_json"},{"location":"api/basic_json/basic_json/#template-parameters","text":"CompatibleType a type such that: CompatibleType is not derived from std::istream , CompatibleType is not basic_json (to avoid hijacking copy/move constructors), CompatibleType is not a different basic_json type (i.e. with different template arguments) CompatibleType is not a basic_json nested type (e.g., json_pointer , iterator , etc.) json_serializer (with U = uncvref_t ) 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","title":"Template parameters"},{"location":"api/basic_json/basic_json/#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","title":"Parameters"},{"location":"api/basic_json/basic_json/#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.","title":"Exception safety"},{"location":"api/basic_json/basic_json/#exceptions","text":"(none) The function does not throw exceptions. (none) (none) The function can throw the following exceptions: Throws type_error.301 if type_deduction is false , manual_type is value_t::object , but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true , an array would have been created. See object(initializer_list_t) for an example. (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. (none) The function does not throw exceptions.","title":"Exceptions"},{"location":"api/basic_json/basic_json/#complexity","text":"Constant. Constant. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Linear in the size of the initializer list init . Linear in cnt . Linear in distance between first and last . Linear in the size of other . Constant.","title":"Complexity"},{"location":"api/basic_json/basic_json/#notes","text":"Overload 5: Empty initializer list When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value. Overload 7: Preconditions 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","title":"Notes"},{"location":"api/basic_json/basic_json/#examples","text":"Example: (1) create an empty value with a given type The following code shows the constructor for different value_t values. #include #include using json = nlohmann :: json ; int main () { // create the different JSON values with default values json j_null ( json :: value_t :: null ); json j_boolean ( json :: value_t :: boolean ); json j_number_integer ( json :: value_t :: number_integer ); json j_number_float ( json :: value_t :: number_float ); json j_object ( json :: value_t :: object ); json j_array ( json :: value_t :: array ); json j_string ( json :: value_t :: string ); // serialize the JSON values std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\" Example: (2) create a null object The following code shows the constructor with and without a null pointer parameter. #include #include using json = nlohmann :: json ; int main () { // implicitly create a JSON null value json j1 ; // explicitly create a JSON null value json j2 ( nullptr ); // serialize the JSON null value std :: cout << j1 << '\\n' << j2 << '\\n' ; } Output: null null Example: (3) create a JSON value from compatible types The following code shows the constructor with several compatible types. #include #include #include #include #include #include #include #include #include using json = nlohmann :: json ; int main () { // ============ // object types // ============ // create an object from an object_t value json :: object_t object_value = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_object_t ( object_value ); // create an object from std::map std :: map < std :: string , int > c_map { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 3 } }; json j_map ( c_map ); // create an object from std::unordered_map std :: unordered_map < const char * , double > c_umap { { \"one\" , 1.2 }, { \"two\" , 2.3 }, { \"three\" , 3.4 } }; json j_umap ( c_umap ); // create an object from std::multimap std :: multimap < std :: string , bool > c_mmap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_mmap ( c_mmap ); // only one entry for key \"three\" is used // create an object from std::unordered_multimap std :: unordered_multimap < std :: string , bool > c_ummap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_ummap ( c_ummap ); // only one entry for key \"three\" is used // serialize the JSON objects std :: cout << j_object_t << '\\n' ; std :: cout << j_map << '\\n' ; std :: cout << j_umap << '\\n' ; std :: cout << j_mmap << '\\n' ; std :: cout << j_ummap << \" \\n\\n \" ; // =========== // array types // =========== // create an array from an array_t value json :: array_t array_value = { \"one\" , \"two\" , 3 , 4.5 , false }; json j_array_t ( array_value ); // create an array from std::vector std :: vector < int > c_vector { 1 , 2 , 3 , 4 }; json j_vec ( c_vector ); // create an array from std::valarray std :: valarray < short > c_valarray { 10 , 9 , 8 , 7 }; json j_valarray ( c_valarray ); // create an array from std::deque std :: deque < double > c_deque { 1.2 , 2.3 , 3.4 , 5.6 }; json j_deque ( c_deque ); // create an array from std::list std :: list < bool > c_list { true , true , false , true }; json j_list ( c_list ); // create an array from std::forward_list std :: forward_list < std :: int64_t > c_flist { 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 }; json j_flist ( c_flist ); // create an array from std::array std :: array < unsigned long , 4 > c_array {{ 1 , 2 , 3 , 4 }}; json j_array ( c_array ); // create an array from std::set std :: set < std :: string > c_set { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_set ( c_set ); // only one entry for \"one\" is used // create an array from std::unordered_set std :: unordered_set < std :: string > c_uset { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_uset ( c_uset ); // only one entry for \"one\" is used // create an array from std::multiset std :: multiset < std :: string > c_mset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_mset ( c_mset ); // both entries for \"one\" are used // create an array from std::unordered_multiset std :: unordered_multiset < std :: string > c_umset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_umset ( c_umset ); // both entries for \"one\" are used // serialize the JSON arrays std :: cout << j_array_t << '\\n' ; std :: cout << j_vec << '\\n' ; std :: cout << j_valarray << '\\n' ; std :: cout << j_deque << '\\n' ; std :: cout << j_list << '\\n' ; std :: cout << j_flist << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_set << '\\n' ; std :: cout << j_uset << '\\n' ; std :: cout << j_mset << '\\n' ; std :: cout << j_umset << \" \\n\\n \" ; // ============ // string types // ============ // create string from a string_t value json :: string_t string_value = \"The quick brown fox jumps over the lazy dog.\" ; json j_string_t ( string_value ); // create a JSON string directly from a string literal json j_string_literal ( \"The quick brown fox jumps over the lazy dog.\" ); // create string from std::string std :: string s_stdstring = \"The quick brown fox jumps over the lazy dog.\" ; json j_stdstring ( s_stdstring ); // serialize the JSON strings std :: cout << j_string_t << '\\n' ; std :: cout << j_string_literal << '\\n' ; std :: cout << j_stdstring << \" \\n\\n \" ; // ============ // number types // ============ // create a JSON number from number_integer_t json :: number_integer_t value_integer_t = -42 ; json j_integer_t ( value_integer_t ); // create a JSON number from number_unsigned_t json :: number_integer_t value_unsigned_t = 17 ; json j_unsigned_t ( value_unsigned_t ); // create a JSON number from an anonymous enum enum { enum_value = 17 }; json j_enum ( enum_value ); // create values of different integer types short n_short = 42 ; int n_int = -23 ; long n_long = 1024 ; int_least32_t n_int_least32_t = -17 ; uint8_t n_uint8_t = 8 ; // create (integer) JSON numbers json j_short ( n_short ); json j_int ( n_int ); json j_long ( n_long ); json j_int_least32_t ( n_int_least32_t ); json j_uint8_t ( n_uint8_t ); // create values of different floating-point types json :: number_float_t v_ok = 3.141592653589793 ; json :: number_float_t v_nan = NAN ; json :: number_float_t v_infinity = INFINITY ; // create values of different floating-point types float n_float = 42.23 ; float n_float_nan = 1.0f / 0.0f ; double n_double = 23.42 ; // create (floating point) JSON numbers json j_ok ( v_ok ); json j_nan ( v_nan ); json j_infinity ( v_infinity ); json j_float ( n_float ); json j_float_nan ( n_float_nan ); json j_double ( n_double ); // serialize the JSON numbers std :: cout << j_integer_t << '\\n' ; std :: cout << j_unsigned_t << '\\n' ; std :: cout << j_enum << '\\n' ; std :: cout << j_short << '\\n' ; std :: cout << j_int << '\\n' ; std :: cout << j_long << '\\n' ; std :: cout << j_int_least32_t << '\\n' ; std :: cout << j_uint8_t << '\\n' ; std :: cout << j_ok << '\\n' ; std :: cout << j_nan << '\\n' ; std :: cout << j_infinity << '\\n' ; std :: cout << j_float << '\\n' ; std :: cout << j_float_nan << '\\n' ; std :: cout << j_double << \" \\n\\n \" ; // ============= // boolean types // ============= // create boolean values json j_truth = true ; json j_falsity = false ; // serialize the JSON booleans std :: cout << j_truth << '\\n' ; std :: cout << j_falsity << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"one\" : 1.2 , \"three\" : 3.4 , \"two\" : 2.3 } { \"one\" : true , \"three\" : false , \"two\" : true } { \"one\" : true , \"three\" : false , \"two\" : true } [ \"one\" , \"two\" , 3 , 4.5 , false ] [ 1 , 2 , 3 , 4 ] [ 10 , 9 , 8 , 7 ] [ 1.2 , 2.3 , 3.4 , 5.6 ] [ true , true , false , true ] [ 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 ] [ 1 , 2 , 3 , 4 ] [ \"four\" , \"one\" , \"three\" , \"two\" ] [ \"four\" , \"three\" , \"two\" , \"one\" ] [ \"four\" , \"one\" , \"one\" , \"two\" ] [ \"four\" , \"two\" , \"one\" , \"one\" ] \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" -42 17 17 42 -23 1024 -17 8 3.141592653589793 null null 42.22999954223633 null 23.42 true false Note the output is platform-dependent. Example: (5) create a container (array or object) from an initializer list The example below shows how JSON values are created from initializer lists. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_empty_init_list = json ({}); json j_object = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_array = { 1 , 2 , 3 , 4 }; json j_nested_object = { { \"one\" , { 1 }}, { \"two\" , { 1 , 2 }} }; json j_nested_array = { {{ 1 }, \"one\" }, {{ 1 , 2 }, \"two\" } }; // serialize the JSON value std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_nested_object << '\\n' ; std :: cout << j_nested_array << '\\n' ; } Output: {} { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 3 , 4 ] { \"one\" :[ 1 ], \"two\" :[ 1 , 2 ]} [[[ 1 ], \"one\" ],[[ 1 , 2 ], \"two\" ]] Example: (6) construct an array with count copies of given value The following code shows examples for creating arrays with several copies of a given value. #include #include using json = nlohmann :: json ; int main () { // create an array by creating copies of a JSON value json value = \"Hello\" ; json array_0 = json ( 0 , value ); json array_1 = json ( 1 , value ); json array_5 = json ( 5 , value ); // serialize the JSON arrays std :: cout << array_0 << '\\n' ; std :: cout << array_1 << '\\n' ; std :: cout << array_5 << '\\n' ; } Output: [] [ \"Hello\" ] [ \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" ] Example: (7) construct a JSON container given an iterator range The example below shows several ways to create JSON values by specifying a subrange with iterators. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_array = { \"alpha\" , \"bravo\" , \"charly\" , \"delta\" , \"easy\" }; json j_number = 42 ; json j_object = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; // create copies using iterators json j_array_range ( j_array . begin () + 1 , j_array . end () - 2 ); json j_number_range ( j_number . begin (), j_number . end ()); json j_object_range ( j_object . begin (), j_object . find ( \"two\" )); // serialize the values std :: cout << j_array_range << '\\n' ; std :: cout << j_number_range << '\\n' ; std :: cout << j_object_range << '\\n' ; // example for an exception try { json j_invalid ( j_number . begin () + 1 , j_number . end ()); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ \"bravo\" , \"charly\" ] 42 { \"one\" : \"eins\" } [ jso n .excep t io n .i n valid_i terat or. 204 ] i terat ors ou t o f ra n ge Example: (8) copy constructor The following code shows an example for the copy constructor. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j1 = { \"one\" , \"two\" , 3 , 4.5 , false }; // create a copy json j2 ( j1 ); // serialize the JSON array std :: cout << j1 << \" = \" << j2 << '\\n' ; std :: cout << std :: boolalpha << ( j1 == j2 ) << '\\n' ; } Output: [ \"one\" , \"two\" , 3 , 4.5 , false ] = [ \"one\" , \"two\" , 3 , 4.5 , false ] true Example: (9) move constructor The code below shows the move constructor explicitly called via std::move . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json a = 23 ; // move contents of a to b json b ( std :: move ( a )); // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: null 23","title":"Examples"},{"location":"api/basic_json/basic_json/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 2.1.0. Since version 3.2.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0.","title":"Version history"},{"location":"api/basic_json/begin/","text":"nlohmann::basic_json:: begin \u00b6 iterator begin () noexcept ; const_iterator begin () const noexcept ; Returns an iterator to the first element. Return value \u00b6 iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for begin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: iterator it = array . begin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"begin"},{"location":"api/basic_json/begin/#nlohmannbasic_jsonbegin","text":"iterator begin () noexcept ; const_iterator begin () const noexcept ; Returns an iterator to the first element.","title":"nlohmann::basic_json::begin"},{"location":"api/basic_json/begin/#return-value","text":"iterator to the first element","title":"Return value"},{"location":"api/basic_json/begin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/begin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/begin/#examples","text":"Example The following code shows an example for begin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: iterator it = array . begin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/begin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/binary/","text":"nlohmann::basic_json:: binary \u00b6 // (1) static basic_json binary ( const typename binary_t :: container_type & init ); static basic_json binary ( typename binary_t :: container_type && init ); // (2) static basic_json binary ( const typename binary_t :: container_type & init , std :: uint8_t subtype ); static basic_json binary ( typename binary_t :: container_type && init , std :: uint8_t subtype ); 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. Parameters \u00b6 init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON Return value \u00b6 JSON binary array value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of init ; constant for typename binary_t::container_type&& init versions. Notes \u00b6 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. Examples \u00b6 Example The following code shows how to create a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42 Version history \u00b6 Added in version 3.8.0.","title":"binary"},{"location":"api/basic_json/binary/#nlohmannbasic_jsonbinary","text":"// (1) static basic_json binary ( const typename binary_t :: container_type & init ); static basic_json binary ( typename binary_t :: container_type && init ); // (2) static basic_json binary ( const typename binary_t :: container_type & init , std :: uint8_t subtype ); static basic_json binary ( typename binary_t :: container_type && init , std :: uint8_t subtype ); 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.","title":"nlohmann::basic_json::binary"},{"location":"api/basic_json/binary/#parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON","title":"Parameters"},{"location":"api/basic_json/binary/#return-value","text":"JSON binary array value","title":"Return value"},{"location":"api/basic_json/binary/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/binary/#complexity","text":"Linear in the size of init ; constant for typename binary_t::container_type&& init versions.","title":"Complexity"},{"location":"api/basic_json/binary/#notes","text":"Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a std::vector . Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.","title":"Notes"},{"location":"api/basic_json/binary/#examples","text":"Example The following code shows how to create a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42","title":"Examples"},{"location":"api/basic_json/binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/binary_t/","text":"nlohmann::basic_json:: binary_t \u00b6 using binary_t = byte_container_with_subtype < BinaryType > ; 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++. Template parameters \u00b6 BinaryType container type to store arrays Notes \u00b6 Default type \u00b6 The default values for BinaryType is std :: vector < std :: uint8_t > . Storage \u00b6 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. Notes on subtypes \u00b6 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. Examples \u00b6 Example The following code shows that binary_t is by default, a typedef to nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> , json :: binary_t >:: value << std :: endl ; } Output: true See also \u00b6 byte_container_with_subtype Version history \u00b6 Added in version 3.8.0. Changed type of subtype to std::uint64_t in version 3.10.0.","title":"binary_t"},{"location":"api/basic_json/binary_t/#nlohmannbasic_jsonbinary_t","text":"using binary_t = byte_container_with_subtype < BinaryType > ; 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++.","title":"nlohmann::basic_json::binary_t"},{"location":"api/basic_json/binary_t/#template-parameters","text":"BinaryType container type to store arrays","title":"Template parameters"},{"location":"api/basic_json/binary_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/binary_t/#default-type","text":"The default values for BinaryType is std :: vector < std :: uint8_t > .","title":"Default type"},{"location":"api/basic_json/binary_t/#storage","text":"Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t * must be dereferenced.","title":"Storage"},{"location":"api/basic_json/binary_t/#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.","title":"Notes on subtypes"},{"location":"api/basic_json/binary_t/#examples","text":"Example The following code shows that binary_t is by default, a typedef to nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> , json :: binary_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/binary_t/#see-also","text":"byte_container_with_subtype","title":"See also"},{"location":"api/basic_json/binary_t/#version-history","text":"Added in version 3.8.0. Changed type of subtype to std::uint64_t in version 3.10.0.","title":"Version history"},{"location":"api/basic_json/boolean_t/","text":"nlohmann::basic_json:: boolean_t \u00b6 using boolean_t = BooleanType ; The type used to store JSON booleans. RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false . To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use. Notes \u00b6 Default type \u00b6 With the default values for BooleanType ( bool ), the default value for boolean_t is bool . Storage \u00b6 Boolean values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that boolean_t is by default, a typedef to bool . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < bool , json :: boolean_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"boolean_t"},{"location":"api/basic_json/boolean_t/#nlohmannbasic_jsonboolean_t","text":"using boolean_t = BooleanType ; The type used to store JSON booleans. RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false . To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.","title":"nlohmann::basic_json::boolean_t"},{"location":"api/basic_json/boolean_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/boolean_t/#default-type","text":"With the default values for BooleanType ( bool ), the default value for boolean_t is bool .","title":"Default type"},{"location":"api/basic_json/boolean_t/#storage","text":"Boolean values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/boolean_t/#examples","text":"Example The following code shows that boolean_t is by default, a typedef to bool . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < bool , json :: boolean_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/boolean_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/cbegin/","text":"nlohmann::basic_json:: cbegin \u00b6 const_iterator cbegin () const noexcept ; Returns an iterator to the first element. Return value \u00b6 iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for cbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value const json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: const_iterator it = array . cbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"cbegin"},{"location":"api/basic_json/cbegin/#nlohmannbasic_jsoncbegin","text":"const_iterator cbegin () const noexcept ; Returns an iterator to the first element.","title":"nlohmann::basic_json::cbegin"},{"location":"api/basic_json/cbegin/#return-value","text":"iterator to the first element","title":"Return value"},{"location":"api/basic_json/cbegin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/cbegin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/cbegin/#examples","text":"Example The following code shows an example for cbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value const json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: const_iterator it = array . cbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/cbegin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/cbor_tag_handler_t/","text":"nlohmann::basic_json:: cbor_tag_handler_t \u00b6 enum class cbor_tag_handler_t { error , ignore , store }; 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) Examples \u00b6 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 #include using json = nlohmann :: json ; int main () { // tagged byte string std :: vector < std :: uint8_t > vec = {{ 0xd8 , 0x42 , 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // cbor_tag_handler_t::error throws try { auto b_throw_on_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: error ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // cbor_tag_handler_t::ignore ignores the tag auto b_ignore_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: ignore ); std :: cout << b_ignore_tag << std :: endl ; // cbor_tag_handler_t::store stores the tag as binary subtype auto b_store_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: store ); std :: cout << b_store_tag << std :: endl ; } Output: [ jso n .excep t io n .parse_error. 112 ] parse error a t by te 1 : sy nta x error while parsi n g CBOR value : i n valid by te : 0 xD 8 { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 66 } Version history \u00b6 Added in version 3.9.0. Added value store in 3.10.0.","title":"cbor_tag_handler_t"},{"location":"api/basic_json/cbor_tag_handler_t/#nlohmannbasic_jsoncbor_tag_handler_t","text":"enum class cbor_tag_handler_t { error , ignore , store }; 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)","title":"nlohmann::basic_json::cbor_tag_handler_t"},{"location":"api/basic_json/cbor_tag_handler_t/#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 #include using json = nlohmann :: json ; int main () { // tagged byte string std :: vector < std :: uint8_t > vec = {{ 0xd8 , 0x42 , 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // cbor_tag_handler_t::error throws try { auto b_throw_on_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: error ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // cbor_tag_handler_t::ignore ignores the tag auto b_ignore_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: ignore ); std :: cout << b_ignore_tag << std :: endl ; // cbor_tag_handler_t::store stores the tag as binary subtype auto b_store_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: store ); std :: cout << b_store_tag << std :: endl ; } Output: [ jso n .excep t io n .parse_error. 112 ] parse error a t by te 1 : sy nta x error while parsi n g CBOR value : i n valid by te : 0 xD 8 { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 66 }","title":"Examples"},{"location":"api/basic_json/cbor_tag_handler_t/#version-history","text":"Added in version 3.9.0. Added value store in 3.10.0.","title":"Version history"},{"location":"api/basic_json/cend/","text":"nlohmann::basic_json:: cend \u00b6 const_iterator cend () const noexcept ; Returns an iterator to one past the last element. Return value \u00b6 iterator one past the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for cend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: const_iterator it = array . cend (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"cend"},{"location":"api/basic_json/cend/#nlohmannbasic_jsoncend","text":"const_iterator cend () const noexcept ; Returns an iterator to one past the last element.","title":"nlohmann::basic_json::cend"},{"location":"api/basic_json/cend/#return-value","text":"iterator one past the last element","title":"Return value"},{"location":"api/basic_json/cend/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/cend/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/cend/#examples","text":"Example The following code shows an example for cend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: const_iterator it = array . cend (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/cend/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/clear/","text":"nlohmann::basic_json:: clear \u00b6 void clear () noexcept ; Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type() : Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array [] Has the same effect as calling * this = basic_json ( type ()); Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear in the size of the JSON value. Notes \u00b6 All iterators, pointers and references related to this container are invalidated. Examples \u00b6 Example The example below shows the effect of clear() to different JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call clear() j_null . clear (); j_boolean . clear (); j_number_integer . clear (); j_number_float . clear (); j_object . clear (); j_array . clear (); j_string . clear (); // serialize the cleared values() std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\" Version history \u00b6 Added in version 1.0.0. Added support for binary types in version 3.8.0.","title":"clear"},{"location":"api/basic_json/clear/#nlohmannbasic_jsonclear","text":"void clear () noexcept ; Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type() : Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array [] Has the same effect as calling * this = basic_json ( type ());","title":"nlohmann::basic_json::clear"},{"location":"api/basic_json/clear/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/clear/#complexity","text":"Linear in the size of the JSON value.","title":"Complexity"},{"location":"api/basic_json/clear/#notes","text":"All iterators, pointers and references related to this container are invalidated.","title":"Notes"},{"location":"api/basic_json/clear/#examples","text":"Example The example below shows the effect of clear() to different JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call clear() j_null . clear (); j_boolean . clear (); j_number_integer . clear (); j_number_float . clear (); j_object . clear (); j_array . clear (); j_string . clear (); // serialize the cleared values() std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\"","title":"Examples"},{"location":"api/basic_json/clear/#version-history","text":"Added in version 1.0.0. Added support for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/contains/","text":"nlohmann::basic_json:: contains \u00b6 // (1) bool contains ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > bool contains ( KeyType && key ) const ; // (3) bool contains ( const json_pointer & ptr ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 key (in) key value to check its existence. ptr (in) JSON pointer to check its existence. Return value \u00b6 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. Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function does not throw exceptions. The function does not throw exceptions. The function can throw the following exceptions: Throws parse_error.106 if an array index begins with 0 . Throws parse_error.109 if an array index was not a number. Complexity \u00b6 Logarithmic in the size of the JSON object. Notes \u00b6 This method always returns false when executed on a JSON type that is not an object. This method can be executed on any JSON value type. Postconditions If j . contains ( x ) returns true for a key or JSON pointer x , then it is safe to call j[x] . Examples \u00b6 Example: (1) check with key The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (2) check with key using string_view The example shows how contains() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" sv ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" sv ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" sv ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (3) check with JSON pointer The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; std :: cout << std :: boolalpha << j . contains ( \"/number\" _json_pointer ) << '\\n' << j . contains ( \"/string\" _json_pointer ) << '\\n' << j . contains ( \"/array\" _json_pointer ) << '\\n' << j . contains ( \"/array/1\" _json_pointer ) << '\\n' << j . contains ( \"/array/-\" _json_pointer ) << '\\n' << j . contains ( \"/array/4\" _json_pointer ) << '\\n' << j . contains ( \"/baz\" _json_pointer ) << std :: endl ; try { // try to use an array index with leading '0' j . contains ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } try { // try to use an array index that is not a number j . contains ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: true true true true false false false Version history \u00b6 Added in version 3.11.0. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0. Added in version 3.7.0.","title":"contains"},{"location":"api/basic_json/contains/#nlohmannbasic_jsoncontains","text":"// (1) bool contains ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > bool contains ( KeyType && key ) const ; // (3) bool contains ( const json_pointer & ptr ) const ; 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.","title":"nlohmann::basic_json::contains"},{"location":"api/basic_json/contains/#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).","title":"Template parameters"},{"location":"api/basic_json/contains/#parameters","text":"key (in) key value to check its existence. ptr (in) JSON pointer to check its existence.","title":"Parameters"},{"location":"api/basic_json/contains/#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.","title":"Return value"},{"location":"api/basic_json/contains/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/contains/#exceptions","text":"The function does not throw exceptions. The function does not throw exceptions. The function can throw the following exceptions: Throws parse_error.106 if an array index begins with 0 . Throws parse_error.109 if an array index was not a number.","title":"Exceptions"},{"location":"api/basic_json/contains/#complexity","text":"Logarithmic in the size of the JSON object.","title":"Complexity"},{"location":"api/basic_json/contains/#notes","text":"This method always returns false when executed on a JSON type that is not an object. This method can be executed on any JSON value type. Postconditions If j . contains ( x ) returns true for a key or JSON pointer x , then it is safe to call j[x] .","title":"Notes"},{"location":"api/basic_json/contains/#examples","text":"Example: (1) check with key The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (2) check with key using string_view The example shows how contains() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" sv ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" sv ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" sv ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (3) check with JSON pointer The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; std :: cout << std :: boolalpha << j . contains ( \"/number\" _json_pointer ) << '\\n' << j . contains ( \"/string\" _json_pointer ) << '\\n' << j . contains ( \"/array\" _json_pointer ) << '\\n' << j . contains ( \"/array/1\" _json_pointer ) << '\\n' << j . contains ( \"/array/-\" _json_pointer ) << '\\n' << j . contains ( \"/array/4\" _json_pointer ) << '\\n' << j . contains ( \"/baz\" _json_pointer ) << std :: endl ; try { // try to use an array index with leading '0' j . contains ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } try { // try to use an array index that is not a number j . contains ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: true true true true false false false","title":"Examples"},{"location":"api/basic_json/contains/#version-history","text":"Added in version 3.11.0. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0. Added in version 3.7.0.","title":"Version history"},{"location":"api/basic_json/count/","text":"nlohmann::basic_json:: count \u00b6 // (1) size_type count ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > size_type count ( KeyType && key ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 key (in) key value of the element to count. Return value \u00b6 Number of elements with key key . If the JSON value is not an object, the return value will be 0 . Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Complexity \u00b6 Logarithmic in the size of the JSON object. Notes \u00b6 This method always returns 0 when executed on a JSON type that is not an object. Examples \u00b6 Example: (1) count number of elements The example shows how count() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" ); auto count_three = j_object . count ( \"three\" ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0 Example: (2) count number of elements using string_view The example shows how count() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" sv ); auto count_three = j_object . count ( \"three\" sv ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0 Version history \u00b6 Added in version 3.11.0. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0.","title":"count"},{"location":"api/basic_json/count/#nlohmannbasic_jsoncount","text":"// (1) size_type count ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > size_type count ( KeyType && key ) const ; 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.","title":"nlohmann::basic_json::count"},{"location":"api/basic_json/count/#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).","title":"Template parameters"},{"location":"api/basic_json/count/#parameters","text":"key (in) key value of the element to count.","title":"Parameters"},{"location":"api/basic_json/count/#return-value","text":"Number of elements with key key . If the JSON value is not an object, the return value will be 0 .","title":"Return value"},{"location":"api/basic_json/count/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/count/#complexity","text":"Logarithmic in the size of the JSON object.","title":"Complexity"},{"location":"api/basic_json/count/#notes","text":"This method always returns 0 when executed on a JSON type that is not an object.","title":"Notes"},{"location":"api/basic_json/count/#examples","text":"Example: (1) count number of elements The example shows how count() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" ); auto count_three = j_object . count ( \"three\" ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0 Example: (2) count number of elements using string_view The example shows how count() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" sv ); auto count_three = j_object . count ( \"three\" sv ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0","title":"Examples"},{"location":"api/basic_json/count/#version-history","text":"Added in version 3.11.0. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/crbegin/","text":"nlohmann::basic_json:: crbegin \u00b6 const_reverse_iterator crbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element. Return value \u00b6 reverse iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for crbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: const_reverse_iterator it = array . crbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"crbegin"},{"location":"api/basic_json/crbegin/#nlohmannbasic_jsoncrbegin","text":"const_reverse_iterator crbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element.","title":"nlohmann::basic_json::crbegin"},{"location":"api/basic_json/crbegin/#return-value","text":"reverse iterator to the first element","title":"Return value"},{"location":"api/basic_json/crbegin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/crbegin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/crbegin/#examples","text":"Example The following code shows an example for crbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: const_reverse_iterator it = array . crbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/crbegin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/crend/","text":"nlohmann::basic_json:: crend \u00b6 const_reverse_iterator crend () const noexcept ; 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. Return value \u00b6 reverse iterator to the element following the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: const_reverse_iterator it = array . crend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"crend"},{"location":"api/basic_json/crend/#nlohmannbasic_jsoncrend","text":"const_reverse_iterator crend () const noexcept ; 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.","title":"nlohmann::basic_json::crend"},{"location":"api/basic_json/crend/#return-value","text":"reverse iterator to the element following the last element","title":"Return value"},{"location":"api/basic_json/crend/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/crend/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/crend/#examples","text":"Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: const_reverse_iterator it = array . crend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/crend/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/default_object_comparator_t/","text":"nlohmann::basic_json:: default_object_comparator_t \u00b6 using default_object_comparator_t = std :: less < StringType > ; // until C++14 using default_object_comparator_t = std :: less <> ; // since C++14 The default comparator used by object_t . Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object. The actual comparator used depends on object_t and can be obtained via object_comparator_t . Examples \u00b6 Example The example below demonstrates the default comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"one < two : \" << json :: default_object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"three < four : \" << json :: default_object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: o ne < t wo : true t hree < f our : false Version history \u00b6 Added in version 3.11.0.","title":"default_object_comparator_t"},{"location":"api/basic_json/default_object_comparator_t/#nlohmannbasic_jsondefault_object_comparator_t","text":"using default_object_comparator_t = std :: less < StringType > ; // until C++14 using default_object_comparator_t = std :: less <> ; // since C++14 The default comparator used by object_t . Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object. The actual comparator used depends on object_t and can be obtained via object_comparator_t .","title":"nlohmann::basic_json::default_object_comparator_t"},{"location":"api/basic_json/default_object_comparator_t/#examples","text":"Example The example below demonstrates the default comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"one < two : \" << json :: default_object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"three < four : \" << json :: default_object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: o ne < t wo : true t hree < f our : false","title":"Examples"},{"location":"api/basic_json/default_object_comparator_t/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/diff/","text":"nlohmann::basic_json:: diff \u00b6 static basic_json diff ( const basic_json & source , const basic_json & target ); 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 ; Parameters \u00b6 source (in) JSON value to compare from target (in) JSON value to compare against Return value \u00b6 a JSON patch to convert the source to target Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the lengths of source and target . Notes \u00b6 Currently, only remove , add , and replace operations are generated. Examples \u00b6 Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } See also \u00b6 RFC 6902 (JSON Patch) Version history \u00b6 Added in version 2.0.0.","title":"diff"},{"location":"api/basic_json/diff/#nlohmannbasic_jsondiff","text":"static basic_json diff ( const basic_json & source , const basic_json & target ); 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 ;","title":"nlohmann::basic_json::diff"},{"location":"api/basic_json/diff/#parameters","text":"source (in) JSON value to compare from target (in) JSON value to compare against","title":"Parameters"},{"location":"api/basic_json/diff/#return-value","text":"a JSON patch to convert the source to target","title":"Return value"},{"location":"api/basic_json/diff/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/diff/#complexity","text":"Linear in the lengths of source and target .","title":"Complexity"},{"location":"api/basic_json/diff/#notes","text":"Currently, only remove , add , and replace operations are generated.","title":"Notes"},{"location":"api/basic_json/diff/#examples","text":"Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Examples"},{"location":"api/basic_json/diff/#see-also","text":"RFC 6902 (JSON Patch)","title":"See also"},{"location":"api/basic_json/diff/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/dump/","text":"nlohmann::basic_json:: dump \u00b6 string_t dump ( const int indent = -1 , const char indent_char = ' ' , const bool ensure_ascii = false , const error_handler_t error_handler = error_handler_t :: strict ) const ; Serialization function for JSON values. The function tries to mimic Python's json.dumps() function , and currently supports its indent and ensure_ascii parameters. Parameters \u00b6 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)). Return value \u00b6 string containing the serialization of the JSON value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Exceptions \u00b6 Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict Complexity \u00b6 Linear. Notes \u00b6 Binary values are serialized as object containing two keys: \"bytes\": an array of bytes as integers \"subtype\": the subtype as integer or null if the binary has no subtype Examples \u00b6 Example The following example shows the effect of different indent , indent_char , and ensure_ascii parameters to the result of the serialization. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hell\u00f6 \ud83d\ude00!\" ; // call dump() std :: cout << \"objects:\" << '\\n' << j_object . dump () << \" \\n\\n \" << j_object . dump ( -1 ) << \" \\n\\n \" << j_object . dump ( 0 ) << \" \\n\\n \" << j_object . dump ( 4 ) << \" \\n\\n \" << j_object . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"arrays:\" << '\\n' << j_array . dump () << \" \\n\\n \" << j_array . dump ( -1 ) << \" \\n\\n \" << j_array . dump ( 0 ) << \" \\n\\n \" << j_array . dump ( 4 ) << \" \\n\\n \" << j_array . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"strings:\" << '\\n' << j_string . dump () << '\\n' << j_string . dump ( -1 , ' ' , true ) << '\\n' ; // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: objec ts : { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } arrays : [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] s tr i n gs : \"Hell\u00f6 \ud83d\ude00!\" \"Hell\\u00f6 \\ud83d\\ude00!\" [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\" Version history \u00b6 Added in version 1.0.0. Indentation character indent_char , option ensure_ascii and exceptions added in version 3.0.0. Error handlers added in version 3.4.0. Serialization of binary values added in version 3.8.0.","title":"dump"},{"location":"api/basic_json/dump/#nlohmannbasic_jsondump","text":"string_t dump ( const int indent = -1 , const char indent_char = ' ' , const bool ensure_ascii = false , const error_handler_t error_handler = error_handler_t :: strict ) const ; Serialization function for JSON values. The function tries to mimic Python's json.dumps() function , and currently supports its indent and ensure_ascii parameters.","title":"nlohmann::basic_json::dump"},{"location":"api/basic_json/dump/#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)).","title":"Parameters"},{"location":"api/basic_json/dump/#return-value","text":"string containing the serialization of the JSON value","title":"Return value"},{"location":"api/basic_json/dump/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/dump/#exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict","title":"Exceptions"},{"location":"api/basic_json/dump/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/dump/#notes","text":"Binary values are serialized as object containing two keys: \"bytes\": an array of bytes as integers \"subtype\": the subtype as integer or null if the binary has no subtype","title":"Notes"},{"location":"api/basic_json/dump/#examples","text":"Example The following example shows the effect of different indent , indent_char , and ensure_ascii parameters to the result of the serialization. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hell\u00f6 \ud83d\ude00!\" ; // call dump() std :: cout << \"objects:\" << '\\n' << j_object . dump () << \" \\n\\n \" << j_object . dump ( -1 ) << \" \\n\\n \" << j_object . dump ( 0 ) << \" \\n\\n \" << j_object . dump ( 4 ) << \" \\n\\n \" << j_object . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"arrays:\" << '\\n' << j_array . dump () << \" \\n\\n \" << j_array . dump ( -1 ) << \" \\n\\n \" << j_array . dump ( 0 ) << \" \\n\\n \" << j_array . dump ( 4 ) << \" \\n\\n \" << j_array . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"strings:\" << '\\n' << j_string . dump () << '\\n' << j_string . dump ( -1 , ' ' , true ) << '\\n' ; // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: objec ts : { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } arrays : [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] s tr i n gs : \"Hell\u00f6 \ud83d\ude00!\" \"Hell\\u00f6 \\ud83d\\ude00!\" [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\"","title":"Examples"},{"location":"api/basic_json/dump/#version-history","text":"Added in version 1.0.0. Indentation character indent_char , option ensure_ascii and exceptions added in version 3.0.0. Error handlers added in version 3.4.0. Serialization of binary values added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/emplace/","text":"nlohmann::basic_json:: emplace \u00b6 template < class ... Args > std :: pair < iterator , bool > emplace ( Args && ... args ); 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 . Template parameters \u00b6 Args compatible types to create a basic_json object Parameters \u00b6 args (in) arguments to forward to a constructor of basic_json Return value \u00b6 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. Exceptions \u00b6 Throws type_error.311 when called on a type other than JSON object or null ; example: \"cannot use emplace() with number\" Complexity \u00b6 Logarithmic in the size of the container, O(log( size() )). Examples \u00b6 Example The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values auto res1 = object . emplace ( \"three\" , 3 ); null . emplace ( \"A\" , \"a\" ); null . emplace ( \"B\" , \"b\" ); // the following call will not add an object, because there is already // a value stored at key \"B\" auto res2 = null . emplace ( \"B\" , \"c\" ); // print values std :: cout << object << '\\n' ; std :: cout << * res1 . first << \" \" << std :: boolalpha << res1 . second << '\\n' ; std :: cout << null << '\\n' ; std :: cout << * res2 . first << \" \" << std :: boolalpha << res2 . second << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } 3 true { \"A\" : \"a\" , \"B\" : \"b\" } \"b\" false Version history \u00b6 Since version 2.0.8.","title":"emplace"},{"location":"api/basic_json/emplace/#nlohmannbasic_jsonemplace","text":"template < class ... Args > std :: pair < iterator , bool > emplace ( Args && ... args ); 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 .","title":"nlohmann::basic_json::emplace"},{"location":"api/basic_json/emplace/#template-parameters","text":"Args compatible types to create a basic_json object","title":"Template parameters"},{"location":"api/basic_json/emplace/#parameters","text":"args (in) arguments to forward to a constructor of basic_json","title":"Parameters"},{"location":"api/basic_json/emplace/#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.","title":"Return value"},{"location":"api/basic_json/emplace/#exceptions","text":"Throws type_error.311 when called on a type other than JSON object or null ; example: \"cannot use emplace() with number\"","title":"Exceptions"},{"location":"api/basic_json/emplace/#complexity","text":"Logarithmic in the size of the container, O(log( size() )).","title":"Complexity"},{"location":"api/basic_json/emplace/#examples","text":"Example The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values auto res1 = object . emplace ( \"three\" , 3 ); null . emplace ( \"A\" , \"a\" ); null . emplace ( \"B\" , \"b\" ); // the following call will not add an object, because there is already // a value stored at key \"B\" auto res2 = null . emplace ( \"B\" , \"c\" ); // print values std :: cout << object << '\\n' ; std :: cout << * res1 . first << \" \" << std :: boolalpha << res1 . second << '\\n' ; std :: cout << null << '\\n' ; std :: cout << * res2 . first << \" \" << std :: boolalpha << res2 . second << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } 3 true { \"A\" : \"a\" , \"B\" : \"b\" } \"b\" false","title":"Examples"},{"location":"api/basic_json/emplace/#version-history","text":"Since version 2.0.8.","title":"Version history"},{"location":"api/basic_json/emplace_back/","text":"nlohmann::basic_json:: emplace_back \u00b6 template < class ... Args > reference emplace_back ( Args && ... args ); 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 . Template parameters \u00b6 Args compatible types to create a basic_json object Parameters \u00b6 args (in) arguments to forward to a constructor of basic_json Return value \u00b6 reference to the inserted element Exceptions \u00b6 Throws type_error.311 when called on a type other than JSON array or null ; example: \"cannot use emplace_back() with number\" Complexity \u00b6 Amortized constant. Examples \u00b6 Example The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . emplace_back ( 6 ); null . emplace_back ( \"first\" ); null . emplace_back ( 3 , \"second\" ); // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 ] [ \"first\" ,[ \"second\" , \"second\" , \"second\" ]] Version history \u00b6 Since version 2.0.8. Returns reference since 3.7.0.","title":"emplace_back"},{"location":"api/basic_json/emplace_back/#nlohmannbasic_jsonemplace_back","text":"template < class ... Args > reference emplace_back ( Args && ... args ); 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 .","title":"nlohmann::basic_json::emplace_back"},{"location":"api/basic_json/emplace_back/#template-parameters","text":"Args compatible types to create a basic_json object","title":"Template parameters"},{"location":"api/basic_json/emplace_back/#parameters","text":"args (in) arguments to forward to a constructor of basic_json","title":"Parameters"},{"location":"api/basic_json/emplace_back/#return-value","text":"reference to the inserted element","title":"Return value"},{"location":"api/basic_json/emplace_back/#exceptions","text":"Throws type_error.311 when called on a type other than JSON array or null ; example: \"cannot use emplace_back() with number\"","title":"Exceptions"},{"location":"api/basic_json/emplace_back/#complexity","text":"Amortized constant.","title":"Complexity"},{"location":"api/basic_json/emplace_back/#examples","text":"Example The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . emplace_back ( 6 ); null . emplace_back ( \"first\" ); null . emplace_back ( 3 , \"second\" ); // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 ] [ \"first\" ,[ \"second\" , \"second\" , \"second\" ]]","title":"Examples"},{"location":"api/basic_json/emplace_back/#version-history","text":"Since version 2.0.8. Returns reference since 3.7.0.","title":"Version history"},{"location":"api/basic_json/empty/","text":"nlohmann::basic_json:: empty \u00b6 bool empty () const noexcept ; Checks if a JSON value has no elements (i.e. whether its size() is 0 ). Return value \u00b6 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() Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity. Possible implementation \u00b6 bool empty () const noexcept { return size () == 0 ; } Notes \u00b6 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. Examples \u00b6 Example The following code uses empty() to check if a JSON object contains any elements. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call empty() std :: cout << std :: boolalpha ; std :: cout << j_null . empty () << '\\n' ; std :: cout << j_boolean . empty () << '\\n' ; std :: cout << j_number_integer . empty () << '\\n' ; std :: cout << j_number_float . empty () << '\\n' ; std :: cout << j_object . empty () << '\\n' ; std :: cout << j_object_empty . empty () << '\\n' ; std :: cout << j_array . empty () << '\\n' ; std :: cout << j_array_empty . empty () << '\\n' ; std :: cout << j_string . empty () << '\\n' ; } Output: true false false false false true false true false Version history \u00b6 Added in version 1.0.0. Extended to return false for binary types in version 3.8.0.","title":"empty"},{"location":"api/basic_json/empty/#nlohmannbasic_jsonempty","text":"bool empty () const noexcept ; Checks if a JSON value has no elements (i.e. whether its size() is 0 ).","title":"nlohmann::basic_json::empty"},{"location":"api/basic_json/empty/#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()","title":"Return value"},{"location":"api/basic_json/empty/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/empty/#complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity.","title":"Complexity"},{"location":"api/basic_json/empty/#possible-implementation","text":"bool empty () const noexcept { return size () == 0 ; }","title":"Possible implementation"},{"location":"api/basic_json/empty/#notes","text":"This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is false in the case of a string.","title":"Notes"},{"location":"api/basic_json/empty/#examples","text":"Example The following code uses empty() to check if a JSON object contains any elements. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call empty() std :: cout << std :: boolalpha ; std :: cout << j_null . empty () << '\\n' ; std :: cout << j_boolean . empty () << '\\n' ; std :: cout << j_number_integer . empty () << '\\n' ; std :: cout << j_number_float . empty () << '\\n' ; std :: cout << j_object . empty () << '\\n' ; std :: cout << j_object_empty . empty () << '\\n' ; std :: cout << j_array . empty () << '\\n' ; std :: cout << j_array_empty . empty () << '\\n' ; std :: cout << j_string . empty () << '\\n' ; } Output: true false false false false true false true false","title":"Examples"},{"location":"api/basic_json/empty/#version-history","text":"Added in version 1.0.0. Extended to return false for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/end/","text":"nlohmann::basic_json:: end \u00b6 iterator end () noexcept ; const_iterator end () const noexcept ; Returns an iterator to one past the last element. Return value \u00b6 iterator one past the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for end() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: iterator it = array . end (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"end"},{"location":"api/basic_json/end/#nlohmannbasic_jsonend","text":"iterator end () noexcept ; const_iterator end () const noexcept ; Returns an iterator to one past the last element.","title":"nlohmann::basic_json::end"},{"location":"api/basic_json/end/#return-value","text":"iterator one past the last element","title":"Return value"},{"location":"api/basic_json/end/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/end/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/end/#examples","text":"Example The following code shows an example for end() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: iterator it = array . end (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/end/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/erase/","text":"nlohmann::basic_json:: erase \u00b6 // (1) iterator erase ( iterator pos ); const_iterator erase ( const_iterator pos ); // (2) iterator erase ( iterator first , iterator last ); const_iterator erase ( const_iterator first , const_iterator last ); // (3) size_type erase ( const typename object_t :: key_type & key ); // (4) template < typename KeyType > size_type erase ( KeyType && key ); // (5) void erase ( const size_type idx ); 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. Template parameters \u00b6 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). Parameters \u00b6 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 Return value \u00b6 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). See 3. (none) Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\" Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\" Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin() ); example: \"iterator out of range\" 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\" Complexity \u00b6 The complexity depends on the type: objects: amortized constant arrays: linear in distance between pos and the end of the container strings and binary: linear in the length of the member other types: constant The complexity depends on the type: objects: log(size()) + std::distance(first, last) arrays: linear in the distance between first and last , plus linear in the distance between last and end of the container strings and binary: linear in the length of the member other types: constant log(size()) + count(key) log(size()) + count(key) Linear in distance between idx and the end of the container. Notes \u00b6 Invalidates iterators and references at or after the point of the erase , including the end() iterator. (none) References and iterators to the erased elements are invalidated. Other references and iterators are not affected. See 3. (none) Examples \u00b6 Example: (1) remove element given an iterator The example shows the effect of erase() for different JSON types using an iterator. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin ()); j_number_integer . erase ( j_number_integer . begin ()); j_number_float . erase ( j_number_float . begin ()); j_object . erase ( j_object . find ( \"two\" )); j_array . erase ( j_array . begin () + 2 ); j_string . erase ( j_string . begin ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 2 , 8 , 16 ] null Example: (2) remove elements given an iterator range The example shows the effect of erase() for different JSON types using an iterator range. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin (), j_boolean . end ()); j_number_integer . erase ( j_number_integer . begin (), j_number_integer . end ()); j_number_float . erase ( j_number_float . begin (), j_number_float . end ()); j_object . erase ( j_object . find ( \"two\" ), j_object . end ()); j_array . erase ( j_array . begin () + 1 , j_array . begin () + 3 ); j_string . erase ( j_string . begin (), j_string . end ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 8 , 16 ] null Example: (3) remove element from a JSON object given a key The example shows the effect of erase() for different JSON types using an object key. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" ); auto count_three = j_object . erase ( \"three\" ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (4) remove element from a JSON object given a key using string_view The example shows the effect of erase() for different JSON types using an object key. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" sv ); auto count_three = j_object . erase ( \"three\" sv ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (5) remove element from a JSON array given an index The example shows the effect of erase() using an array index. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j_array = { 0 , 1 , 2 , 3 , 4 , 5 }; // call erase() j_array . erase ( 2 ); // print values std :: cout << j_array << '\\n' ; } Output: [ 0 , 1 , 3 , 4 , 5 ] Version history \u00b6 Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 1.0.0.","title":"erase"},{"location":"api/basic_json/erase/#nlohmannbasic_jsonerase","text":"// (1) iterator erase ( iterator pos ); const_iterator erase ( const_iterator pos ); // (2) iterator erase ( iterator first , iterator last ); const_iterator erase ( const_iterator first , const_iterator last ); // (3) size_type erase ( const typename object_t :: key_type & key ); // (4) template < typename KeyType > size_type erase ( KeyType && key ); // (5) void erase ( const size_type idx ); 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.","title":"nlohmann::basic_json::erase"},{"location":"api/basic_json/erase/#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).","title":"Template parameters"},{"location":"api/basic_json/erase/#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","title":"Parameters"},{"location":"api/basic_json/erase/#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). See 3. (none)","title":"Return value"},{"location":"api/basic_json/erase/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/erase/#exceptions","text":"The function can throw the following exceptions: Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\" Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\" Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin() ); example: \"iterator out of range\" 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\"","title":"Exceptions"},{"location":"api/basic_json/erase/#complexity","text":"The complexity depends on the type: objects: amortized constant arrays: linear in distance between pos and the end of the container strings and binary: linear in the length of the member other types: constant The complexity depends on the type: objects: log(size()) + std::distance(first, last) arrays: linear in the distance between first and last , plus linear in the distance between last and end of the container strings and binary: linear in the length of the member other types: constant log(size()) + count(key) log(size()) + count(key) Linear in distance between idx and the end of the container.","title":"Complexity"},{"location":"api/basic_json/erase/#notes","text":"Invalidates iterators and references at or after the point of the erase , including the end() iterator. (none) References and iterators to the erased elements are invalidated. Other references and iterators are not affected. See 3. (none)","title":"Notes"},{"location":"api/basic_json/erase/#examples","text":"Example: (1) remove element given an iterator The example shows the effect of erase() for different JSON types using an iterator. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin ()); j_number_integer . erase ( j_number_integer . begin ()); j_number_float . erase ( j_number_float . begin ()); j_object . erase ( j_object . find ( \"two\" )); j_array . erase ( j_array . begin () + 2 ); j_string . erase ( j_string . begin ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 2 , 8 , 16 ] null Example: (2) remove elements given an iterator range The example shows the effect of erase() for different JSON types using an iterator range. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin (), j_boolean . end ()); j_number_integer . erase ( j_number_integer . begin (), j_number_integer . end ()); j_number_float . erase ( j_number_float . begin (), j_number_float . end ()); j_object . erase ( j_object . find ( \"two\" ), j_object . end ()); j_array . erase ( j_array . begin () + 1 , j_array . begin () + 3 ); j_string . erase ( j_string . begin (), j_string . end ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 8 , 16 ] null Example: (3) remove element from a JSON object given a key The example shows the effect of erase() for different JSON types using an object key. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" ); auto count_three = j_object . erase ( \"three\" ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (4) remove element from a JSON object given a key using string_view The example shows the effect of erase() for different JSON types using an object key. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" sv ); auto count_three = j_object . erase ( \"three\" sv ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (5) remove element from a JSON array given an index The example shows the effect of erase() using an array index. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j_array = { 0 , 1 , 2 , 3 , 4 , 5 }; // call erase() j_array . erase ( 2 ); // print values std :: cout << j_array << '\\n' ; } Output: [ 0 , 1 , 3 , 4 , 5 ]","title":"Examples"},{"location":"api/basic_json/erase/#version-history","text":"Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/error_handler_t/","text":"nlohmann::basic_json:: error_handler_t \u00b6 enum class error_handler_t { strict , replace , ignore }; 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 Examples \u00b6 Example The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence. #include #include using json = nlohmann :: json ; int main () { // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\" Version history \u00b6 Added in version 3.4.0.","title":"error_handler_t"},{"location":"api/basic_json/error_handler_t/#nlohmannbasic_jsonerror_handler_t","text":"enum class error_handler_t { strict , replace , ignore }; 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","title":"nlohmann::basic_json::error_handler_t"},{"location":"api/basic_json/error_handler_t/#examples","text":"Example The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence. #include #include using json = nlohmann :: json ; int main () { // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\"","title":"Examples"},{"location":"api/basic_json/error_handler_t/#version-history","text":"Added in version 3.4.0.","title":"Version history"},{"location":"api/basic_json/exception/","text":"nlohmann::basic_json:: exception \u00b6 class exception : public std :: exception ; This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions, see example below. Subclasses: 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 Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Notes \u00b6 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. Examples \u00b6 Example The following code shows how arbitrary library exceptions can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for a non-existing key json j = {{ \"foo\" , \"bar\" }}; json k = j . at ( \"non-existing\" ); } catch ( const json :: exception & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' n o n -e xis t i n g' n o t f ou n d excep t io n id : 403 See also \u00b6 List of exceptions Version history \u00b6 Since version 3.0.0.","title":"exception"},{"location":"api/basic_json/exception/#nlohmannbasic_jsonexception","text":"class exception : public std :: exception ; This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions, see example below. Subclasses: 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","title":"nlohmann::basic_json::exception"},{"location":"api/basic_json/exception/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/exception/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/exception/#notes","text":"To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.","title":"Notes"},{"location":"api/basic_json/exception/#examples","text":"Example The following code shows how arbitrary library exceptions can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for a non-existing key json j = {{ \"foo\" , \"bar\" }}; json k = j . at ( \"non-existing\" ); } catch ( const json :: exception & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' n o n -e xis t i n g' n o t f ou n d excep t io n id : 403","title":"Examples"},{"location":"api/basic_json/exception/#see-also","text":"List of exceptions","title":"See also"},{"location":"api/basic_json/exception/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/find/","text":"nlohmann::basic_json:: find \u00b6 // (1) iterator find ( const typename object_t :: key_type & key ); const_iterator find ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > iterator find ( KeyType && key ); template < typename KeyType > const_iterator find ( KeyType && key ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 key (in) key value of the element to search for. Return value \u00b6 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. Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Complexity \u00b6 Logarithmic in the size of the JSON object. Notes \u00b6 This method always returns end() when executed on a JSON type that is not an object. Examples \u00b6 Example: (1) find object element by key The example shows how find() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" ); auto it_three = j_object . find ( \"three\" ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false Example: (2) find object element by key using string_view The example shows how find() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" sv ); auto it_three = j_object . find ( \"three\" sv ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false See also \u00b6 contains checks whether a key exists Version history \u00b6 Added in version 3.11.0. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.","title":"find"},{"location":"api/basic_json/find/#nlohmannbasic_jsonfind","text":"// (1) iterator find ( const typename object_t :: key_type & key ); const_iterator find ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > iterator find ( KeyType && key ); template < typename KeyType > const_iterator find ( KeyType && key ) const ; 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.","title":"nlohmann::basic_json::find"},{"location":"api/basic_json/find/#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).","title":"Template parameters"},{"location":"api/basic_json/find/#parameters","text":"key (in) key value of the element to search for.","title":"Parameters"},{"location":"api/basic_json/find/#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.","title":"Return value"},{"location":"api/basic_json/find/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/find/#complexity","text":"Logarithmic in the size of the JSON object.","title":"Complexity"},{"location":"api/basic_json/find/#notes","text":"This method always returns end() when executed on a JSON type that is not an object.","title":"Notes"},{"location":"api/basic_json/find/#examples","text":"Example: (1) find object element by key The example shows how find() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" ); auto it_three = j_object . find ( \"three\" ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false Example: (2) find object element by key using string_view The example shows how find() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" sv ); auto it_three = j_object . find ( \"three\" sv ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false","title":"Examples"},{"location":"api/basic_json/find/#see-also","text":"contains checks whether a key exists","title":"See also"},{"location":"api/basic_json/find/#version-history","text":"Added in version 3.11.0. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/flatten/","text":"nlohmann::basic_json:: flatten \u00b6 basic_json flatten () const ; 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. Return value \u00b6 an object that maps JSON pointers to primitive values Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Complexity \u00b6 Linear in the size the JSON value. Notes \u00b6 Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function. Examples \u00b6 Example The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // call flatten() std :: cout << std :: setw ( 4 ) << j . flatten () << '\\n' ; } Output: { \"/answer/everything\" : 42 , \"/happy\" : true , \"/list/0\" : 1 , \"/list/1\" : 0 , \"/list/2\" : 2 , \"/name\" : \"Niels\" , \"/nothing\" : null , \"/object/currency\" : \"USD\" , \"/object/value\" : 42.99 , \"/pi\" : 3.141 } See also \u00b6 unflatten the reverse function Version history \u00b6 Added in version 2.0.0.","title":"flatten"},{"location":"api/basic_json/flatten/#nlohmannbasic_jsonflatten","text":"basic_json flatten () const ; 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.","title":"nlohmann::basic_json::flatten"},{"location":"api/basic_json/flatten/#return-value","text":"an object that maps JSON pointers to primitive values","title":"Return value"},{"location":"api/basic_json/flatten/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/flatten/#complexity","text":"Linear in the size the JSON value.","title":"Complexity"},{"location":"api/basic_json/flatten/#notes","text":"Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.","title":"Notes"},{"location":"api/basic_json/flatten/#examples","text":"Example The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // call flatten() std :: cout << std :: setw ( 4 ) << j . flatten () << '\\n' ; } Output: { \"/answer/everything\" : 42 , \"/happy\" : true , \"/list/0\" : 1 , \"/list/1\" : 0 , \"/list/2\" : 2 , \"/name\" : \"Niels\" , \"/nothing\" : null , \"/object/currency\" : \"USD\" , \"/object/value\" : 42.99 , \"/pi\" : 3.141 }","title":"Examples"},{"location":"api/basic_json/flatten/#see-also","text":"unflatten the reverse function","title":"See also"},{"location":"api/basic_json/flatten/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/from_bjdata/","text":"nlohmann::basic_json:: from_bjdata \u00b6 // (1) template < typename InputType > static basic_json from_bjdata ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bjdata ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in BJData format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 3.11.0.","title":"from_bjdata"},{"location":"api/basic_json/from_bjdata/#nlohmannbasic_jsonfrom_bjdata","text":"// (1) template < typename InputType > static basic_json from_bjdata ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bjdata ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_bjdata"},{"location":"api/basic_json/from_bjdata/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_bjdata/#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)","title":"Parameters"},{"location":"api/basic_json/from_bjdata/#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 .","title":"Return value"},{"location":"api/basic_json/from_bjdata/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_bjdata/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully","title":"Exceptions"},{"location":"api/basic_json/from_bjdata/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_bjdata/#examples","text":"Example The example shows the deserialization of a byte vector in BJData format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_bjdata/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/from_bson/","text":"nlohmann::basic_json:: from_bson \u00b6 // (1) template < typename InputType > static basic_json from_bson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.114 if an unsupported BSON record type is encountered. Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in BSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } See also \u00b6 BSON specification to_bson for the analogous serialization from_cbor for the related CBOR format from_msgpack for the related MessagePack format from_ubjson for the related UBJSON format Version history \u00b6 Added in version 3.4.0. Deprecation 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.","title":"from_bson"},{"location":"api/basic_json/from_bson/#nlohmannbasic_jsonfrom_bson","text":"// (1) template < typename InputType > static basic_json from_bson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_bson"},{"location":"api/basic_json/from_bson/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_bson/#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)","title":"Parameters"},{"location":"api/basic_json/from_bson/#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 .","title":"Return value"},{"location":"api/basic_json/from_bson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_bson/#exceptions","text":"Throws parse_error.114 if an unsupported BSON record type is encountered.","title":"Exceptions"},{"location":"api/basic_json/from_bson/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_bson/#examples","text":"Example The example shows the deserialization of a byte vector in BSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_bson/#see-also","text":"BSON specification to_bson for the analogous serialization from_cbor for the related CBOR format from_msgpack for the related MessagePack format from_ubjson for the related UBJSON format","title":"See also"},{"location":"api/basic_json/from_bson/#version-history","text":"Added in version 3.4.0. Deprecation 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.","title":"Version history"},{"location":"api/basic_json/from_cbor/","text":"nlohmann::basic_json:: from_cbor \u00b6 // (1) template < typename InputType > static basic_json from_cbor ( InputType && i , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); // (2) template < typename IteratorType > static basic_json from_cbor ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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 Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from CBOR were used in the given input or if the input is not valid CBOR Throws parse_error.113 if a string was expected as map key, but not found Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in CBOR format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"from_cbor"},{"location":"api/basic_json/from_cbor/#nlohmannbasic_jsonfrom_cbor","text":"// (1) template < typename InputType > static basic_json from_cbor ( InputType && i , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); // (2) template < typename IteratorType > static basic_json from_cbor ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_cbor"},{"location":"api/basic_json/from_cbor/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_cbor/#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","title":"Parameters"},{"location":"api/basic_json/from_cbor/#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 .","title":"Return value"},{"location":"api/basic_json/from_cbor/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_cbor/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from CBOR were used in the given input or if the input is not valid CBOR Throws parse_error.113 if a string was expected as map key, but not found","title":"Exceptions"},{"location":"api/basic_json/from_cbor/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_cbor/#examples","text":"Example The example shows the deserialization of a byte vector in CBOR format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_cbor/#version-history","text":"Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"Version history"},{"location":"api/basic_json/from_msgpack/","text":"nlohmann::basic_json:: from_msgpack \u00b6 // (1) template < typename InputType > static basic_json from_msgpack ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_msgpack ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the MessagePack serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from MessagePack were used in the given input or if the input is not valid MessagePack Throws parse_error.113 if a string was expected as map key, but not found Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in MessagePack format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"from_msgpack"},{"location":"api/basic_json/from_msgpack/#nlohmannbasic_jsonfrom_msgpack","text":"// (1) template < typename InputType > static basic_json from_msgpack ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_msgpack ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the MessagePack serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_msgpack"},{"location":"api/basic_json/from_msgpack/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_msgpack/#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)","title":"Parameters"},{"location":"api/basic_json/from_msgpack/#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 .","title":"Return value"},{"location":"api/basic_json/from_msgpack/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_msgpack/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from MessagePack were used in the given input or if the input is not valid MessagePack Throws parse_error.113 if a string was expected as map key, but not found","title":"Exceptions"},{"location":"api/basic_json/from_msgpack/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_msgpack/#examples","text":"Example The example shows the deserialization of a byte vector in MessagePack format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_msgpack/#version-history","text":"Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"Version history"},{"location":"api/basic_json/from_ubjson/","text":"nlohmann::basic_json:: from_ubjson \u00b6 // (1) template < typename InputType > static basic_json from_ubjson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_ubjson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in UBJSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 3.1.0. 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.","title":"from_ubjson"},{"location":"api/basic_json/from_ubjson/#nlohmannbasic_jsonfrom_ubjson","text":"// (1) template < typename InputType > static basic_json from_ubjson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_ubjson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_ubjson"},{"location":"api/basic_json/from_ubjson/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_ubjson/#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)","title":"Parameters"},{"location":"api/basic_json/from_ubjson/#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 .","title":"Return value"},{"location":"api/basic_json/from_ubjson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_ubjson/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully","title":"Exceptions"},{"location":"api/basic_json/from_ubjson/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_ubjson/#examples","text":"Example The example shows the deserialization of a byte vector in UBJSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_ubjson/#version-history","text":"Added in version 3.1.0. 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.","title":"Version history"},{"location":"api/basic_json/front/","text":"nlohmann::basic_json:: front \u00b6 reference front (); const_reference front () const ; Returns a reference to the first element in the container. For a JSON container c , the expression c . front () is equivalent to * c . begin () . Return value \u00b6 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. Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 If the JSON value is null , exception invalid_iterator.214 is thrown. Complexity \u00b6 Constant. Notes \u00b6 Precondition The array or object must not be empty. Calling front on an empty array or object yields undefined behavior. Examples \u00b6 Example The following code shows an example for front() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call front() //std::cout << j_null.front() << '\\n'; // would throw std :: cout << j_boolean . front () << '\\n' ; std :: cout << j_number_integer . front () << '\\n' ; std :: cout << j_number_float . front () << '\\n' ; std :: cout << j_object . front () << '\\n' ; //std::cout << j_object_empty.front() << '\\n'; // undefined behavior std :: cout << j_array . front () << '\\n' ; //std::cout << j_array_empty.front() << '\\n'; // undefined behavior std :: cout << j_string . front () << '\\n' ; } Output: true 17 23.42 1 1 \"Hello, world\" See also \u00b6 back to access the last element Version history \u00b6 Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"front"},{"location":"api/basic_json/front/#nlohmannbasic_jsonfront","text":"reference front (); const_reference front () const ; Returns a reference to the first element in the container. For a JSON container c , the expression c . front () is equivalent to * c . begin () .","title":"nlohmann::basic_json::front"},{"location":"api/basic_json/front/#return-value","text":"In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.","title":"Return value"},{"location":"api/basic_json/front/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/front/#exceptions","text":"If the JSON value is null , exception invalid_iterator.214 is thrown.","title":"Exceptions"},{"location":"api/basic_json/front/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/front/#notes","text":"Precondition The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.","title":"Notes"},{"location":"api/basic_json/front/#examples","text":"Example The following code shows an example for front() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call front() //std::cout << j_null.front() << '\\n'; // would throw std :: cout << j_boolean . front () << '\\n' ; std :: cout << j_number_integer . front () << '\\n' ; std :: cout << j_number_float . front () << '\\n' ; std :: cout << j_object . front () << '\\n' ; //std::cout << j_object_empty.front() << '\\n'; // undefined behavior std :: cout << j_array . front () << '\\n' ; //std::cout << j_array_empty.front() << '\\n'; // undefined behavior std :: cout << j_string . front () << '\\n' ; } Output: true 17 23.42 1 1 \"Hello, world\"","title":"Examples"},{"location":"api/basic_json/front/#see-also","text":"back to access the last element","title":"See also"},{"location":"api/basic_json/front/#version-history","text":"Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get/","text":"nlohmann::basic_json:: get \u00b6 // (1) template < typename ValueType > ValueType get () const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), std :: declval < ValueType &> ()))); // (2) template < typename BasicJsonType > BasicJsonType get () const ; // (3) template < typename PointerType > PointerType get_ptr (); template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; 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 from_json() method. The function is equivalent to executing ValueType ret ; JSONSerializer < ValueType >:: from_json ( * this , ret ); return ret ; This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&) , and json_serializer does not have a from_json() method of the form ValueType from_json(const basic_json&) If the type is not CopyConstructible and not DefaultConstructible , the value is converted by calling the json_serializer from_json() method. The function is then equivalent to executing return JSONSerializer < ValueTypeCV >:: from_json ( * this ); This overload is chosen if: ValueType is not basic_json and json_serializer has a from_json() method of the form ValueType from_json(const basic_json&) If json_serializer has both overloads of from_json() , the latter one is chosen. Overload for basic_json specializations. The function is equivalent to executing return * this ; Explicit pointer access to the internally stored JSON value. No copies are made. Template parameters \u00b6 ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t , object_t , string_t , boolean_t , number_integer_t , or number_unsigned_t , number_float_t , or binary_t . Other types will not compile. Return value \u00b6 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 Exceptions \u00b6 Depends on what json_serializer from_json() method throws Notes \u00b6 Undefined behavior Writing data to the pointee (overload 3) of the result yields an undefined state. Examples \u00b6 Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use explicit conversions auto v1 = json_types [ \"boolean\" ]. template get < bool > (); auto v2 = json_types [ \"number\" ][ \"integer\" ]. template get < int > (); auto v3 = json_types [ \"number\" ][ \"integer\" ]. template get < short > (); auto v4 = json_types [ \"number\" ][ \"floating-point\" ]. template get < float > (); auto v5 = json_types [ \"number\" ][ \"floating-point\" ]. template get < int > (); auto v6 = json_types [ \"string\" ]. template get < std :: string > (); auto v7 = json_types [ \"array\" ]. template get < std :: vector < short >> (); auto v8 = json_types . template get < std :: unordered_map < std :: string , json >> (); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . template get < const json :: number_integer_t *> (); auto p2 = value . template get < json :: number_integer_t *> (); auto p3 = value . template get < json :: number_integer_t * const > (); auto p4 = value . template get < const json :: number_integer_t * const > (); auto p5 = value . template get < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true Version history \u00b6 Since version 2.1.0. Since version 2.1.0. Extended to work with other specializations of basic_json in version 3.2.0. Since version 1.0.0.","title":"get"},{"location":"api/basic_json/get/#nlohmannbasic_jsonget","text":"// (1) template < typename ValueType > ValueType get () const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), std :: declval < ValueType &> ()))); // (2) template < typename BasicJsonType > BasicJsonType get () const ; // (3) template < typename PointerType > PointerType get_ptr (); template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; 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 from_json() method. The function is equivalent to executing ValueType ret ; JSONSerializer < ValueType >:: from_json ( * this , ret ); return ret ; This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&) , and json_serializer does not have a from_json() method of the form ValueType from_json(const basic_json&) If the type is not CopyConstructible and not DefaultConstructible , the value is converted by calling the json_serializer from_json() method. The function is then equivalent to executing return JSONSerializer < ValueTypeCV >:: from_json ( * this ); This overload is chosen if: ValueType is not basic_json and json_serializer has a from_json() method of the form ValueType from_json(const basic_json&) If json_serializer has both overloads of from_json() , the latter one is chosen. Overload for basic_json specializations. The function is equivalent to executing return * this ; Explicit pointer access to the internally stored JSON value. No copies are made.","title":"nlohmann::basic_json::get"},{"location":"api/basic_json/get/#template-parameters","text":"ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t , object_t , string_t , boolean_t , number_integer_t , or number_unsigned_t , number_float_t , or binary_t . Other types will not compile.","title":"Template parameters"},{"location":"api/basic_json/get/#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","title":"Return value"},{"location":"api/basic_json/get/#exceptions","text":"Depends on what json_serializer from_json() method throws","title":"Exceptions"},{"location":"api/basic_json/get/#notes","text":"Undefined behavior Writing data to the pointee (overload 3) of the result yields an undefined state.","title":"Notes"},{"location":"api/basic_json/get/#examples","text":"Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use explicit conversions auto v1 = json_types [ \"boolean\" ]. template get < bool > (); auto v2 = json_types [ \"number\" ][ \"integer\" ]. template get < int > (); auto v3 = json_types [ \"number\" ][ \"integer\" ]. template get < short > (); auto v4 = json_types [ \"number\" ][ \"floating-point\" ]. template get < float > (); auto v5 = json_types [ \"number\" ][ \"floating-point\" ]. template get < int > (); auto v6 = json_types [ \"string\" ]. template get < std :: string > (); auto v7 = json_types [ \"array\" ]. template get < std :: vector < short >> (); auto v8 = json_types . template get < std :: unordered_map < std :: string , json >> (); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . template get < const json :: number_integer_t *> (); auto p2 = value . template get < json :: number_integer_t *> (); auto p3 = value . template get < json :: number_integer_t * const > (); auto p4 = value . template get < const json :: number_integer_t * const > (); auto p5 = value . template get < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true","title":"Examples"},{"location":"api/basic_json/get/#version-history","text":"Since version 2.1.0. Since version 2.1.0. Extended to work with other specializations of basic_json in version 3.2.0. Since version 1.0.0.","title":"Version history"},{"location":"api/basic_json/get_allocator/","text":"nlohmann::basic_json:: get_allocator \u00b6 static allocator_type get_allocator (); Returns the allocator associated with the container. Return value \u00b6 associated allocator Examples \u00b6 Example The example shows how get_allocator() is used to created json values. #include #include using json = nlohmann :: json ; int main () { auto alloc = json :: get_allocator (); using traits_t = std :: allocator_traits < decltype ( alloc ) > ; json * j = traits_t :: allocate ( alloc , 1 ); traits_t :: construct ( alloc , j , \"Hello, world!\" ); std :: cout << * j << std :: endl ; traits_t :: destroy ( alloc , j ); traits_t :: deallocate ( alloc , j , 1 ); } Output: \"Hello, world!\" Version history \u00b6 Added in version 1.0.0.","title":"get_allocator"},{"location":"api/basic_json/get_allocator/#nlohmannbasic_jsonget_allocator","text":"static allocator_type get_allocator (); Returns the allocator associated with the container.","title":"nlohmann::basic_json::get_allocator"},{"location":"api/basic_json/get_allocator/#return-value","text":"associated allocator","title":"Return value"},{"location":"api/basic_json/get_allocator/#examples","text":"Example The example shows how get_allocator() is used to created json values. #include #include using json = nlohmann :: json ; int main () { auto alloc = json :: get_allocator (); using traits_t = std :: allocator_traits < decltype ( alloc ) > ; json * j = traits_t :: allocate ( alloc , 1 ); traits_t :: construct ( alloc , j , \"Hello, world!\" ); std :: cout << * j << std :: endl ; traits_t :: destroy ( alloc , j ); traits_t :: deallocate ( alloc , j , 1 ); } Output: \"Hello, world!\"","title":"Examples"},{"location":"api/basic_json/get_allocator/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/get_binary/","text":"nlohmann::basic_json:: get_binary \u00b6 binary_t & get_binary (); const binary_t & get_binary () const ; Returns a reference to the stored binary value. Return value \u00b6 Reference to binary value. Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 Throws type_error.302 if the value is not binary Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows how to query a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42 Version history \u00b6 Added in version 3.8.0.","title":"get_binary"},{"location":"api/basic_json/get_binary/#nlohmannbasic_jsonget_binary","text":"binary_t & get_binary (); const binary_t & get_binary () const ; Returns a reference to the stored binary value.","title":"nlohmann::basic_json::get_binary"},{"location":"api/basic_json/get_binary/#return-value","text":"Reference to binary value.","title":"Return value"},{"location":"api/basic_json/get_binary/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/get_binary/#exceptions","text":"Throws type_error.302 if the value is not binary","title":"Exceptions"},{"location":"api/basic_json/get_binary/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/get_binary/#examples","text":"Example The following code shows how to query a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42","title":"Examples"},{"location":"api/basic_json/get_binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get_ptr/","text":"nlohmann::basic_json:: get_ptr \u00b6 template < typename PointerType > PointerType get_ptr () noexcept ; template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; Implicit pointer access to the internally stored JSON value. No copies are made. Template parameters \u00b6 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. Return value \u00b6 pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Notes \u00b6 Undefined behavior Writing data to the pointee of the result yields an undefined state. Examples \u00b6 Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . get_ptr < const json :: number_integer_t *> (); auto p2 = value . get_ptr < json :: number_integer_t *> (); auto p3 = value . get_ptr < json :: number_integer_t * const > (); auto p4 = value . get_ptr < const json :: number_integer_t * const > (); auto p5 = value . get_ptr < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true Version history \u00b6 Added in version 1.0.0. Extended to binary types in version 3.8.0.","title":"get_ptr"},{"location":"api/basic_json/get_ptr/#nlohmannbasic_jsonget_ptr","text":"template < typename PointerType > PointerType get_ptr () noexcept ; template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; Implicit pointer access to the internally stored JSON value. No copies are made.","title":"nlohmann::basic_json::get_ptr"},{"location":"api/basic_json/get_ptr/#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.","title":"Template parameters"},{"location":"api/basic_json/get_ptr/#return-value","text":"pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise","title":"Return value"},{"location":"api/basic_json/get_ptr/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/get_ptr/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/get_ptr/#notes","text":"Undefined behavior Writing data to the pointee of the result yields an undefined state.","title":"Notes"},{"location":"api/basic_json/get_ptr/#examples","text":"Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . get_ptr < const json :: number_integer_t *> (); auto p2 = value . get_ptr < json :: number_integer_t *> (); auto p3 = value . get_ptr < json :: number_integer_t * const > (); auto p4 = value . get_ptr < const json :: number_integer_t * const > (); auto p5 = value . get_ptr < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true","title":"Examples"},{"location":"api/basic_json/get_ptr/#version-history","text":"Added in version 1.0.0. Extended to binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get_ref/","text":"nlohmann::basic_json:: get_ref \u00b6 template < typename ReferenceType > ReferenceType get_ref (); template < typename ReferenceType > const ReferenceType get_ref () const ; Implicit reference access to the internally stored JSON value. No copies are made. Template parameters \u00b6 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. Return value \u00b6 reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 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\" . Complexity \u00b6 Constant. Notes \u00b6 Undefined behavior Writing data to the referee of the result yields an undefined state. Examples \u00b6 Example The example shows several calls to get_ref() . #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting references auto r1 = value . get_ref < const json :: number_integer_t &> (); auto r2 = value . get_ref < json :: number_integer_t &> (); // print the values std :: cout << r1 << ' ' << r2 << '\\n' ; // incompatible type throws exception try { auto r3 = value . get_ref < json :: number_float_t &> (); } catch ( const json :: type_error & ex ) { std :: cout << ex . what () << '\\n' ; } } Output: 17 17 [ jso n .excep t io n . t ype_error. 303 ] i n compa t ible Re feren ceType f or ge t _re f , ac tual t ype is nu mber Version history \u00b6 Added in version 1.1.0. Extended to binary types in version 3.8.0.","title":"get_ref"},{"location":"api/basic_json/get_ref/#nlohmannbasic_jsonget_ref","text":"template < typename ReferenceType > ReferenceType get_ref (); template < typename ReferenceType > const ReferenceType get_ref () const ; Implicit reference access to the internally stored JSON value. No copies are made.","title":"nlohmann::basic_json::get_ref"},{"location":"api/basic_json/get_ref/#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.","title":"Template parameters"},{"location":"api/basic_json/get_ref/#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","title":"Return value"},{"location":"api/basic_json/get_ref/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/get_ref/#exceptions","text":"Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: \"incompatible ReferenceType for get_ref, actual type is binary\" .","title":"Exceptions"},{"location":"api/basic_json/get_ref/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/get_ref/#notes","text":"Undefined behavior Writing data to the referee of the result yields an undefined state.","title":"Notes"},{"location":"api/basic_json/get_ref/#examples","text":"Example The example shows several calls to get_ref() . #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting references auto r1 = value . get_ref < const json :: number_integer_t &> (); auto r2 = value . get_ref < json :: number_integer_t &> (); // print the values std :: cout << r1 << ' ' << r2 << '\\n' ; // incompatible type throws exception try { auto r3 = value . get_ref < json :: number_float_t &> (); } catch ( const json :: type_error & ex ) { std :: cout << ex . what () << '\\n' ; } } Output: 17 17 [ jso n .excep t io n . t ype_error. 303 ] i n compa t ible Re feren ceType f or ge t _re f , ac tual t ype is nu mber","title":"Examples"},{"location":"api/basic_json/get_ref/#version-history","text":"Added in version 1.1.0. Extended to binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get_to/","text":"nlohmann::basic_json:: get_to \u00b6 template < typename ValueType > ValueType & get_to ( ValueType & v ) const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), v ))); Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer from_json() method. The function is equivalent to executing ValueType v ; JSONSerializer < ValueType >:: from_json ( * this , v ); This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&) Template parameters \u00b6 ValueType the value type to return Return value \u00b6 the input parameter, allowing chaining calls Exceptions \u00b6 Depends on what json_serializer from_json() method throws Examples \u00b6 Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std :: vector < short > , (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; bool v1 ; int v2 ; short v3 ; float v4 ; int v5 ; std :: string v6 ; std :: vector < short > v7 ; std :: unordered_map < std :: string , json > v8 ; // use explicit conversions json_types [ \"boolean\" ]. get_to ( v1 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v2 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v3 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v4 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v5 ); json_types [ \"string\" ]. get_to ( v6 ); json_types [ \"array\" ]. get_to ( v7 ); json_types . get_to ( v8 ); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] Version history \u00b6 Since version 3.3.0.","title":"get_to"},{"location":"api/basic_json/get_to/#nlohmannbasic_jsonget_to","text":"template < typename ValueType > ValueType & get_to ( ValueType & v ) const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), v ))); Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer from_json() method. The function is equivalent to executing ValueType v ; JSONSerializer < ValueType >:: from_json ( * this , v ); This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&)","title":"nlohmann::basic_json::get_to"},{"location":"api/basic_json/get_to/#template-parameters","text":"ValueType the value type to return","title":"Template parameters"},{"location":"api/basic_json/get_to/#return-value","text":"the input parameter, allowing chaining calls","title":"Return value"},{"location":"api/basic_json/get_to/#exceptions","text":"Depends on what json_serializer from_json() method throws","title":"Exceptions"},{"location":"api/basic_json/get_to/#examples","text":"Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std :: vector < short > , (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; bool v1 ; int v2 ; short v3 ; float v4 ; int v5 ; std :: string v6 ; std :: vector < short > v7 ; std :: unordered_map < std :: string , json > v8 ; // use explicit conversions json_types [ \"boolean\" ]. get_to ( v1 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v2 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v3 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v4 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v5 ); json_types [ \"string\" ]. get_to ( v6 ); json_types [ \"array\" ]. get_to ( v7 ); json_types . get_to ( v8 ); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ]","title":"Examples"},{"location":"api/basic_json/get_to/#version-history","text":"Since version 3.3.0.","title":"Version history"},{"location":"api/basic_json/input_format_t/","text":"nlohmann::basic_json:: input_format_t \u00b6 enum class input_format_t { json , cbor , msgpack , ubjson , bson , bjdata }; This enumeration is used in the sax_parse function to choose the input format to parse: json JSON (JavaScript Object Notation) cbor CBOR (Concise Binary Object Representation) msgpack MessagePack ubjson UBJSON (Universal Binary JSON) bson BSON (Binary JSON) bjdata BJData (Binary JData) Examples \u00b6 Example The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true Version history \u00b6 Added in version 3.2.0.","title":"input_format_t"},{"location":"api/basic_json/input_format_t/#nlohmannbasic_jsoninput_format_t","text":"enum class input_format_t { json , cbor , msgpack , ubjson , bson , bjdata }; This enumeration is used in the sax_parse function to choose the input format to parse: json JSON (JavaScript Object Notation) cbor CBOR (Concise Binary Object Representation) msgpack MessagePack ubjson UBJSON (Universal Binary JSON) bson BSON (Binary JSON) bjdata BJData (Binary JData)","title":"nlohmann::basic_json::input_format_t"},{"location":"api/basic_json/input_format_t/#examples","text":"Example The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true","title":"Examples"},{"location":"api/basic_json/input_format_t/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/basic_json/insert/","text":"nlohmann::basic_json:: insert \u00b6 // (1) iterator insert ( const_iterator pos , const basic_json & val ); iterator insert ( const_iterator pos , basic_json && val ); // (2) iterator insert ( const_iterator pos , size_type cnt , const basic_json & val ); // (3) iterator insert ( const_iterator pos , const_iterator first , const_iterator last ); // (4) iterator insert ( const_iterator pos , initializer_list_t ilist ); // (5) void insert ( const_iterator first , const_iterator last ); Inserts element val into array before iterator pos . Inserts cnt copies of val into array before iterator pos . Inserts elements from range [first, last) into array before iterator pos . Inserts elements from initializer list ilist into array before iterator pos . Inserts elements from range [first, last) into object. Parameters \u00b6 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 Return value \u00b6 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 (none) Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 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\" 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\" Complexity \u00b6 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. Examples \u00b6 Example (1): insert element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 10 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 10 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 10 [ 1 , 2 , 10 , 3 , 4 ] Example (2): insert copies of element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 7 copies of number 7 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 7 , 7 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 7 , 7 , 7 , 7 , 7 , 7 , 7 , 3 , 4 ] Example (3): insert range of elements into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // create a JSON array to copy values from json v2 = { \"one\" , \"two\" , \"three\" , \"four\" }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), v2 . begin (), v2 . end ()); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: \"one\" [ 1 , 2 , 3 , 4 , \"one\" , \"two\" , \"three\" , \"four\" ] Example (4): insert elements from initializer list into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), { 7 , 8 , 9 }); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 3 , 4 , 7 , 8 , 9 ] Example (5): insert range of elements into object The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create two JSON objects json j1 = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; json j2 = {{ \"eleven\" , \"elf\" }, { \"seventeen\" , \"siebzehn\" }}; // output objects std :: cout << j1 << '\\n' ; std :: cout << j2 << '\\n' ; // insert range from j2 to j1 j1 . insert ( j2 . begin (), j2 . end ()); // output result of insert call std :: cout << j1 << '\\n' ; } Output: { \"one\" : \"eins\" , \"two\" : \"zwei\" } { \"eleven\" : \"elf\" , \"seventeen\" : \"siebzehn\" } { \"eleven\" : \"elf\" , \"one\" : \"eins\" , \"seventeen\" : \"siebzehn\" , \"two\" : \"zwei\" } Version history \u00b6 Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 3.0.0.","title":"insert"},{"location":"api/basic_json/insert/#nlohmannbasic_jsoninsert","text":"// (1) iterator insert ( const_iterator pos , const basic_json & val ); iterator insert ( const_iterator pos , basic_json && val ); // (2) iterator insert ( const_iterator pos , size_type cnt , const basic_json & val ); // (3) iterator insert ( const_iterator pos , const_iterator first , const_iterator last ); // (4) iterator insert ( const_iterator pos , initializer_list_t ilist ); // (5) void insert ( const_iterator first , const_iterator last ); Inserts element val into array before iterator pos . Inserts cnt copies of val into array before iterator pos . Inserts elements from range [first, last) into array before iterator pos . Inserts elements from initializer list ilist into array before iterator pos . Inserts elements from range [first, last) into object.","title":"nlohmann::basic_json::insert"},{"location":"api/basic_json/insert/#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","title":"Parameters"},{"location":"api/basic_json/insert/#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 (none)","title":"Return value"},{"location":"api/basic_json/insert/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/insert/#exceptions","text":"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\" 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\"","title":"Exceptions"},{"location":"api/basic_json/insert/#complexity","text":"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.","title":"Complexity"},{"location":"api/basic_json/insert/#examples","text":"Example (1): insert element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 10 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 10 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 10 [ 1 , 2 , 10 , 3 , 4 ] Example (2): insert copies of element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 7 copies of number 7 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 7 , 7 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 7 , 7 , 7 , 7 , 7 , 7 , 7 , 3 , 4 ] Example (3): insert range of elements into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // create a JSON array to copy values from json v2 = { \"one\" , \"two\" , \"three\" , \"four\" }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), v2 . begin (), v2 . end ()); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: \"one\" [ 1 , 2 , 3 , 4 , \"one\" , \"two\" , \"three\" , \"four\" ] Example (4): insert elements from initializer list into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), { 7 , 8 , 9 }); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 3 , 4 , 7 , 8 , 9 ] Example (5): insert range of elements into object The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create two JSON objects json j1 = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; json j2 = {{ \"eleven\" , \"elf\" }, { \"seventeen\" , \"siebzehn\" }}; // output objects std :: cout << j1 << '\\n' ; std :: cout << j2 << '\\n' ; // insert range from j2 to j1 j1 . insert ( j2 . begin (), j2 . end ()); // output result of insert call std :: cout << j1 << '\\n' ; } Output: { \"one\" : \"eins\" , \"two\" : \"zwei\" } { \"eleven\" : \"elf\" , \"seventeen\" : \"siebzehn\" } { \"eleven\" : \"elf\" , \"one\" : \"eins\" , \"seventeen\" : \"siebzehn\" , \"two\" : \"zwei\" }","title":"Examples"},{"location":"api/basic_json/insert/#version-history","text":"Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 3.0.0.","title":"Version history"},{"location":"api/basic_json/invalid_iterator/","text":"nlohmann::basic_json:: invalid_iterator \u00b6 class invalid_iterator : public exception ; This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx (see list of iterator errors ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .i n valid_i terat or. 207 ] ca nn o t use key() f or n o n - objec t i terat ors excep t io n id : 207 See also \u00b6 List of iterator errors parse_error for exceptions indicating a parse error 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 Version history \u00b6 Since version 3.0.0.","title":"invalid_iterator"},{"location":"api/basic_json/invalid_iterator/#nlohmannbasic_jsoninvalid_iterator","text":"class invalid_iterator : public exception ; This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx (see list of iterator errors ).","title":"nlohmann::basic_json::invalid_iterator"},{"location":"api/basic_json/invalid_iterator/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/invalid_iterator/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/invalid_iterator/#examples","text":"Example The following code shows how a invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .i n valid_i terat or. 207 ] ca nn o t use key() f or n o n - objec t i terat ors excep t io n id : 207","title":"Examples"},{"location":"api/basic_json/invalid_iterator/#see-also","text":"List of iterator errors parse_error for exceptions indicating a parse error 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","title":"See also"},{"location":"api/basic_json/invalid_iterator/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/is_array/","text":"nlohmann::basic_json:: is_array \u00b6 constexpr bool is_array () const noexcept ; This function returns true if and only if the JSON value is an array. Return value \u00b6 true if type is an array, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_array() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_array() std :: cout << std :: boolalpha ; std :: cout << j_null . is_array () << '\\n' ; std :: cout << j_boolean . is_array () << '\\n' ; std :: cout << j_number_integer . is_array () << '\\n' ; std :: cout << j_number_unsigned_integer . is_array () << '\\n' ; std :: cout << j_number_float . is_array () << '\\n' ; std :: cout << j_object . is_array () << '\\n' ; std :: cout << j_array . is_array () << '\\n' ; std :: cout << j_string . is_array () << '\\n' ; std :: cout << j_binary . is_array () << '\\n' ; } Output: false false false false false false true false false Version history \u00b6 Added in version 1.0.0.","title":"is_array"},{"location":"api/basic_json/is_array/#nlohmannbasic_jsonis_array","text":"constexpr bool is_array () const noexcept ; This function returns true if and only if the JSON value is an array.","title":"nlohmann::basic_json::is_array"},{"location":"api/basic_json/is_array/#return-value","text":"true if type is an array, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_array/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_array/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_array/#examples","text":"Example The following code exemplifies is_array() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_array() std :: cout << std :: boolalpha ; std :: cout << j_null . is_array () << '\\n' ; std :: cout << j_boolean . is_array () << '\\n' ; std :: cout << j_number_integer . is_array () << '\\n' ; std :: cout << j_number_unsigned_integer . is_array () << '\\n' ; std :: cout << j_number_float . is_array () << '\\n' ; std :: cout << j_object . is_array () << '\\n' ; std :: cout << j_array . is_array () << '\\n' ; std :: cout << j_string . is_array () << '\\n' ; std :: cout << j_binary . is_array () << '\\n' ; } Output: false false false false false false true false false","title":"Examples"},{"location":"api/basic_json/is_array/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_binary/","text":"nlohmann::basic_json:: is_binary \u00b6 constexpr bool is_binary () const noexcept ; This function returns true if and only if the JSON value is binary array. Return value \u00b6 true if type is binary, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_binary() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_binary() std :: cout << std :: boolalpha ; std :: cout << j_null . is_binary () << '\\n' ; std :: cout << j_boolean . is_binary () << '\\n' ; std :: cout << j_number_integer . is_binary () << '\\n' ; std :: cout << j_number_unsigned_integer . is_binary () << '\\n' ; std :: cout << j_number_float . is_binary () << '\\n' ; std :: cout << j_object . is_binary () << '\\n' ; std :: cout << j_array . is_binary () << '\\n' ; std :: cout << j_string . is_binary () << '\\n' ; std :: cout << j_binary . is_binary () << '\\n' ; } Output: false false false false false false false false true Version history \u00b6 Added in version 3.8.0.","title":"is_binary"},{"location":"api/basic_json/is_binary/#nlohmannbasic_jsonis_binary","text":"constexpr bool is_binary () const noexcept ; This function returns true if and only if the JSON value is binary array.","title":"nlohmann::basic_json::is_binary"},{"location":"api/basic_json/is_binary/#return-value","text":"true if type is binary, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_binary/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_binary/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_binary/#examples","text":"Example The following code exemplifies is_binary() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_binary() std :: cout << std :: boolalpha ; std :: cout << j_null . is_binary () << '\\n' ; std :: cout << j_boolean . is_binary () << '\\n' ; std :: cout << j_number_integer . is_binary () << '\\n' ; std :: cout << j_number_unsigned_integer . is_binary () << '\\n' ; std :: cout << j_number_float . is_binary () << '\\n' ; std :: cout << j_object . is_binary () << '\\n' ; std :: cout << j_array . is_binary () << '\\n' ; std :: cout << j_string . is_binary () << '\\n' ; std :: cout << j_binary . is_binary () << '\\n' ; } Output: false false false false false false false false true","title":"Examples"},{"location":"api/basic_json/is_binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/is_boolean/","text":"nlohmann::basic_json:: is_boolean \u00b6 constexpr bool is_boolean () const noexcept ; This function returns true if and only if the JSON value is true or false . Return value \u00b6 true if type is boolean, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_boolean() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_boolean() std :: cout << std :: boolalpha ; std :: cout << j_null . is_boolean () << '\\n' ; std :: cout << j_boolean . is_boolean () << '\\n' ; std :: cout << j_number_integer . is_boolean () << '\\n' ; std :: cout << j_number_unsigned_integer . is_boolean () << '\\n' ; std :: cout << j_number_float . is_boolean () << '\\n' ; std :: cout << j_object . is_boolean () << '\\n' ; std :: cout << j_array . is_boolean () << '\\n' ; std :: cout << j_string . is_boolean () << '\\n' ; std :: cout << j_binary . is_boolean () << '\\n' ; } Output: false true false false false false false false false Version history \u00b6 Added in version 1.0.0.","title":"is_boolean"},{"location":"api/basic_json/is_boolean/#nlohmannbasic_jsonis_boolean","text":"constexpr bool is_boolean () const noexcept ; This function returns true if and only if the JSON value is true or false .","title":"nlohmann::basic_json::is_boolean"},{"location":"api/basic_json/is_boolean/#return-value","text":"true if type is boolean, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_boolean/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_boolean/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_boolean/#examples","text":"Example The following code exemplifies is_boolean() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_boolean() std :: cout << std :: boolalpha ; std :: cout << j_null . is_boolean () << '\\n' ; std :: cout << j_boolean . is_boolean () << '\\n' ; std :: cout << j_number_integer . is_boolean () << '\\n' ; std :: cout << j_number_unsigned_integer . is_boolean () << '\\n' ; std :: cout << j_number_float . is_boolean () << '\\n' ; std :: cout << j_object . is_boolean () << '\\n' ; std :: cout << j_array . is_boolean () << '\\n' ; std :: cout << j_string . is_boolean () << '\\n' ; std :: cout << j_binary . is_boolean () << '\\n' ; } Output: false true false false false false false false false","title":"Examples"},{"location":"api/basic_json/is_boolean/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_discarded/","text":"nlohmann::basic_json:: is_discarded \u00b6 constexpr bool is_discarded () const noexcept ; This function returns true for a JSON value if either: the value was discarded during parsing with a callback function (see parser_callback_t ), or the value is the result of parsing invalid JSON with parameter allow_exceptions set to false ; see parse for more information. Return value \u00b6 true if type is discarded, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Notes \u00b6 Comparisons Discarded values are never compared equal with operator== . That is, checking whether a JSON value j is discarded will only work via: j . is_discarded () because j == json :: value_t :: discarded 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. Examples \u00b6 Example The following code exemplifies is_discarded() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_discarded() std :: cout << std :: boolalpha ; std :: cout << j_null . is_discarded () << '\\n' ; std :: cout << j_boolean . is_discarded () << '\\n' ; std :: cout << j_number_integer . is_discarded () << '\\n' ; std :: cout << j_number_unsigned_integer . is_discarded () << '\\n' ; std :: cout << j_number_float . is_discarded () << '\\n' ; std :: cout << j_object . is_discarded () << '\\n' ; std :: cout << j_array . is_discarded () << '\\n' ; std :: cout << j_string . is_discarded () << '\\n' ; std :: cout << j_binary . is_discarded () << '\\n' ; } Output: false false false false false false false false false Version history \u00b6 Added in version 1.0.0.","title":"is_discarded"},{"location":"api/basic_json/is_discarded/#nlohmannbasic_jsonis_discarded","text":"constexpr bool is_discarded () const noexcept ; This function returns true for a JSON value if either: the value was discarded during parsing with a callback function (see parser_callback_t ), or the value is the result of parsing invalid JSON with parameter allow_exceptions set to false ; see parse for more information.","title":"nlohmann::basic_json::is_discarded"},{"location":"api/basic_json/is_discarded/#return-value","text":"true if type is discarded, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_discarded/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_discarded/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_discarded/#notes","text":"Comparisons Discarded values are never compared equal with operator== . That is, checking whether a JSON value j is discarded will only work via: j . is_discarded () because j == json :: value_t :: discarded 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.","title":"Notes"},{"location":"api/basic_json/is_discarded/#examples","text":"Example The following code exemplifies is_discarded() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_discarded() std :: cout << std :: boolalpha ; std :: cout << j_null . is_discarded () << '\\n' ; std :: cout << j_boolean . is_discarded () << '\\n' ; std :: cout << j_number_integer . is_discarded () << '\\n' ; std :: cout << j_number_unsigned_integer . is_discarded () << '\\n' ; std :: cout << j_number_float . is_discarded () << '\\n' ; std :: cout << j_object . is_discarded () << '\\n' ; std :: cout << j_array . is_discarded () << '\\n' ; std :: cout << j_string . is_discarded () << '\\n' ; std :: cout << j_binary . is_discarded () << '\\n' ; } Output: false false false false false false false false false","title":"Examples"},{"location":"api/basic_json/is_discarded/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_null/","text":"nlohmann::basic_json:: is_null \u00b6 constexpr bool is_null () const noexcept ; This function returns true if and only if the JSON value is null . Return value \u00b6 true if type is null , false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_null() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_null() std :: cout << std :: boolalpha ; std :: cout << j_null . is_null () << '\\n' ; std :: cout << j_boolean . is_null () << '\\n' ; std :: cout << j_number_integer . is_null () << '\\n' ; std :: cout << j_number_unsigned_integer . is_null () << '\\n' ; std :: cout << j_number_float . is_null () << '\\n' ; std :: cout << j_object . is_null () << '\\n' ; std :: cout << j_array . is_null () << '\\n' ; std :: cout << j_string . is_null () << '\\n' ; std :: cout << j_binary . is_null () << '\\n' ; } Output: true false false false false false false false false Version history \u00b6 Added in version 1.0.0.","title":"is_null"},{"location":"api/basic_json/is_null/#nlohmannbasic_jsonis_null","text":"constexpr bool is_null () const noexcept ; This function returns true if and only if the JSON value is null .","title":"nlohmann::basic_json::is_null"},{"location":"api/basic_json/is_null/#return-value","text":"true if type is null , false otherwise.","title":"Return value"},{"location":"api/basic_json/is_null/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_null/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_null/#examples","text":"Example The following code exemplifies is_null() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_null() std :: cout << std :: boolalpha ; std :: cout << j_null . is_null () << '\\n' ; std :: cout << j_boolean . is_null () << '\\n' ; std :: cout << j_number_integer . is_null () << '\\n' ; std :: cout << j_number_unsigned_integer . is_null () << '\\n' ; std :: cout << j_number_float . is_null () << '\\n' ; std :: cout << j_object . is_null () << '\\n' ; std :: cout << j_array . is_null () << '\\n' ; std :: cout << j_string . is_null () << '\\n' ; std :: cout << j_binary . is_null () << '\\n' ; } Output: true false false false false false false false false","title":"Examples"},{"location":"api/basic_json/is_null/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_number/","text":"nlohmann::basic_json:: is_number \u00b6 constexpr bool is_number () const noexcept ; This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. Return value \u00b6 true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Possible implementation \u00b6 constexpr bool is_number () const noexcept { return is_number_integer () || is_number_float (); } Examples \u00b6 Example The following code exemplifies is_number() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number () << '\\n' ; std :: cout << j_boolean . is_number () << '\\n' ; std :: cout << j_number_integer . is_number () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number () << '\\n' ; std :: cout << j_number_float . is_number () << '\\n' ; std :: cout << j_object . is_number () << '\\n' ; std :: cout << j_array . is_number () << '\\n' ; std :: cout << j_string . is_number () << '\\n' ; std :: cout << j_binary . is_number () << '\\n' ; } Output: false false true true true false false false false See also \u00b6 is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number Version history \u00b6 Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"is_number"},{"location":"api/basic_json/is_number/#nlohmannbasic_jsonis_number","text":"constexpr bool is_number () const noexcept ; This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.","title":"nlohmann::basic_json::is_number"},{"location":"api/basic_json/is_number/#return-value","text":"true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number/#possible-implementation","text":"constexpr bool is_number () const noexcept { return is_number_integer () || is_number_float (); }","title":"Possible implementation"},{"location":"api/basic_json/is_number/#examples","text":"Example The following code exemplifies is_number() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number () << '\\n' ; std :: cout << j_boolean . is_number () << '\\n' ; std :: cout << j_number_integer . is_number () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number () << '\\n' ; std :: cout << j_number_float . is_number () << '\\n' ; std :: cout << j_object . is_number () << '\\n' ; std :: cout << j_array . is_number () << '\\n' ; std :: cout << j_string . is_number () << '\\n' ; std :: cout << j_binary . is_number () << '\\n' ; } Output: false false true true true false false false false","title":"Examples"},{"location":"api/basic_json/is_number/#see-also","text":"is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number","title":"See also"},{"location":"api/basic_json/is_number/#version-history","text":"Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"Version history"},{"location":"api/basic_json/is_number_float/","text":"nlohmann::basic_json:: is_number_float \u00b6 constexpr bool is_number_float () const noexcept ; This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. Return value \u00b6 true if type is a floating-point number, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_number_float() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_float() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_float () << '\\n' ; std :: cout << j_boolean . is_number_float () << '\\n' ; std :: cout << j_number_integer . is_number_float () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_float () << '\\n' ; std :: cout << j_number_float . is_number_float () << '\\n' ; std :: cout << j_object . is_number_float () << '\\n' ; std :: cout << j_array . is_number_float () << '\\n' ; std :: cout << j_string . is_number_float () << '\\n' ; std :: cout << j_binary . is_number_float () << '\\n' ; } Output: false false false false true false false false false See also \u00b6 is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number Version history \u00b6 Added in version 1.0.0.","title":"is_number_float"},{"location":"api/basic_json/is_number_float/#nlohmannbasic_jsonis_number_float","text":"constexpr bool is_number_float () const noexcept ; This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.","title":"nlohmann::basic_json::is_number_float"},{"location":"api/basic_json/is_number_float/#return-value","text":"true if type is a floating-point number, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number_float/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number_float/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number_float/#examples","text":"Example The following code exemplifies is_number_float() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_float() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_float () << '\\n' ; std :: cout << j_boolean . is_number_float () << '\\n' ; std :: cout << j_number_integer . is_number_float () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_float () << '\\n' ; std :: cout << j_number_float . is_number_float () << '\\n' ; std :: cout << j_object . is_number_float () << '\\n' ; std :: cout << j_array . is_number_float () << '\\n' ; std :: cout << j_string . is_number_float () << '\\n' ; std :: cout << j_binary . is_number_float () << '\\n' ; } Output: false false false false true false false false false","title":"Examples"},{"location":"api/basic_json/is_number_float/#see-also","text":"is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number","title":"See also"},{"location":"api/basic_json/is_number_float/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_number_integer/","text":"nlohmann::basic_json:: is_number_integer \u00b6 constexpr bool is_number_integer () const noexcept ; This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. Return value \u00b6 true if type is an integer or unsigned integer number, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_number_integer() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_integer() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_integer () << '\\n' ; std :: cout << j_boolean . is_number_integer () << '\\n' ; std :: cout << j_number_integer . is_number_integer () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_integer () << '\\n' ; std :: cout << j_number_float . is_number_integer () << '\\n' ; std :: cout << j_object . is_number_integer () << '\\n' ; std :: cout << j_array . is_number_integer () << '\\n' ; std :: cout << j_string . is_number_integer () << '\\n' ; std :: cout << j_binary . is_number_integer () << '\\n' ; } Output: false false true true false false false false false See also \u00b6 is_number() check if value is a number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number Version history \u00b6 Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"is_number_integer"},{"location":"api/basic_json/is_number_integer/#nlohmannbasic_jsonis_number_integer","text":"constexpr bool is_number_integer () const noexcept ; This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.","title":"nlohmann::basic_json::is_number_integer"},{"location":"api/basic_json/is_number_integer/#return-value","text":"true if type is an integer or unsigned integer number, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number_integer/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number_integer/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number_integer/#examples","text":"Example The following code exemplifies is_number_integer() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_integer() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_integer () << '\\n' ; std :: cout << j_boolean . is_number_integer () << '\\n' ; std :: cout << j_number_integer . is_number_integer () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_integer () << '\\n' ; std :: cout << j_number_float . is_number_integer () << '\\n' ; std :: cout << j_object . is_number_integer () << '\\n' ; std :: cout << j_array . is_number_integer () << '\\n' ; std :: cout << j_string . is_number_integer () << '\\n' ; std :: cout << j_binary . is_number_integer () << '\\n' ; } Output: false false true true false false false false false","title":"Examples"},{"location":"api/basic_json/is_number_integer/#see-also","text":"is_number() check if value is a number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number","title":"See also"},{"location":"api/basic_json/is_number_integer/#version-history","text":"Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"Version history"},{"location":"api/basic_json/is_number_unsigned/","text":"nlohmann::basic_json:: is_number_unsigned \u00b6 constexpr bool is_number_unsigned () const noexcept ; This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. Return value \u00b6 true if type is an unsigned integer number, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_number_unsigned() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_unsigned() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_unsigned () << '\\n' ; std :: cout << j_boolean . is_number_unsigned () << '\\n' ; std :: cout << j_number_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_float . is_number_unsigned () << '\\n' ; std :: cout << j_object . is_number_unsigned () << '\\n' ; std :: cout << j_array . is_number_unsigned () << '\\n' ; std :: cout << j_string . is_number_unsigned () << '\\n' ; std :: cout << j_binary . is_number_unsigned () << '\\n' ; } Output: false false false true false false false false false See also \u00b6 is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_float() check if value is a floating-point number Version history \u00b6 Added in version 2.0.0.","title":"is_number_unsigned"},{"location":"api/basic_json/is_number_unsigned/#nlohmannbasic_jsonis_number_unsigned","text":"constexpr bool is_number_unsigned () const noexcept ; This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.","title":"nlohmann::basic_json::is_number_unsigned"},{"location":"api/basic_json/is_number_unsigned/#return-value","text":"true if type is an unsigned integer number, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number_unsigned/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number_unsigned/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number_unsigned/#examples","text":"Example The following code exemplifies is_number_unsigned() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_unsigned() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_unsigned () << '\\n' ; std :: cout << j_boolean . is_number_unsigned () << '\\n' ; std :: cout << j_number_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_float . is_number_unsigned () << '\\n' ; std :: cout << j_object . is_number_unsigned () << '\\n' ; std :: cout << j_array . is_number_unsigned () << '\\n' ; std :: cout << j_string . is_number_unsigned () << '\\n' ; std :: cout << j_binary . is_number_unsigned () << '\\n' ; } Output: false false false true false false false false false","title":"Examples"},{"location":"api/basic_json/is_number_unsigned/#see-also","text":"is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_float() check if value is a floating-point number","title":"See also"},{"location":"api/basic_json/is_number_unsigned/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/is_object/","text":"nlohmann::basic_json:: is_object \u00b6 constexpr bool is_object () const noexcept ; This function returns true if and only if the JSON value is an object. Return value \u00b6 true if type is an object, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_object() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_object() std :: cout << std :: boolalpha ; std :: cout << j_null . is_object () << '\\n' ; std :: cout << j_boolean . is_object () << '\\n' ; std :: cout << j_number_integer . is_object () << '\\n' ; std :: cout << j_number_unsigned_integer . is_object () << '\\n' ; std :: cout << j_number_float . is_object () << '\\n' ; std :: cout << j_object . is_object () << '\\n' ; std :: cout << j_array . is_object () << '\\n' ; std :: cout << j_string . is_object () << '\\n' ; std :: cout << j_binary . is_object () << '\\n' ; } Output: false false false false false true false false false Version history \u00b6 Added in version 1.0.0.","title":"is_object"},{"location":"api/basic_json/is_object/#nlohmannbasic_jsonis_object","text":"constexpr bool is_object () const noexcept ; This function returns true if and only if the JSON value is an object.","title":"nlohmann::basic_json::is_object"},{"location":"api/basic_json/is_object/#return-value","text":"true if type is an object, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_object/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_object/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_object/#examples","text":"Example The following code exemplifies is_object() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_object() std :: cout << std :: boolalpha ; std :: cout << j_null . is_object () << '\\n' ; std :: cout << j_boolean . is_object () << '\\n' ; std :: cout << j_number_integer . is_object () << '\\n' ; std :: cout << j_number_unsigned_integer . is_object () << '\\n' ; std :: cout << j_number_float . is_object () << '\\n' ; std :: cout << j_object . is_object () << '\\n' ; std :: cout << j_array . is_object () << '\\n' ; std :: cout << j_string . is_object () << '\\n' ; std :: cout << j_binary . is_object () << '\\n' ; } Output: false false false false false true false false false","title":"Examples"},{"location":"api/basic_json/is_object/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_primitive/","text":"nlohmann::basic_json:: is_primitive \u00b6 constexpr bool is_primitive () const noexcept ; This function returns true if and only if the JSON type is primitive (string, number, boolean, null , binary). Return value \u00b6 true if type is primitive (string, number, boolean, null , or binary), false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Possible implementation \u00b6 constexpr bool is_primitive () const noexcept { return is_null () || is_string () || is_boolean () || is_number () || is_binary (); } Notes \u00b6 The term primitive stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values. Examples \u00b6 Example The following code exemplifies is_primitive() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_primitive() std :: cout << std :: boolalpha ; std :: cout << j_null . is_primitive () << '\\n' ; std :: cout << j_boolean . is_primitive () << '\\n' ; std :: cout << j_number_integer . is_primitive () << '\\n' ; std :: cout << j_number_unsigned_integer . is_primitive () << '\\n' ; std :: cout << j_number_float . is_primitive () << '\\n' ; std :: cout << j_object . is_primitive () << '\\n' ; std :: cout << j_array . is_primitive () << '\\n' ; std :: cout << j_string . is_primitive () << '\\n' ; std :: cout << j_binary . is_primitive () << '\\n' ; } Output: true true true true true false false true true See also \u00b6 is_structured() returns whether JSON value is structured is_null() returns whether JSON value is null is_string() returns whether JSON value is a string is_boolean() returns whether JSON value is a boolean is_number() returns whether JSON value is a number is_binary() returns whether JSON value is a binary array Version history \u00b6 Added in version 1.0.0. Extended to return true for binary types in version 3.8.0.","title":"is_primitive"},{"location":"api/basic_json/is_primitive/#nlohmannbasic_jsonis_primitive","text":"constexpr bool is_primitive () const noexcept ; This function returns true if and only if the JSON type is primitive (string, number, boolean, null , binary).","title":"nlohmann::basic_json::is_primitive"},{"location":"api/basic_json/is_primitive/#return-value","text":"true if type is primitive (string, number, boolean, null , or binary), false otherwise.","title":"Return value"},{"location":"api/basic_json/is_primitive/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_primitive/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_primitive/#possible-implementation","text":"constexpr bool is_primitive () const noexcept { return is_null () || is_string () || is_boolean () || is_number () || is_binary (); }","title":"Possible implementation"},{"location":"api/basic_json/is_primitive/#notes","text":"The term primitive stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.","title":"Notes"},{"location":"api/basic_json/is_primitive/#examples","text":"Example The following code exemplifies is_primitive() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_primitive() std :: cout << std :: boolalpha ; std :: cout << j_null . is_primitive () << '\\n' ; std :: cout << j_boolean . is_primitive () << '\\n' ; std :: cout << j_number_integer . is_primitive () << '\\n' ; std :: cout << j_number_unsigned_integer . is_primitive () << '\\n' ; std :: cout << j_number_float . is_primitive () << '\\n' ; std :: cout << j_object . is_primitive () << '\\n' ; std :: cout << j_array . is_primitive () << '\\n' ; std :: cout << j_string . is_primitive () << '\\n' ; std :: cout << j_binary . is_primitive () << '\\n' ; } Output: true true true true true false false true true","title":"Examples"},{"location":"api/basic_json/is_primitive/#see-also","text":"is_structured() returns whether JSON value is structured is_null() returns whether JSON value is null is_string() returns whether JSON value is a string is_boolean() returns whether JSON value is a boolean is_number() returns whether JSON value is a number is_binary() returns whether JSON value is a binary array","title":"See also"},{"location":"api/basic_json/is_primitive/#version-history","text":"Added in version 1.0.0. Extended to return true for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/is_string/","text":"nlohmann::basic_json:: is_string \u00b6 constexpr bool is_string () const noexcept ; This function returns true if and only if the JSON value is a string. Return value \u00b6 true if type is a string, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_string() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_string() std :: cout << std :: boolalpha ; std :: cout << j_null . is_string () << '\\n' ; std :: cout << j_boolean . is_string () << '\\n' ; std :: cout << j_number_integer . is_string () << '\\n' ; std :: cout << j_number_unsigned_integer . is_string () << '\\n' ; std :: cout << j_number_float . is_string () << '\\n' ; std :: cout << j_object . is_string () << '\\n' ; std :: cout << j_array . is_string () << '\\n' ; std :: cout << j_string . is_string () << '\\n' ; std :: cout << j_binary . is_string () << '\\n' ; } Output: false false false false false false false true false Version history \u00b6 Added in version 1.0.0.","title":"is_string"},{"location":"api/basic_json/is_string/#nlohmannbasic_jsonis_string","text":"constexpr bool is_string () const noexcept ; This function returns true if and only if the JSON value is a string.","title":"nlohmann::basic_json::is_string"},{"location":"api/basic_json/is_string/#return-value","text":"true if type is a string, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_string/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_string/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_string/#examples","text":"Example The following code exemplifies is_string() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_string() std :: cout << std :: boolalpha ; std :: cout << j_null . is_string () << '\\n' ; std :: cout << j_boolean . is_string () << '\\n' ; std :: cout << j_number_integer . is_string () << '\\n' ; std :: cout << j_number_unsigned_integer . is_string () << '\\n' ; std :: cout << j_number_float . is_string () << '\\n' ; std :: cout << j_object . is_string () << '\\n' ; std :: cout << j_array . is_string () << '\\n' ; std :: cout << j_string . is_string () << '\\n' ; std :: cout << j_binary . is_string () << '\\n' ; } Output: false false false false false false false true false","title":"Examples"},{"location":"api/basic_json/is_string/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_structured/","text":"nlohmann::basic_json:: is_structured \u00b6 constexpr bool is_structured () const noexcept ; This function returns true if and only if the JSON type is structured (array or object). Return value \u00b6 true if type is structured (array or object), false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Possible implementation \u00b6 constexpr bool is_primitive () const noexcept { return is_array () || is_object (); } Notes \u00b6 The term structured stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). Note that though strings are containers in C++, they are treated as primitive values in JSON. Examples \u00b6 Example The following code exemplifies is_structured() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_structured() std :: cout << std :: boolalpha ; std :: cout << j_null . is_structured () << '\\n' ; std :: cout << j_boolean . is_structured () << '\\n' ; std :: cout << j_number_integer . is_structured () << '\\n' ; std :: cout << j_number_unsigned_integer . is_structured () << '\\n' ; std :: cout << j_number_float . is_structured () << '\\n' ; std :: cout << j_object . is_structured () << '\\n' ; std :: cout << j_array . is_structured () << '\\n' ; std :: cout << j_string . is_structured () << '\\n' ; std :: cout << j_binary . is_structured () << '\\n' ; } Output: false false false false false true true false false See also \u00b6 is_primitive() returns whether JSON value is primitive is_array() returns whether value is an array is_object() returns whether value is an object Version history \u00b6 Added in version 1.0.0.","title":"is_structured"},{"location":"api/basic_json/is_structured/#nlohmannbasic_jsonis_structured","text":"constexpr bool is_structured () const noexcept ; This function returns true if and only if the JSON type is structured (array or object).","title":"nlohmann::basic_json::is_structured"},{"location":"api/basic_json/is_structured/#return-value","text":"true if type is structured (array or object), false otherwise.","title":"Return value"},{"location":"api/basic_json/is_structured/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_structured/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_structured/#possible-implementation","text":"constexpr bool is_primitive () const noexcept { return is_array () || is_object (); }","title":"Possible implementation"},{"location":"api/basic_json/is_structured/#notes","text":"The term structured stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). Note that though strings are containers in C++, they are treated as primitive values in JSON.","title":"Notes"},{"location":"api/basic_json/is_structured/#examples","text":"Example The following code exemplifies is_structured() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_structured() std :: cout << std :: boolalpha ; std :: cout << j_null . is_structured () << '\\n' ; std :: cout << j_boolean . is_structured () << '\\n' ; std :: cout << j_number_integer . is_structured () << '\\n' ; std :: cout << j_number_unsigned_integer . is_structured () << '\\n' ; std :: cout << j_number_float . is_structured () << '\\n' ; std :: cout << j_object . is_structured () << '\\n' ; std :: cout << j_array . is_structured () << '\\n' ; std :: cout << j_string . is_structured () << '\\n' ; std :: cout << j_binary . is_structured () << '\\n' ; } Output: false false false false false true true false false","title":"Examples"},{"location":"api/basic_json/is_structured/#see-also","text":"is_primitive() returns whether JSON value is primitive is_array() returns whether value is an array is_object() returns whether value is an object","title":"See also"},{"location":"api/basic_json/is_structured/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/items/","text":"nlohmann::basic_json:: items \u00b6 iteration_proxy < iterator > items () noexcept ; iteration_proxy < const_iterator > items () const noexcept ; 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 ) { std :: cout << \"key: \" << it . key () << \", value:\" << it . value () << '\\n' ; } Range-based for loop without items() function: for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\n' ; } Range-based for loop with items() function: for ( auto & el : j_object . items ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; } Return value \u00b6 iteration proxy object wrapping the current value with an interface to use in range-based for loops Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Constant. Notes \u00b6 When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string. Lifetime issues Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information. Examples \u00b6 Example The following code shows an example for items() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // example for an object for ( auto & x : j_object . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } // example for an array for ( auto & x : j_array . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } } Output: key : o ne , value : 1 key : t wo , value : 2 key : 0 , value : 1 key : 1 , value : 2 key : 2 , value : 4 key : 3 , value : 8 key : 4 , value : 16 Version history \u00b6 Added iterator_wrapper in version 3.0.0. 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.","title":"items"},{"location":"api/basic_json/items/#nlohmannbasic_jsonitems","text":"iteration_proxy < iterator > items () noexcept ; iteration_proxy < const_iterator > items () const noexcept ; 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 ) { std :: cout << \"key: \" << it . key () << \", value:\" << it . value () << '\\n' ; } Range-based for loop without items() function: for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\n' ; } Range-based for loop with items() function: for ( auto & el : j_object . items ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; }","title":"nlohmann::basic_json::items"},{"location":"api/basic_json/items/#return-value","text":"iteration proxy object wrapping the current value with an interface to use in range-based for loops","title":"Return value"},{"location":"api/basic_json/items/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/items/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/items/#notes","text":"When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string. Lifetime issues Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.","title":"Notes"},{"location":"api/basic_json/items/#examples","text":"Example The following code shows an example for items() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // example for an object for ( auto & x : j_object . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } // example for an array for ( auto & x : j_array . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } } Output: key : o ne , value : 1 key : t wo , value : 2 key : 0 , value : 1 key : 1 , value : 2 key : 2 , value : 4 key : 3 , value : 8 key : 4 , value : 16","title":"Examples"},{"location":"api/basic_json/items/#version-history","text":"Added iterator_wrapper in version 3.0.0. 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.","title":"Version history"},{"location":"api/basic_json/json_base_class_t/","text":"nlohmann::basic_json:: json_base_class_t \u00b6 using json_base_class_t = detail :: json_base_class < CustomBaseClass > ; 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. Template parameters \u00b6 CustomBaseClass the base class to be added to basic_json Notes \u00b6 Default type \u00b6 The default value for CustomBaseClass is void . In this case an empty base class is used and no additional functionality is injected. Limitations \u00b6 The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well. Examples \u00b6 Example The following code shows how to inject custom data and methods for each node. #include #include class visitor_adaptor_with_metadata { public : template < class Fnc > void visit ( const Fnc & fnc ) const ; int metadata = 42 ; private : template < class Ptr , class Fnc > void do_visit ( const Ptr & ptr , const Fnc & fnc ) const ; }; using json = nlohmann :: basic_json < std :: map , std :: vector , std :: string , bool , std :: int64_t , std :: uint64_t , double , std :: allocator , nlohmann :: adl_serializer , std :: vector < std :: uint8_t > , visitor_adaptor_with_metadata > ; template < class Fnc > void visitor_adaptor_with_metadata :: visit ( const Fnc & fnc ) const { do_visit ( json :: json_pointer {}, fnc ); } template < class Ptr , class Fnc > void visitor_adaptor_with_metadata :: do_visit ( const Ptr & ptr , const Fnc & fnc ) const { using value_t = nlohmann :: detail :: value_t ; const json & j = * static_cast < const json *> ( this ); switch ( j . type ()) { case value_t :: object : fnc ( ptr , j ); for ( const auto & entry : j . items ()) { entry . value (). do_visit ( ptr / entry . key (), fnc ); } break ; case value_t :: array : fnc ( ptr , j ); for ( std :: size_t i = 0 ; i < j . size (); ++ i ) { j . at ( i ). do_visit ( ptr / std :: to_string ( i ), fnc ); } break ; case value_t :: null : case value_t :: string : case value_t :: boolean : case value_t :: number_integer : case value_t :: number_unsigned : case value_t :: number_float : case value_t :: binary : fnc ( ptr , j ); break ; case value_t :: discarded : default : break ; } } int main () { // create a json object json j ; j [ \"null\" ]; j [ \"object\" ][ \"uint\" ] = 1U ; j [ \"object\" ]. metadata = 21 ; // visit and output j . visit ( [ & ]( const json :: json_pointer & p , const json & j ) { std :: cout << ( p . empty () ? std :: string { \"/\" } : p . to_string ()) << \" - metadata = \" << j . metadata << \" -> \" << j . dump () << '\\n' ; }); } Output: / - me ta da ta = 42 - > { \"null\" : null , \"object\" :{ \"uint\" : 1 }} / null - me ta da ta = 42 - > null /objec t - me ta da ta = 21 - > { \"uint\" : 1 } /objec t /ui nt - me ta da ta = 42 - > 1 Version history \u00b6 Added in version 3.12.0.","title":"json_base_class_t"},{"location":"api/basic_json/json_base_class_t/#nlohmannbasic_jsonjson_base_class_t","text":"using json_base_class_t = detail :: json_base_class < CustomBaseClass > ; 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.","title":"nlohmann::basic_json::json_base_class_t"},{"location":"api/basic_json/json_base_class_t/#template-parameters","text":"CustomBaseClass the base class to be added to basic_json","title":"Template parameters"},{"location":"api/basic_json/json_base_class_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/json_base_class_t/#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.","title":"Default type"},{"location":"api/basic_json/json_base_class_t/#limitations","text":"The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.","title":"Limitations"},{"location":"api/basic_json/json_base_class_t/#examples","text":"Example The following code shows how to inject custom data and methods for each node. #include #include class visitor_adaptor_with_metadata { public : template < class Fnc > void visit ( const Fnc & fnc ) const ; int metadata = 42 ; private : template < class Ptr , class Fnc > void do_visit ( const Ptr & ptr , const Fnc & fnc ) const ; }; using json = nlohmann :: basic_json < std :: map , std :: vector , std :: string , bool , std :: int64_t , std :: uint64_t , double , std :: allocator , nlohmann :: adl_serializer , std :: vector < std :: uint8_t > , visitor_adaptor_with_metadata > ; template < class Fnc > void visitor_adaptor_with_metadata :: visit ( const Fnc & fnc ) const { do_visit ( json :: json_pointer {}, fnc ); } template < class Ptr , class Fnc > void visitor_adaptor_with_metadata :: do_visit ( const Ptr & ptr , const Fnc & fnc ) const { using value_t = nlohmann :: detail :: value_t ; const json & j = * static_cast < const json *> ( this ); switch ( j . type ()) { case value_t :: object : fnc ( ptr , j ); for ( const auto & entry : j . items ()) { entry . value (). do_visit ( ptr / entry . key (), fnc ); } break ; case value_t :: array : fnc ( ptr , j ); for ( std :: size_t i = 0 ; i < j . size (); ++ i ) { j . at ( i ). do_visit ( ptr / std :: to_string ( i ), fnc ); } break ; case value_t :: null : case value_t :: string : case value_t :: boolean : case value_t :: number_integer : case value_t :: number_unsigned : case value_t :: number_float : case value_t :: binary : fnc ( ptr , j ); break ; case value_t :: discarded : default : break ; } } int main () { // create a json object json j ; j [ \"null\" ]; j [ \"object\" ][ \"uint\" ] = 1U ; j [ \"object\" ]. metadata = 21 ; // visit and output j . visit ( [ & ]( const json :: json_pointer & p , const json & j ) { std :: cout << ( p . empty () ? std :: string { \"/\" } : p . to_string ()) << \" - metadata = \" << j . metadata << \" -> \" << j . dump () << '\\n' ; }); } Output: / - me ta da ta = 42 - > { \"null\" : null , \"object\" :{ \"uint\" : 1 }} / null - me ta da ta = 42 - > null /objec t - me ta da ta = 21 - > { \"uint\" : 1 } /objec t /ui nt - me ta da ta = 42 - > 1","title":"Examples"},{"location":"api/basic_json/json_base_class_t/#version-history","text":"Added in version 3.12.0.","title":"Version history"},{"location":"api/basic_json/json_serializer/","text":"nlohmann::basic_json:: json_serializer \u00b6 template < typename T , typename SFINAE > using json_serializer = JSONSerializer < T , SFINAE > ; Template parameters \u00b6 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 Notes \u00b6 Default type \u00b6 The default values for json_serializer is adl_serializer . Examples \u00b6 Example The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer . #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace Version history \u00b6 Since version 2.0.0.","title":"json_serializer"},{"location":"api/basic_json/json_serializer/#nlohmannbasic_jsonjson_serializer","text":"template < typename T , typename SFINAE > using json_serializer = JSONSerializer < T , SFINAE > ;","title":"nlohmann::basic_json::json_serializer"},{"location":"api/basic_json/json_serializer/#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","title":"Template parameters"},{"location":"api/basic_json/json_serializer/#notes","text":"","title":"Notes"},{"location":"api/basic_json/json_serializer/#default-type","text":"The default values for json_serializer is adl_serializer .","title":"Default type"},{"location":"api/basic_json/json_serializer/#examples","text":"Example The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer . #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace","title":"Examples"},{"location":"api/basic_json/json_serializer/#version-history","text":"Since version 2.0.0.","title":"Version history"},{"location":"api/basic_json/max_size/","text":"nlohmann::basic_json:: max_size \u00b6 size_type max_size () const noexcept ; 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. Return value \u00b6 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() Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity. Notes \u00b6 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 . Examples \u00b6 Example The following code calls max_size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call max_size() std :: cout << j_null . max_size () << '\\n' ; std :: cout << j_boolean . max_size () << '\\n' ; std :: cout << j_number_integer . max_size () << '\\n' ; std :: cout << j_number_float . max_size () << '\\n' ; std :: cout << j_object . max_size () << '\\n' ; std :: cout << j_array . max_size () << '\\n' ; std :: cout << j_string . max_size () << '\\n' ; } Output: 0 1 1 1 115292150460684697 576460752303423487 1 Note the output is platform-dependent. Version history \u00b6 Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"max_size"},{"location":"api/basic_json/max_size/#nlohmannbasic_jsonmax_size","text":"size_type max_size () const noexcept ; 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.","title":"nlohmann::basic_json::max_size"},{"location":"api/basic_json/max_size/#return-value","text":"The return value depends on the different types and is defined as follows: Value type return value null 0 (same as size() ) boolean 1 (same as size() ) string 1 (same as size() ) number 1 (same as size() ) binary 1 (same as size() ) object result of function object_t::max_size() array result of function array_t::max_size()","title":"Return value"},{"location":"api/basic_json/max_size/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/max_size/#complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.","title":"Complexity"},{"location":"api/basic_json/max_size/#notes","text":"This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of string elements the JSON value can store which is 1 .","title":"Notes"},{"location":"api/basic_json/max_size/#examples","text":"Example The following code calls max_size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call max_size() std :: cout << j_null . max_size () << '\\n' ; std :: cout << j_boolean . max_size () << '\\n' ; std :: cout << j_number_integer . max_size () << '\\n' ; std :: cout << j_number_float . max_size () << '\\n' ; std :: cout << j_object . max_size () << '\\n' ; std :: cout << j_array . max_size () << '\\n' ; std :: cout << j_string . max_size () << '\\n' ; } Output: 0 1 1 1 115292150460684697 576460752303423487 1 Note the output is platform-dependent.","title":"Examples"},{"location":"api/basic_json/max_size/#version-history","text":"Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/merge_patch/","text":"nlohmann::basic_json:: merge_patch \u00b6 void merge_patch ( const basic_json & apply_patch ); 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 ): if Patch is an Object : if Target is not an Object : Target = {} // Ignore the contents and set it to an empty Object for each Name / Value pair in Patch : if Value is null : if Name exists in Target : remove the Name / Value pair from Target else : Target [ Name ] = MergePatch ( Target [ Name ], Value ) return Target else : return Patch Thereby, Target is the current object; that is, the patch is applied to the current value. Parameters \u00b6 apply_patch (in) the patch to apply Complexity \u00b6 Linear in the lengths of apply_patch . Examples \u00b6 Example The following code shows how a JSON Merge Patch is applied to a JSON document. #include #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" } See also \u00b6 RFC 7396 (JSON Merge Patch) patch apply a JSON patch Version history \u00b6 Added in version 3.0.0.","title":"merge_patch"},{"location":"api/basic_json/merge_patch/#nlohmannbasic_jsonmerge_patch","text":"void merge_patch ( const basic_json & apply_patch ); 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 ): if Patch is an Object : if Target is not an Object : Target = {} // Ignore the contents and set it to an empty Object for each Name / Value pair in Patch : if Value is null : if Name exists in Target : remove the Name / Value pair from Target else : Target [ Name ] = MergePatch ( Target [ Name ], Value ) return Target else : return Patch Thereby, Target is the current object; that is, the patch is applied to the current value.","title":"nlohmann::basic_json::merge_patch"},{"location":"api/basic_json/merge_patch/#parameters","text":"apply_patch (in) the patch to apply","title":"Parameters"},{"location":"api/basic_json/merge_patch/#complexity","text":"Linear in the lengths of apply_patch .","title":"Complexity"},{"location":"api/basic_json/merge_patch/#examples","text":"Example The following code shows how a JSON Merge Patch is applied to a JSON document. #include #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" }","title":"Examples"},{"location":"api/basic_json/merge_patch/#see-also","text":"RFC 7396 (JSON Merge Patch) patch apply a JSON patch","title":"See also"},{"location":"api/basic_json/merge_patch/#version-history","text":"Added in version 3.0.0.","title":"Version history"},{"location":"api/basic_json/meta/","text":"nlohmann::basic_json:: meta \u00b6 static basic_json meta (); This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. Return value \u00b6 JSON object holding version information key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang , icc , gcc , ilecpp , msvc , pgcpp , sunpro , and unknown ), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32 , linux , apple , unix , and unknown . url The URL of the project as string. version The version of the library. It is an object with the following keys: major , minor , and patch as defined by Semantic Versioning , and string (the version string). Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example output of the meta() function. #include #include #include using json = nlohmann :: json ; int main () { // call meta() std :: cout << std :: setw ( 4 ) << json :: meta () << '\\n' ; } Output: { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } } Note the output is platform-dependent. See also \u00b6 NLOHMANN_JSON_VERSION_MAJOR / NLOHMANN_JSON_VERSION_MINOR / NLOHMANN_JSON_VERSION_PATCH - library version information Version history \u00b6 Added in version 2.1.0.","title":"meta"},{"location":"api/basic_json/meta/#nlohmannbasic_jsonmeta","text":"static basic_json meta (); This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.","title":"nlohmann::basic_json::meta"},{"location":"api/basic_json/meta/#return-value","text":"JSON object holding version information key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang , icc , gcc , ilecpp , msvc , pgcpp , sunpro , and unknown ), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32 , linux , apple , unix , and unknown . url The URL of the project as string. version The version of the library. It is an object with the following keys: major , minor , and patch as defined by Semantic Versioning , and string (the version string).","title":"Return value"},{"location":"api/basic_json/meta/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/meta/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/meta/#examples","text":"Example The following code shows an example output of the meta() function. #include #include #include using json = nlohmann :: json ; int main () { // call meta() std :: cout << std :: setw ( 4 ) << json :: meta () << '\\n' ; } Output: { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } } Note the output is platform-dependent.","title":"Examples"},{"location":"api/basic_json/meta/#see-also","text":"NLOHMANN_JSON_VERSION_MAJOR / NLOHMANN_JSON_VERSION_MINOR / NLOHMANN_JSON_VERSION_PATCH - library version information","title":"See also"},{"location":"api/basic_json/meta/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/basic_json/number_float_t/","text":"nlohmann::basic_json:: number_float_t \u00b6 using number_float_t = NumberFloatType ; 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. Notes \u00b6 Default type \u00b6 With the default values for NumberFloatType ( double ), the default value for number_float_t is double . Default behavior \u00b6 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 . Limits \u00b6 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 . Storage \u00b6 Floating-point number values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that number_float_t is by default, a typedef to double . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < double , json :: number_float_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"number_float_t"},{"location":"api/basic_json/number_float_t/#nlohmannbasic_jsonnumber_float_t","text":"using number_float_t = NumberFloatType ; 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.","title":"nlohmann::basic_json::number_float_t"},{"location":"api/basic_json/number_float_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/number_float_t/#default-type","text":"With the default values for NumberFloatType ( double ), the default value for number_float_t is double .","title":"Default type"},{"location":"api/basic_json/number_float_t/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"api/basic_json/number_float_t/#limits","text":"RFC 8259 states: This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null .","title":"Limits"},{"location":"api/basic_json/number_float_t/#storage","text":"Floating-point number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/number_float_t/#examples","text":"Example The following code shows that number_float_t is by default, a typedef to double . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < double , json :: number_float_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/number_float_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/number_integer_t/","text":"nlohmann::basic_json:: number_integer_t \u00b6 using number_integer_t = NumberIntegerType ; The type used to store JSON numbers (integers). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use. Notes \u00b6 Default type \u00b6 With the default values for NumberIntegerType ( std::int64_t ), the default value for number_integer_t is std :: int64_t . Default behavior \u00b6 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 . Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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. Storage \u00b6 Integer number values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that number_integer_t is by default, a typedef to std :: int64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: int64_t , json :: number_integer_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"number_integer_t"},{"location":"api/basic_json/number_integer_t/#nlohmannbasic_jsonnumber_integer_t","text":"using number_integer_t = NumberIntegerType ; The type used to store JSON numbers (integers). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.","title":"nlohmann::basic_json::number_integer_t"},{"location":"api/basic_json/number_integer_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/number_integer_t/#default-type","text":"With the default values for NumberIntegerType ( std::int64_t ), the default value for number_integer_t is std :: int64_t .","title":"Default type"},{"location":"api/basic_json/number_integer_t/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"api/basic_json/number_integer_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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.","title":"Limits"},{"location":"api/basic_json/number_integer_t/#storage","text":"Integer number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/number_integer_t/#examples","text":"Example The following code shows that number_integer_t is by default, a typedef to std :: int64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: int64_t , json :: number_integer_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/number_integer_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/number_unsigned_t/","text":"nlohmann::basic_json:: number_unsigned_t \u00b6 using number_unsigned_t = NumberUnsignedType ; The type used to store JSON numbers (unsigned). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use. Notes \u00b6 Default type \u00b6 With the default values for NumberUnsignedType ( std::uint64_t ), the default value for number_unsigned_t is std :: uint64_t . Default behavior \u00b6 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 . Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range \\f [-2^{53}+1, 2^{53}-1]\\f [-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. Storage \u00b6 Integer number values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that number_unsigned_t is by default, a typedef to std :: uint64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: uint64_t , json :: number_unsigned_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 2.0.0.","title":"number_unsigned_t"},{"location":"api/basic_json/number_unsigned_t/#nlohmannbasic_jsonnumber_unsigned_t","text":"using number_unsigned_t = NumberUnsignedType ; The type used to store JSON numbers (unsigned). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.","title":"nlohmann::basic_json::number_unsigned_t"},{"location":"api/basic_json/number_unsigned_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/number_unsigned_t/#default-type","text":"With the default values for NumberUnsignedType ( std::uint64_t ), the default value for number_unsigned_t is std :: uint64_t .","title":"Default type"},{"location":"api/basic_json/number_unsigned_t/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"api/basic_json/number_unsigned_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range \\f [-2^{53}+1, 2^{53}-1]\\f [-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.","title":"Limits"},{"location":"api/basic_json/number_unsigned_t/#storage","text":"Integer number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/number_unsigned_t/#examples","text":"Example The following code shows that number_unsigned_t is by default, a typedef to std :: uint64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: uint64_t , json :: number_unsigned_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/number_unsigned_t/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/object/","text":"nlohmann::basic_json:: object \u00b6 static basic_json object ( initializer_list_t init = {}); 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. Parameters \u00b6 init (in) initializer list with JSON values to create an object from (optional) Return value \u00b6 JSON object value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 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. Complexity \u00b6 Linear in the size of init . Notes \u00b6 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) . Examples \u00b6 Example The following code shows an example for the object function. #include #include using json = nlohmann :: json ; int main () { // create JSON objects json j_no_init_list = json :: object (); json j_empty_init_list = json :: object ({}); json j_list_of_pairs = json :: object ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON objects std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; // example for an exception try { // can only create an object from a list of pairs json j_invalid_object = json :: object ({{ \"one\" , 1 , 2 }}); } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: {} {} { \"one\" : 1 , \"two\" : 2 } [ jso n .excep t io n . t ype_error. 301 ] ca nn o t crea te objec t fr om i n i t ializer lis t See also \u00b6 basic_json(initializer_list_t) - create a JSON value from an initializer list array - create a JSON array value from an initializer list Version history \u00b6 Added in version 1.0.0.","title":"object"},{"location":"api/basic_json/object/#nlohmannbasic_jsonobject","text":"static basic_json object ( initializer_list_t init = {}); 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.","title":"nlohmann::basic_json::object"},{"location":"api/basic_json/object/#parameters","text":"init (in) initializer list with JSON values to create an object from (optional)","title":"Parameters"},{"location":"api/basic_json/object/#return-value","text":"JSON object value","title":"Return value"},{"location":"api/basic_json/object/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/object/#exceptions","text":"Throws type_error.301 if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to basic_json(initializer_list_t, bool, value_t) , an array would have been created from the passed initializer list init . See example below.","title":"Exceptions"},{"location":"api/basic_json/object/#complexity","text":"Linear in the size of init .","title":"Complexity"},{"location":"api/basic_json/object/#notes","text":"This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t) , there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t) .","title":"Notes"},{"location":"api/basic_json/object/#examples","text":"Example The following code shows an example for the object function. #include #include using json = nlohmann :: json ; int main () { // create JSON objects json j_no_init_list = json :: object (); json j_empty_init_list = json :: object ({}); json j_list_of_pairs = json :: object ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON objects std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; // example for an exception try { // can only create an object from a list of pairs json j_invalid_object = json :: object ({{ \"one\" , 1 , 2 }}); } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: {} {} { \"one\" : 1 , \"two\" : 2 } [ jso n .excep t io n . t ype_error. 301 ] ca nn o t crea te objec t fr om i n i t ializer lis t","title":"Examples"},{"location":"api/basic_json/object/#see-also","text":"basic_json(initializer_list_t) - create a JSON value from an initializer list array - create a JSON array value from an initializer list","title":"See also"},{"location":"api/basic_json/object/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/object_comparator_t/","text":"nlohmann::basic_json:: object_comparator_t \u00b6 using object_comparator_t = typename object_t :: key_compare ; // or using object_comparator_t = default_object_comparator_t ; The comparator used by object_t . Defined as typename object_t :: key_compare if available, and default_object_comparator_t otherwise. Examples \u00b6 Example The example below demonstrates the used object comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"json::object_comparator_t( \\\" one \\\" , \\\" two \\\" ) = \" << json :: object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"json::object_comparator_t( \\\" three \\\" , \\\" four \\\" ) = \" << json :: object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: jso n :: objec t _compara t or_ t ( \"one\" , \"two\" ) = true jso n :: objec t _compara t or_ t ( \"three\" , \"four\" ) = false Version history \u00b6 Added in version 3.0.0. Changed to be conditionally defined as typename object_t :: key_compare or default_object_comparator_t in version 3.11.0.","title":"object_comparator_t"},{"location":"api/basic_json/object_comparator_t/#nlohmannbasic_jsonobject_comparator_t","text":"using object_comparator_t = typename object_t :: key_compare ; // or using object_comparator_t = default_object_comparator_t ; The comparator used by object_t . Defined as typename object_t :: key_compare if available, and default_object_comparator_t otherwise.","title":"nlohmann::basic_json::object_comparator_t"},{"location":"api/basic_json/object_comparator_t/#examples","text":"Example The example below demonstrates the used object comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"json::object_comparator_t( \\\" one \\\" , \\\" two \\\" ) = \" << json :: object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"json::object_comparator_t( \\\" three \\\" , \\\" four \\\" ) = \" << json :: object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: jso n :: objec t _compara t or_ t ( \"one\" , \"two\" ) = true jso n :: objec t _compara t or_ t ( \"three\" , \"four\" ) = false","title":"Examples"},{"location":"api/basic_json/object_comparator_t/#version-history","text":"Added in version 3.0.0. Changed to be conditionally defined as typename object_t :: key_compare or default_object_comparator_t in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/object_t/","text":"nlohmann::basic_json:: object_t \u00b6 using object_t = ObjectType < StringType , basic_json , default_object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; 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. Template parameters \u00b6 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 is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator ) Notes \u00b6 Default type \u00b6 With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: // until C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less < std :: string > , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > // since C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > See default_object_comparator_t for more information. Behavior \u00b6 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. Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object. Storage \u00b6 Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced. Object key order \u00b6 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. Examples \u00b6 Example The following code shows that object_t is by default, a typedef to std :: map < json :: string_t , json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: map < json :: string_t , json > , json :: object_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"object_t"},{"location":"api/basic_json/object_t/#nlohmannbasic_jsonobject_t","text":"using object_t = ObjectType < StringType , basic_json , default_object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; 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.","title":"nlohmann::basic_json::object_t"},{"location":"api/basic_json/object_t/#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 is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator )","title":"Template parameters"},{"location":"api/basic_json/object_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/object_t/#default-type","text":"With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: // until C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less < std :: string > , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > // since C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > See default_object_comparator_t for more information.","title":"Default type"},{"location":"api/basic_json/object_t/#behavior","text":"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.","title":"Behavior"},{"location":"api/basic_json/object_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.","title":"Limits"},{"location":"api/basic_json/object_t/#storage","text":"Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.","title":"Storage"},{"location":"api/basic_json/object_t/#object-key-order","text":"The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259 , because any order implements the specified \"unordered\" nature of JSON objects.","title":"Object key order"},{"location":"api/basic_json/object_t/#examples","text":"Example The following code shows that object_t is by default, a typedef to std :: map < json :: string_t , json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: map < json :: string_t , json > , json :: object_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/object_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/operator%2B%3D/","text":"nlohmann::basic_json:: operator+= \u00b6 // (1) reference operator += ( basic_json && val ); reference operator += ( const basic_json & val ); // (2) reference operator += ( const typename object_t :: value_type & val ); // (3) reference operator += ( initializer_list_t init ); 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&&) . Parameters \u00b6 val (in) the value to add to the JSON array/object init (in) an initializer list Return value \u00b6 * this Exceptions \u00b6 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\" Complexity \u00b6 Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init . Notes \u00b6 (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 , see #235 for more information. Examples \u00b6 Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]] Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"operator+="},{"location":"api/basic_json/operator%2B%3D/#nlohmannbasic_jsonoperator","text":"// (1) reference operator += ( basic_json && val ); reference operator += ( const basic_json & val ); // (2) reference operator += ( const typename object_t :: value_type & val ); // (3) reference operator += ( initializer_list_t init ); 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&&) .","title":"nlohmann::basic_json::operator+="},{"location":"api/basic_json/operator%2B%3D/#parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list","title":"Parameters"},{"location":"api/basic_json/operator%2B%3D/#return-value","text":"* this","title":"Return value"},{"location":"api/basic_json/operator%2B%3D/#exceptions","text":"All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use operator+=() with number\"","title":"Exceptions"},{"location":"api/basic_json/operator%2B%3D/#complexity","text":"Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init .","title":"Complexity"},{"location":"api/basic_json/operator%2B%3D/#notes","text":"(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list , see #235 for more information.","title":"Notes"},{"location":"api/basic_json/operator%2B%3D/#examples","text":"Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]]","title":"Examples"},{"location":"api/basic_json/operator%2B%3D/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"Version history"},{"location":"api/basic_json/operator%3D/","text":"nlohmann::basic_json:: operator= \u00b6 basic_json & operator = ( basic_json other ) noexcept ( std :: is_nothrow_move_constructible < value_t >:: value && std :: is_nothrow_move_assignable < value_t >:: value && std :: is_nothrow_move_constructible < json_value >:: value && std :: is_nothrow_move_assignable < json_value >:: value ); 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. Parameters \u00b6 other (in) value to copy from Complexity \u00b6 Linear. Examples \u00b6 Example The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b . Finally, the copy of a (which is the null value after the swap) is destroyed. #include #include using json = nlohmann :: json ; int main () { // create JSON values json a = 23 ; json b = 42 ; // copy-assign a to b b = a ; // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: 23 23 Version history \u00b6 Added in version 1.0.0.","title":"operator="},{"location":"api/basic_json/operator%3D/#nlohmannbasic_jsonoperator","text":"basic_json & operator = ( basic_json other ) noexcept ( std :: is_nothrow_move_constructible < value_t >:: value && std :: is_nothrow_move_assignable < value_t >:: value && std :: is_nothrow_move_constructible < json_value >:: value && std :: is_nothrow_move_assignable < json_value >:: value ); 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.","title":"nlohmann::basic_json::operator="},{"location":"api/basic_json/operator%3D/#parameters","text":"other (in) value to copy from","title":"Parameters"},{"location":"api/basic_json/operator%3D/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator%3D/#examples","text":"Example The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b . Finally, the copy of a (which is the null value after the swap) is destroyed. #include #include using json = nlohmann :: json ; int main () { // create JSON values json a = 23 ; json b = 42 ; // copy-assign a to b b = a ; // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: 23 23","title":"Examples"},{"location":"api/basic_json/operator%3D/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/operator%5B%5D/","text":"nlohmann::basic_json:: operator[] \u00b6 // (1) reference operator []( size_type idx ); const_reference operator []( size_type idx ) const ; // (2) reference operator []( typename object_t :: key_type key ); const_reference operator []( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference operator []( KeyType && key ); template < typename KeyType > const_reference operator []( KeyType && key ) const ; // (4) reference operator []( const json_pointer & ptr ); const_reference operator []( const json_pointer & ptr ) const ; 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 . Template parameters \u00b6 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). Parameters \u00b6 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 Return value \u00b6 (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 Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense. The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense. 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'. Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version. Throws out_of_range.404 if the JSON pointer ptr can not be resolved. Complexity \u00b6 Constant if idx is in the range of the array. Otherwise, linear in idx - size() . Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container. Notes \u00b6 Undefined behavior and runtime assertions 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. Examples \u00b6 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 #include using json = nlohmann :: json ; int main () { // create a JSON array json array = { 1 , 2 , 3 , 4 , 5 }; // output element at index 3 (fourth element) std :: cout << array [ 3 ] << '\\n' ; // change last element to 6 array [ array . size () - 1 ] = 6 ; // output changed array std :: cout << array << '\\n' ; // write beyond array limit array [ 10 ] = 11 ; // output changed array std :: cout << array << '\\n' ; } Output: 4 [ 1 , 2 , 3 , 4 , 6 ] [ 1 , 2 , 3 , 4 , 6 , null , null , null , null , null , 11 ] Example: (1) access specified array element (const) The example below shows how array elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; } Output: \"third\" Example: (2) access specified object element The example below shows how object elements can be read and written using the [] operator. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" ]; // write to nonexisting key object [ \"five\" ][ \"really\" ][ \"nested\" ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (2) access specified object element (const) The example below shows how object elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << '\\n' ; } Output: 2 Example: (3) access specified object element using string_view The example below shows how object elements can be read using the [] operator. #include #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" sv ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" sv ]; // write to nonexisting key object [ \"five\" sv ][ \"really\" sv ][ \"nested\" sv ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (3) access specified object element using string_view (const) The example below shows how object elements can be read using the [] operator. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << '\\n' ; } Output: 2 Example: (4) access specified element via JSON Pointer The example below shows how values can be read and written using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; // writing access // change the string j [ \"/string\" _json_pointer ] = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // \"change\" a nonexisting object entry j [ \"/boolean\" _json_pointer ] = true ; // output the changed object std :: cout << j << '\\n' ; // change an array element j [ \"/array/1\" _json_pointer ] = 21 ; // \"change\" an array element with nonexisting index j [ \"/array/4\" _json_pointer ] = 44 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // \"change\" the array element past the end j [ \"/array/-\" _json_pointer ] = 55 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" { \"array\" :[ 1 , 2 ], \"boolean\" : true , \"number\" : 1 , \"string\" : \"bar\" } [ 1 , 21 , null , null , 44 ] [ 1 , 21 , null , null , 44 , 55 ] Example: (4) access specified element via JSON Pointer (const) The example below shows how values can be read using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2 See also \u00b6 documentation on unchecked access documentation on runtime assertions see at for access by reference with range checking see value for access with default value Version history \u00b6 Added in version 1.0.0. Added in version 1.0.0. Added overloads for T* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0. Added in version 3.11.0. Added in version 2.0.0.","title":"operator[]"},{"location":"api/basic_json/operator%5B%5D/#nlohmannbasic_jsonoperator","text":"// (1) reference operator []( size_type idx ); const_reference operator []( size_type idx ) const ; // (2) reference operator []( typename object_t :: key_type key ); const_reference operator []( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference operator []( KeyType && key ); template < typename KeyType > const_reference operator []( KeyType && key ) const ; // (4) reference operator []( const json_pointer & ptr ); const_reference operator []( const json_pointer & ptr ) const ; 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 .","title":"nlohmann::basic_json::operator[]"},{"location":"api/basic_json/operator%5B%5D/#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).","title":"Template parameters"},{"location":"api/basic_json/operator%5B%5D/#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","title":"Parameters"},{"location":"api/basic_json/operator%5B%5D/#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","title":"Return value"},{"location":"api/basic_json/operator%5B%5D/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/operator%5B%5D/#exceptions","text":"The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense. The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense. 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'. Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version. Throws out_of_range.404 if the JSON pointer ptr can not be resolved.","title":"Exceptions"},{"location":"api/basic_json/operator%5B%5D/#complexity","text":"Constant if idx is in the range of the array. Otherwise, linear in idx - size() . Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container.","title":"Complexity"},{"location":"api/basic_json/operator%5B%5D/#notes","text":"Undefined behavior and runtime assertions 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.","title":"Notes"},{"location":"api/basic_json/operator%5B%5D/#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 #include using json = nlohmann :: json ; int main () { // create a JSON array json array = { 1 , 2 , 3 , 4 , 5 }; // output element at index 3 (fourth element) std :: cout << array [ 3 ] << '\\n' ; // change last element to 6 array [ array . size () - 1 ] = 6 ; // output changed array std :: cout << array << '\\n' ; // write beyond array limit array [ 10 ] = 11 ; // output changed array std :: cout << array << '\\n' ; } Output: 4 [ 1 , 2 , 3 , 4 , 6 ] [ 1 , 2 , 3 , 4 , 6 , null , null , null , null , null , 11 ] Example: (1) access specified array element (const) The example below shows how array elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; } Output: \"third\" Example: (2) access specified object element The example below shows how object elements can be read and written using the [] operator. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" ]; // write to nonexisting key object [ \"five\" ][ \"really\" ][ \"nested\" ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (2) access specified object element (const) The example below shows how object elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << '\\n' ; } Output: 2 Example: (3) access specified object element using string_view The example below shows how object elements can be read using the [] operator. #include #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" sv ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" sv ]; // write to nonexisting key object [ \"five\" sv ][ \"really\" sv ][ \"nested\" sv ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (3) access specified object element using string_view (const) The example below shows how object elements can be read using the [] operator. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << '\\n' ; } Output: 2 Example: (4) access specified element via JSON Pointer The example below shows how values can be read and written using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; // writing access // change the string j [ \"/string\" _json_pointer ] = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // \"change\" a nonexisting object entry j [ \"/boolean\" _json_pointer ] = true ; // output the changed object std :: cout << j << '\\n' ; // change an array element j [ \"/array/1\" _json_pointer ] = 21 ; // \"change\" an array element with nonexisting index j [ \"/array/4\" _json_pointer ] = 44 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // \"change\" the array element past the end j [ \"/array/-\" _json_pointer ] = 55 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" { \"array\" :[ 1 , 2 ], \"boolean\" : true , \"number\" : 1 , \"string\" : \"bar\" } [ 1 , 21 , null , null , 44 ] [ 1 , 21 , null , null , 44 , 55 ] Example: (4) access specified element via JSON Pointer (const) The example below shows how values can be read using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2","title":"Examples"},{"location":"api/basic_json/operator%5B%5D/#see-also","text":"documentation on unchecked access documentation on runtime assertions see at for access by reference with range checking see value for access with default value","title":"See also"},{"location":"api/basic_json/operator%5B%5D/#version-history","text":"Added in version 1.0.0. Added in version 1.0.0. Added overloads for T* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0. Added in version 3.11.0. Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/operator_ValueType/","text":"nlohmann::basic_json:: operator ValueType \u00b6 template < typename ValueType > JSON_EXPLICIT operator ValueType () const ; 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 . Template parameters \u00b6 ValueType the value type to return Return value \u00b6 copy of the JSON value, converted to ValueType Exceptions \u00b6 Depends on what json_serializer from_json() method throws Complexity \u00b6 Linear in the size of the JSON value. Notes \u00b6 Definition of JSON_EXPLICIT By default JSON_EXPLICIT is defined to the empty string, so the signature is: template < typename ValueType > operator ValueType () const ; If JSON_USE_IMPLICIT_CONVERSIONS is set to 0 , JSON_EXPLICIT is defined to explicit : template < typename ValueType > explicit operator ValueType () const ; 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 . Examples \u00b6 Example The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use implicit conversions bool v1 = json_types [ \"boolean\" ]; int v2 = json_types [ \"number\" ][ \"integer\" ]; short v3 = json_types [ \"number\" ][ \"integer\" ]; float v4 = json_types [ \"number\" ][ \"floating-point\" ]; int v5 = json_types [ \"number\" ][ \"floating-point\" ]; std :: string v6 = json_types [ \"string\" ]; std :: vector < short > v7 = json_types [ \"array\" ]; std :: unordered_map < std :: string , json > v8 = json_types ; // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } // example for an exception try { bool v1 = json_types [ \"string\" ]; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] [ jso n .excep t io n . t ype_error. 302 ] t ype mus t be boolea n , bu t is s tr i n g Version history \u00b6 Since version 1.0.0. Macros JSON_EXPLICIT / JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.","title":"operator ValueType"},{"location":"api/basic_json/operator_ValueType/#nlohmannbasic_jsonoperator-valuetype","text":"template < typename ValueType > JSON_EXPLICIT operator ValueType () const ; 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 .","title":"nlohmann::basic_json::operator ValueType"},{"location":"api/basic_json/operator_ValueType/#template-parameters","text":"ValueType the value type to return","title":"Template parameters"},{"location":"api/basic_json/operator_ValueType/#return-value","text":"copy of the JSON value, converted to ValueType","title":"Return value"},{"location":"api/basic_json/operator_ValueType/#exceptions","text":"Depends on what json_serializer from_json() method throws","title":"Exceptions"},{"location":"api/basic_json/operator_ValueType/#complexity","text":"Linear in the size of the JSON value.","title":"Complexity"},{"location":"api/basic_json/operator_ValueType/#notes","text":"Definition of JSON_EXPLICIT By default JSON_EXPLICIT is defined to the empty string, so the signature is: template < typename ValueType > operator ValueType () const ; If JSON_USE_IMPLICIT_CONVERSIONS is set to 0 , JSON_EXPLICIT is defined to explicit : template < typename ValueType > explicit operator ValueType () const ; 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 .","title":"Notes"},{"location":"api/basic_json/operator_ValueType/#examples","text":"Example The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use implicit conversions bool v1 = json_types [ \"boolean\" ]; int v2 = json_types [ \"number\" ][ \"integer\" ]; short v3 = json_types [ \"number\" ][ \"integer\" ]; float v4 = json_types [ \"number\" ][ \"floating-point\" ]; int v5 = json_types [ \"number\" ][ \"floating-point\" ]; std :: string v6 = json_types [ \"string\" ]; std :: vector < short > v7 = json_types [ \"array\" ]; std :: unordered_map < std :: string , json > v8 = json_types ; // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } // example for an exception try { bool v1 = json_types [ \"string\" ]; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] [ jso n .excep t io n . t ype_error. 302 ] t ype mus t be boolea n , bu t is s tr i n g","title":"Examples"},{"location":"api/basic_json/operator_ValueType/#version-history","text":"Since version 1.0.0. Macros JSON_EXPLICIT / JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.","title":"Version history"},{"location":"api/basic_json/operator_eq/","text":"nlohmann::basic_json:: operator== \u00b6 // until C++20 bool operator == ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator == ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator == ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator == ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator == ( ScalarType rhs ) const noexcept ; // (2) }; 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. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing special values 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 > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-defined operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } ... } Comparing different basic_json specializations Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects { \"version\" : 1 , \"type\" : \"integer\" } and { \"type\" : \"integer\" , \"version\" : 1 } depends on whether nlohmann::json or nlohmann::ordered_json is used: #include #include #include using json = nlohmann :: json ; int main () { nlohmann :: json uj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: json uj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; nlohmann :: ordered_json oj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: ordered_json oj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; std :: cout << std :: boolalpha << ( uj1 == uj2 ) << '\\n' << ( oj1 == oj2 ) << std :: endl ; } Output: true false Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 == array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 == object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 == number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 == string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } true 17 == 17.0 true \"foo\" == \"bar\" false Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" == nullptr \" << ( array == nullptr ) << '\\n' ; std :: cout << object << \" == nullptr \" << ( object == nullptr ) << '\\n' ; std :: cout << number << \" == nullptr \" << ( number == nullptr ) << '\\n' ; std :: cout << string << \" == nullptr \" << ( string == nullptr ) << '\\n' ; std :: cout << null << \" == nullptr \" << ( null == nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == null p tr false { \"A\" : \"a\" , \"B\" : \"b\" } == null p tr false 17 == null p tr false \"foo\" == null p tr false null == null p tr true Version history \u00b6 Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"operator=="},{"location":"api/basic_json/operator_eq/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator == ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator == ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator == ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator == ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator == ( ScalarType rhs ) const noexcept ; // (2) }; 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.","title":"nlohmann::basic_json::operator=="},{"location":"api/basic_json/operator_eq/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_eq/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_eq/#return-value","text":"whether the values lhs / *this and rhs are equal","title":"Return value"},{"location":"api/basic_json/operator_eq/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_eq/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_eq/#notes","text":"Comparing special values 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 > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-defined operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } ... } Comparing different basic_json specializations Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects { \"version\" : 1 , \"type\" : \"integer\" } and { \"type\" : \"integer\" , \"version\" : 1 } depends on whether nlohmann::json or nlohmann::ordered_json is used: #include #include #include using json = nlohmann :: json ; int main () { nlohmann :: json uj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: json uj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; nlohmann :: ordered_json oj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: ordered_json oj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; std :: cout << std :: boolalpha << ( uj1 == uj2 ) << '\\n' << ( oj1 == oj2 ) << std :: endl ; } Output: true false","title":"Notes"},{"location":"api/basic_json/operator_eq/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 == array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 == object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 == number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 == string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } true 17 == 17.0 true \"foo\" == \"bar\" false Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" == nullptr \" << ( array == nullptr ) << '\\n' ; std :: cout << object << \" == nullptr \" << ( object == nullptr ) << '\\n' ; std :: cout << number << \" == nullptr \" << ( number == nullptr ) << '\\n' ; std :: cout << string << \" == nullptr \" << ( string == nullptr ) << '\\n' ; std :: cout << null << \" == nullptr \" << ( null == nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == null p tr false { \"A\" : \"a\" , \"B\" : \"b\" } == null p tr false 17 == null p tr false \"foo\" == null p tr false null == null p tr true","title":"Examples"},{"location":"api/basic_json/operator_eq/#version-history","text":"Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_ge/","text":"nlohmann::basic_json:: operator>= \u00b6 // until C++20 bool operator >= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator >= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator >= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is less than or equal to rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" >= \" << array_2 << \" \" << ( array_1 >= array_2 ) << '\\n' ; std :: cout << object_1 << \" >= \" << object_2 << \" \" << ( object_1 >= object_2 ) << '\\n' ; std :: cout << number_1 << \" >= \" << number_2 << \" \" << ( number_1 >= number_2 ) << '\\n' ; std :: cout << string_1 << \" >= \" << string_2 << \" \" << ( string_1 >= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] >= [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } >= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 >= 17.0000000000001 false \"foo\" >= \"bar\" true See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator>="},{"location":"api/basic_json/operator_ge/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator >= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator >= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator >= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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.","title":"nlohmann::basic_json::operator>="},{"location":"api/basic_json/operator_ge/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_ge/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_ge/#return-value","text":"whether lhs is less than or equal to rhs","title":"Return value"},{"location":"api/basic_json/operator_ge/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_ge/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_ge/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_ge/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" >= \" << array_2 << \" \" << ( array_1 >= array_2 ) << '\\n' ; std :: cout << object_1 << \" >= \" << object_2 << \" \" << ( object_1 >= object_2 ) << '\\n' ; std :: cout << number_1 << \" >= \" << number_2 << \" \" << ( number_1 >= number_2 ) << '\\n' ; std :: cout << string_1 << \" >= \" << string_2 << \" \" << ( string_1 >= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] >= [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } >= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 >= 17.0000000000001 false \"foo\" >= \"bar\" true","title":"Examples"},{"location":"api/basic_json/operator_ge/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_ge/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_gt/","text":"nlohmann::basic_json:: operator> \u00b6 // until C++20 bool operator > ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator > ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator > ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is greater than rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" > \" << array_2 << \" \" << ( array_1 > array_2 ) << '\\n' ; std :: cout << object_1 << \" > \" << object_2 << \" \" << ( object_1 > object_2 ) << '\\n' ; std :: cout << number_1 << \" > \" << number_2 << \" \" << ( number_1 > number_2 ) << '\\n' ; std :: cout << string_1 << \" > \" << string_2 << \" \" << ( string_1 > string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] > [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } > { \"A\" : \"a\" , \"B\" : \"b\" } false 17 > 17.0000000000001 false \"foo\" > \"bar\" true See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator>"},{"location":"api/basic_json/operator_gt/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator > ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator > ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator > ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.","title":"nlohmann::basic_json::operator>"},{"location":"api/basic_json/operator_gt/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_gt/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_gt/#return-value","text":"whether lhs is greater than rhs","title":"Return value"},{"location":"api/basic_json/operator_gt/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_gt/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_gt/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_gt/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" > \" << array_2 << \" \" << ( array_1 > array_2 ) << '\\n' ; std :: cout << object_1 << \" > \" << object_2 << \" \" << ( object_1 > object_2 ) << '\\n' ; std :: cout << number_1 << \" > \" << number_2 << \" \" << ( number_1 > number_2 ) << '\\n' ; std :: cout << string_1 << \" > \" << string_2 << \" \" << ( string_1 > string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] > [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } > { \"A\" : \"a\" , \"B\" : \"b\" } false 17 > 17.0000000000001 false \"foo\" > \"bar\" true","title":"Examples"},{"location":"api/basic_json/operator_gt/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_gt/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_le/","text":"nlohmann::basic_json:: operator<= \u00b6 // until C++20 bool operator <= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator <= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator <= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is less than or equal to rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" <= \" << array_2 << \" \" << ( array_1 <= array_2 ) << '\\n' ; std :: cout << object_1 << \" <= \" << object_2 << \" \" << ( object_1 <= object_2 ) << '\\n' ; std :: cout << number_1 << \" <= \" << number_2 << \" \" << ( number_1 <= number_2 ) << '\\n' ; std :: cout << string_1 << \" <= \" << string_2 << \" \" << ( string_1 <= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] <= [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } <= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 <= 17.0000000000001 true \"foo\" <= \"bar\" false See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator<="},{"location":"api/basic_json/operator_le/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator <= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator <= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator <= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.","title":"nlohmann::basic_json::operator<="},{"location":"api/basic_json/operator_le/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_le/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_le/#return-value","text":"whether lhs is less than or equal to rhs","title":"Return value"},{"location":"api/basic_json/operator_le/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_le/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_le/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_le/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" <= \" << array_2 << \" \" << ( array_1 <= array_2 ) << '\\n' ; std :: cout << object_1 << \" <= \" << object_2 << \" \" << ( object_1 <= object_2 ) << '\\n' ; std :: cout << number_1 << \" <= \" << number_2 << \" \" << ( number_1 <= number_2 ) << '\\n' ; std :: cout << string_1 << \" <= \" << string_2 << \" \" << ( string_1 <= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] <= [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } <= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 <= 17.0000000000001 true \"foo\" <= \"bar\" false","title":"Examples"},{"location":"api/basic_json/operator_le/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_le/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_lt/","text":"nlohmann::basic_json:: operator< \u00b6 // until C++20 bool operator < ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator < ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator < ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is less than rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 < array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 < object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 < number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 < string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } false 17 == 17.0000000000001 true \"foo\" == \"bar\" false See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator<"},{"location":"api/basic_json/operator_lt/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator < ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator < ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator < ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.","title":"nlohmann::basic_json::operator<"},{"location":"api/basic_json/operator_lt/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_lt/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_lt/#return-value","text":"whether lhs is less than rhs","title":"Return value"},{"location":"api/basic_json/operator_lt/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_lt/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_lt/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_lt/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 < array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 < object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 < number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 < string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } false 17 == 17.0000000000001 true \"foo\" == \"bar\" false","title":"Examples"},{"location":"api/basic_json/operator_lt/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_lt/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_ne/","text":"nlohmann::basic_json:: operator!= \u00b6 // until C++20 bool operator != ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator != ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator != ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator != ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator != ( ScalarType rhs ) const noexcept ; // (2) }; 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. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are not equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" != \" << array_2 << \" \" << ( array_1 != array_2 ) << '\\n' ; std :: cout << object_1 << \" != \" << object_2 << \" \" << ( object_1 != object_2 ) << '\\n' ; std :: cout << number_1 << \" != \" << number_2 << \" \" << ( number_1 != number_2 ) << '\\n' ; std :: cout << string_1 << \" != \" << string_2 << \" \" << ( string_1 != string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } != { \"A\" : \"a\" , \"B\" : \"b\" } false 17 != 17.0 false \"foo\" != \"bar\" true Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" != nullptr \" << ( array != nullptr ) << '\\n' ; std :: cout << object << \" != nullptr \" << ( object != nullptr ) << '\\n' ; std :: cout << number << \" != nullptr \" << ( number != nullptr ) << '\\n' ; std :: cout << string << \" != nullptr \" << ( string != nullptr ) << '\\n' ; std :: cout << null << \" != nullptr \" << ( null != nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != null p tr true { \"A\" : \"a\" , \"B\" : \"b\" } != null p tr true 17 != null p tr true \"foo\" != null p tr true null != null p tr false Version history \u00b6 Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"operator!="},{"location":"api/basic_json/operator_ne/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator != ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator != ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator != ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator != ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator != ( ScalarType rhs ) const noexcept ; // (2) }; 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.","title":"nlohmann::basic_json::operator!="},{"location":"api/basic_json/operator_ne/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_ne/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_ne/#return-value","text":"whether the values lhs / *this and rhs are not equal","title":"Return value"},{"location":"api/basic_json/operator_ne/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_ne/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_ne/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number.","title":"Notes"},{"location":"api/basic_json/operator_ne/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" != \" << array_2 << \" \" << ( array_1 != array_2 ) << '\\n' ; std :: cout << object_1 << \" != \" << object_2 << \" \" << ( object_1 != object_2 ) << '\\n' ; std :: cout << number_1 << \" != \" << number_2 << \" \" << ( number_1 != number_2 ) << '\\n' ; std :: cout << string_1 << \" != \" << string_2 << \" \" << ( string_1 != string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } != { \"A\" : \"a\" , \"B\" : \"b\" } false 17 != 17.0 false \"foo\" != \"bar\" true Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" != nullptr \" << ( array != nullptr ) << '\\n' ; std :: cout << object << \" != nullptr \" << ( object != nullptr ) << '\\n' ; std :: cout << number << \" != nullptr \" << ( number != nullptr ) << '\\n' ; std :: cout << string << \" != nullptr \" << ( string != nullptr ) << '\\n' ; std :: cout << null << \" != nullptr \" << ( null != nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != null p tr true { \"A\" : \"a\" , \"B\" : \"b\" } != null p tr true 17 != null p tr true \"foo\" != null p tr true null != null p tr false","title":"Examples"},{"location":"api/basic_json/operator_ne/#version-history","text":"Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_spaceship/","text":"nlohmann::basic_json:: operator<=> \u00b6 // since C++20 class basic_json { std :: partial_ordering operator <=> ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > std :: partial_ordering operator <=> ( const ScalarType rhs ) const noexcept ; // (2) }; 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). Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 rhs (in) second value to consider Return value \u00b6 the std::partial_ordering of the 3-way comparison of *this and rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered : Comparing a NaN with itself. Comparing a NaN with another NaN . Comparing a NaN and any other number. Examples \u00b6 Example: (1) comparing JSON values The example demonstrates comparing several JSON values. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number = 17 ; json string = \"foo\" ; json discarded = json ( json :: value_t :: discarded ); // output values and comparisons std :: cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string ( array_1 <=> array_2 ) << '\\n' ; // *NOPAD* std :: cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string ( object_1 <=> object_2 ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << number << \" := \" << to_string ( string <=> number ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << discarded << \" := \" << to_string ( string <=> discarded ) << '\\n' ; // *NOPAD* } Output: [ 1 , 2 , 3 ] <=> [ 1 , 2 , 4 ] : = less { \"A\" : \"a\" , \"B\" : \"b\" } <=> { \"A\" : \"a\" , \"B\" : \"b\" } : = equivale nt \"foo\" <=> 17 : = grea ter \"foo\" <=> : = u n ordered Example: (2) comparing JSON values and scalars The example demonstrates comparing several JSON values and scalars. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { using float_limits = std :: numeric_limits < json :: number_float_t > ; constexpr auto nan = float_limits :: quiet_NaN (); // create several JSON values json boolean = false ; json number = 17 ; json string = \"17\" ; // output values and comparisons std :: cout << std :: boolalpha << std :: fixed ; std :: cout << boolean << \" <=> \" << true << \" := \" << to_string ( boolean <=> true ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << 17.0 << \" := \" << to_string ( number <=> 17.0 ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << nan << \" := \" << to_string ( number <=> nan ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << 17 << \" := \" << to_string ( string <=> 17 ) << '\\n' ; // *NOPAD* } Output: false <=> true : = less 17 <=> 17.000000 : = equivale nt 17 <=> nan : = u n ordered \"17\" <=> 17 : = grea ter See also \u00b6 operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator<= - comparison: less than or equal operator> - comparison: greater than operator>= - comparison: greater than or equal Version history \u00b6 Added in version 3.11.0. Added in version 3.11.0.","title":"operator<=>"},{"location":"api/basic_json/operator_spaceship/#nlohmannbasic_jsonoperator","text":"// since C++20 class basic_json { std :: partial_ordering operator <=> ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > std :: partial_ordering operator <=> ( const ScalarType rhs ) const noexcept ; // (2) }; 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).","title":"nlohmann::basic_json::operator<=>"},{"location":"api/basic_json/operator_spaceship/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_spaceship/#parameters","text":"rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_spaceship/#return-value","text":"the std::partial_ordering of the 3-way comparison of *this and rhs","title":"Return value"},{"location":"api/basic_json/operator_spaceship/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_spaceship/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_spaceship/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered : Comparing a NaN with itself. Comparing a NaN with another NaN . Comparing a NaN and any other number.","title":"Notes"},{"location":"api/basic_json/operator_spaceship/#examples","text":"Example: (1) comparing JSON values The example demonstrates comparing several JSON values. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number = 17 ; json string = \"foo\" ; json discarded = json ( json :: value_t :: discarded ); // output values and comparisons std :: cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string ( array_1 <=> array_2 ) << '\\n' ; // *NOPAD* std :: cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string ( object_1 <=> object_2 ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << number << \" := \" << to_string ( string <=> number ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << discarded << \" := \" << to_string ( string <=> discarded ) << '\\n' ; // *NOPAD* } Output: [ 1 , 2 , 3 ] <=> [ 1 , 2 , 4 ] : = less { \"A\" : \"a\" , \"B\" : \"b\" } <=> { \"A\" : \"a\" , \"B\" : \"b\" } : = equivale nt \"foo\" <=> 17 : = grea ter \"foo\" <=> : = u n ordered Example: (2) comparing JSON values and scalars The example demonstrates comparing several JSON values and scalars. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { using float_limits = std :: numeric_limits < json :: number_float_t > ; constexpr auto nan = float_limits :: quiet_NaN (); // create several JSON values json boolean = false ; json number = 17 ; json string = \"17\" ; // output values and comparisons std :: cout << std :: boolalpha << std :: fixed ; std :: cout << boolean << \" <=> \" << true << \" := \" << to_string ( boolean <=> true ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << 17.0 << \" := \" << to_string ( number <=> 17.0 ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << nan << \" := \" << to_string ( number <=> nan ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << 17 << \" := \" << to_string ( string <=> 17 ) << '\\n' ; // *NOPAD* } Output: false <=> true : = less 17 <=> 17.000000 : = equivale nt 17 <=> nan : = u n ordered \"17\" <=> 17 : = grea ter","title":"Examples"},{"location":"api/basic_json/operator_spaceship/#see-also","text":"operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator<= - comparison: less than or equal operator> - comparison: greater than operator>= - comparison: greater than or equal","title":"See also"},{"location":"api/basic_json/operator_spaceship/#version-history","text":"Added in version 3.11.0. Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_value_t/","text":"nlohmann::basic_json:: operator value_t \u00b6 constexpr operator value_t () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration. Return value \u00b6 the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies operator value_t() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call operator value_t() json :: value_t t_null = j_null ; json :: value_t t_boolean = j_boolean ; json :: value_t t_number_integer = j_number_integer ; json :: value_t t_number_unsigned = j_number_unsigned ; json :: value_t t_number_float = j_number_float ; json :: value_t t_object = j_object ; json :: value_t t_array = j_array ; json :: value_t t_string = j_string ; // print types std :: cout << std :: boolalpha ; std :: cout << ( t_null == json :: value_t :: null ) << '\\n' ; std :: cout << ( t_boolean == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( t_number_integer == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( t_number_unsigned == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( t_number_float == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( t_object == json :: value_t :: object ) << '\\n' ; std :: cout << ( t_array == json :: value_t :: array ) << '\\n' ; std :: cout << ( t_string == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true Version history \u00b6 Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"operator value_t"},{"location":"api/basic_json/operator_value_t/#nlohmannbasic_jsonoperator-value_t","text":"constexpr operator value_t () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration.","title":"nlohmann::basic_json::operator value_t"},{"location":"api/basic_json/operator_value_t/#return-value","text":"the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded","title":"Return value"},{"location":"api/basic_json/operator_value_t/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_value_t/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/operator_value_t/#examples","text":"Example The following code exemplifies operator value_t() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call operator value_t() json :: value_t t_null = j_null ; json :: value_t t_boolean = j_boolean ; json :: value_t t_number_integer = j_number_integer ; json :: value_t t_number_unsigned = j_number_unsigned ; json :: value_t t_number_float = j_number_float ; json :: value_t t_object = j_object ; json :: value_t t_array = j_array ; json :: value_t t_string = j_string ; // print types std :: cout << std :: boolalpha ; std :: cout << ( t_null == json :: value_t :: null ) << '\\n' ; std :: cout << ( t_boolean == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( t_number_integer == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( t_number_unsigned == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( t_number_float == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( t_object == json :: value_t :: object ) << '\\n' ; std :: cout << ( t_array == json :: value_t :: array ) << '\\n' ; std :: cout << ( t_string == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true","title":"Examples"},{"location":"api/basic_json/operator_value_t/#version-history","text":"Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/other_error/","text":"nlohmann::basic_json:: other_error \u00b6 class other_error : public exception ; This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx (see list of other errors ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .o t her_error. 501 ] u nsu ccess ful : { \"op\" : \"test\" , \"path\" : \"/best_biscuit/name\" , \"value\" : \"Choco Leibniz\" } excep t io n id : 501 See also \u00b6 List of other errors 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 Version history \u00b6 Since version 3.0.0.","title":"other_error"},{"location":"api/basic_json/other_error/#nlohmannbasic_jsonother_error","text":"class other_error : public exception ; This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx (see list of other errors ).","title":"nlohmann::basic_json::other_error"},{"location":"api/basic_json/other_error/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/other_error/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/other_error/#examples","text":"Example The following code shows how a other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .o t her_error. 501 ] u nsu ccess ful : { \"op\" : \"test\" , \"path\" : \"/best_biscuit/name\" , \"value\" : \"Choco Leibniz\" } excep t io n id : 501","title":"Examples"},{"location":"api/basic_json/other_error/#see-also","text":"List of other errors 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","title":"See also"},{"location":"api/basic_json/other_error/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/out_of_range/","text":"nlohmann::basic_json:: out_of_range \u00b6 class out_of_range : public exception ; 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 ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge excep t io n id : 401 See also \u00b6 List of out-of-range errors 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 other_error for exceptions indicating other library errors Version history \u00b6 Since version 3.0.0.","title":"out_of_range"},{"location":"api/basic_json/out_of_range/#nlohmannbasic_jsonout_of_range","text":"class out_of_range : public exception ; 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 ).","title":"nlohmann::basic_json::out_of_range"},{"location":"api/basic_json/out_of_range/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/out_of_range/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/out_of_range/#examples","text":"Example The following code shows how a out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge excep t io n id : 401","title":"Examples"},{"location":"api/basic_json/out_of_range/#see-also","text":"List of out-of-range errors 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 other_error for exceptions indicating other library errors","title":"See also"},{"location":"api/basic_json/out_of_range/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/parse/","text":"nlohmann::basic_json:: parse \u00b6 // (1) template < typename InputType > static basic_json parse ( InputType && i , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); // (2) template < typename IteratorType > static basic_json parse ( IteratorType first , IteratorType last , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); Deserialize from a compatible input. Deserialize from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len Parameters \u00b6 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 Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails. Complexity \u00b6 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. Notes \u00b6 (1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion . Examples \u00b6 Parsing from a character array The example below demonstrates the parse() function reading from an array. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text char text [] = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a string The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from an input stream The example below demonstrates the parse() function with and without callback function. #include #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // fill a stream with JSON text std :: stringstream ss ; ss << text ; // parse and serialize JSON json j_complete = json :: parse ( ss ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // fill a stream with JSON text ss . clear (); ss << text ; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( ss , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a contiguous container The example below demonstrates the parse() function reading from a contiguous container. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as std::vector std :: vector < std :: uint8_t > text = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , '\\0' }; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from a non null-terminated string The example below demonstrates the parse() function reading from a string that is not null-terminated. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as string that is not null-terminated const char * ptr = \"[1,2,3]another value\" ; // parse and serialize JSON json j_complete = json :: parse ( ptr , ptr + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from an iterator pair The example below demonstrates the parse() function reading from an iterator pair. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given an input with other values std :: vector < std :: uint8_t > input = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , 'o' , 't' , 'h' , 'e' , 'r' }; // parse and serialize JSON json j_complete = json :: parse ( input . begin (), input . begin () + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Effect of allow_exceptions parameter The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function. #include #include using json = nlohmann :: json ; int main () { // an invalid JSON text std :: string text = R \" ( { \"key\": \"value without closing quotes } ) \" ; // parse with exceptions try { json j = json :: parse ( text ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // parse without exceptions json j = json :: parse ( text , nullptr , false ); if ( j . is_discarded ()) { std :: cout << \"the input is invalid JSON\" << std :: endl ; } else { std :: cout << \"the input is valid JSON: \" << j << std :: endl ; } } Output: [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 4 , colum n 0 : sy nta x error while parsi n g value - i n valid s tr i n g : co ntr ol charac ter U+ 000 A (LF) mus t be escaped t o \\u 000 A or \\ n ; las t read : '\"value without closing quotes' the input is invalid JSON See also \u00b6 accept - check if the input is valid JSON operator>> - deserialize from stream Version history \u00b6 Added in version 1.0.0. Overload for contiguous containers (1) added in version 2.0.3. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"parse"},{"location":"api/basic_json/parse/#nlohmannbasic_jsonparse","text":"// (1) template < typename InputType > static basic_json parse ( InputType && i , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); // (2) template < typename IteratorType > static basic_json parse ( IteratorType first , IteratorType last , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); Deserialize from a compatible input. Deserialize from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.","title":"nlohmann::basic_json::parse"},{"location":"api/basic_json/parse/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len","title":"Template parameters"},{"location":"api/basic_json/parse/#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","title":"Parameters"},{"location":"api/basic_json/parse/#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 .","title":"Return value"},{"location":"api/basic_json/parse/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/parse/#exceptions","text":"Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails.","title":"Exceptions"},{"location":"api/basic_json/parse/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb or reading from (1) the input i or (2) the iterator range [ first , last ] has a super-linear complexity.","title":"Complexity"},{"location":"api/basic_json/parse/#notes","text":"(1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion .","title":"Notes"},{"location":"api/basic_json/parse/#examples","text":"Parsing from a character array The example below demonstrates the parse() function reading from an array. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text char text [] = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a string The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from an input stream The example below demonstrates the parse() function with and without callback function. #include #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // fill a stream with JSON text std :: stringstream ss ; ss << text ; // parse and serialize JSON json j_complete = json :: parse ( ss ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // fill a stream with JSON text ss . clear (); ss << text ; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( ss , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a contiguous container The example below demonstrates the parse() function reading from a contiguous container. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as std::vector std :: vector < std :: uint8_t > text = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , '\\0' }; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from a non null-terminated string The example below demonstrates the parse() function reading from a string that is not null-terminated. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as string that is not null-terminated const char * ptr = \"[1,2,3]another value\" ; // parse and serialize JSON json j_complete = json :: parse ( ptr , ptr + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from an iterator pair The example below demonstrates the parse() function reading from an iterator pair. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given an input with other values std :: vector < std :: uint8_t > input = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , 'o' , 't' , 'h' , 'e' , 'r' }; // parse and serialize JSON json j_complete = json :: parse ( input . begin (), input . begin () + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Effect of allow_exceptions parameter The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function. #include #include using json = nlohmann :: json ; int main () { // an invalid JSON text std :: string text = R \" ( { \"key\": \"value without closing quotes } ) \" ; // parse with exceptions try { json j = json :: parse ( text ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // parse without exceptions json j = json :: parse ( text , nullptr , false ); if ( j . is_discarded ()) { std :: cout << \"the input is invalid JSON\" << std :: endl ; } else { std :: cout << \"the input is valid JSON: \" << j << std :: endl ; } } Output: [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 4 , colum n 0 : sy nta x error while parsi n g value - i n valid s tr i n g : co ntr ol charac ter U+ 000 A (LF) mus t be escaped t o \\u 000 A or \\ n ; las t read : '\"value without closing quotes' the input is invalid JSON","title":"Examples"},{"location":"api/basic_json/parse/#see-also","text":"accept - check if the input is valid JSON operator>> - deserialize from stream","title":"See also"},{"location":"api/basic_json/parse/#version-history","text":"Added in version 1.0.0. Overload for contiguous containers (1) added in version 2.0.3. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"Version history"},{"location":"api/basic_json/parse_error/","text":"nlohmann::basic_json:: parse_error \u00b6 class parse_error : public exception ; 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 ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception byte - byte index of the parse error Notes \u00b6 For an input with n n bytes, 1 is the index of the first character and n+1 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. Examples \u00b6 Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message : [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 1 , colum n 8 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d ' [ ' , ' { ' , or a li teral excep t io n id : 101 by te posi t io n o f error : 8 See also \u00b6 List of parse errors 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 Version history \u00b6 Since version 3.0.0.","title":"parse_error"},{"location":"api/basic_json/parse_error/#nlohmannbasic_jsonparse_error","text":"class parse_error : public exception ; 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 ).","title":"nlohmann::basic_json::parse_error"},{"location":"api/basic_json/parse_error/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/parse_error/#member-variables","text":"id - the id of the exception byte - byte index of the parse error","title":"Member variables"},{"location":"api/basic_json/parse_error/#notes","text":"For an input with n n bytes, 1 is the index of the first character and n+1 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.","title":"Notes"},{"location":"api/basic_json/parse_error/#examples","text":"Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message : [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 1 , colum n 8 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d ' [ ' , ' { ' , or a li teral excep t io n id : 101 by te posi t io n o f error : 8","title":"Examples"},{"location":"api/basic_json/parse_error/#see-also","text":"List of parse errors 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","title":"See also"},{"location":"api/basic_json/parse_error/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/parse_event_t/","text":"nlohmann::basic_json:: parse_event_t \u00b6 enum class parse_event_t : std :: uint8_t { object_start , object_end , array_start , array_end , key , value }; The parser callback distinguishes the following events: object_start : the parser read { and started to process a JSON object key : the parser read a key of a value in an object object_end : the parser read } and finished processing a JSON object array_start : the parser read [ and started to process a JSON array array_end : the parser read ] and finished processing a JSON array value : the parser finished reading a JSON value Examples \u00b6 Version history \u00b6 Added in version 1.0.0.","title":"parse_event_t"},{"location":"api/basic_json/parse_event_t/#nlohmannbasic_jsonparse_event_t","text":"enum class parse_event_t : std :: uint8_t { object_start , object_end , array_start , array_end , key , value }; The parser callback distinguishes the following events: object_start : the parser read { and started to process a JSON object key : the parser read a key of a value in an object object_end : the parser read } and finished processing a JSON object array_start : the parser read [ and started to process a JSON array array_end : the parser read ] and finished processing a JSON array value : the parser finished reading a JSON value","title":"nlohmann::basic_json::parse_event_t"},{"location":"api/basic_json/parse_event_t/#examples","text":"","title":"Examples"},{"location":"api/basic_json/parse_event_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/parser_callback_t/","text":"nlohmann::basic_json:: parser_callback_t \u00b6 template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ; With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Discarding a value (i.e., returning false ) has different effects depending on the context in which function was called: 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. Parameters \u00b6 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 Return value \u00b6 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. Examples \u00b6 Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Version history \u00b6 Added in version 1.0.0.","title":"parser_callback_t"},{"location":"api/basic_json/parser_callback_t/#nlohmannbasic_jsonparser_callback_t","text":"template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ; With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Discarding a value (i.e., returning false ) has different effects depending on the context in which function was called: 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.","title":"nlohmann::basic_json::parser_callback_t"},{"location":"api/basic_json/parser_callback_t/#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","title":"Parameters"},{"location":"api/basic_json/parser_callback_t/#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.","title":"Return value"},{"location":"api/basic_json/parser_callback_t/#examples","text":"Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } }","title":"Examples"},{"location":"api/basic_json/parser_callback_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/patch/","text":"nlohmann::basic_json:: patch \u00b6 basic_json patch ( const basic_json & json_patch ) const ; 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. Parameters \u00b6 json_patch (in) JSON patch document Return value \u00b6 patched document Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 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. Complexity \u00b6 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. Notes \u00b6 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. Examples \u00b6 Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } See also \u00b6 RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch_inplace applies a JSON Patch without creating a copy of the document merge_patch applies a JSON Merge Patch Version history \u00b6 Added in version 2.0.0.","title":"patch"},{"location":"api/basic_json/patch/#nlohmannbasic_jsonpatch","text":"basic_json patch ( const basic_json & json_patch ) const ; 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.","title":"nlohmann::basic_json::patch"},{"location":"api/basic_json/patch/#parameters","text":"json_patch (in) JSON patch document","title":"Parameters"},{"location":"api/basic_json/patch/#return-value","text":"patched document","title":"Return value"},{"location":"api/basic_json/patch/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/patch/#exceptions","text":"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.","title":"Exceptions"},{"location":"api/basic_json/patch/#complexity","text":"Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.","title":"Complexity"},{"location":"api/basic_json/patch/#notes","text":"The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value.","title":"Notes"},{"location":"api/basic_json/patch/#examples","text":"Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Examples"},{"location":"api/basic_json/patch/#see-also","text":"RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch_inplace applies a JSON Patch without creating a copy of the document merge_patch applies a JSON Merge Patch","title":"See also"},{"location":"api/basic_json/patch/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/patch_inplace/","text":"nlohmann::basic_json:: patch_inplace \u00b6 void patch_inplace ( const basic_json & json_patch ) const ; 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. Parameters \u00b6 json_patch (in) JSON patch document Exception safety \u00b6 No guarantees, value may be corrupted by an unsuccessful patch operation. Exceptions \u00b6 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. Complexity \u00b6 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. Notes \u00b6 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. Examples \u00b6 Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // output original document std :: cout << \"Before \\n \" << std :: setw ( 4 ) << doc << std :: endl ; // apply the patch doc . patch_inplace ( patch ); // output patched document std :: cout << \" \\n After \\n \" << std :: setw ( 4 ) << doc << std :: endl ; } Output: Be f ore { \"baz\" : \"qux\" , \"foo\" : \"bar\" } A fter { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } See also \u00b6 RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch applies a JSON Merge Patch merge_patch applies a JSON Merge Patch Version history \u00b6 Added in version 3.11.0.","title":"patch_inplace"},{"location":"api/basic_json/patch_inplace/#nlohmannbasic_jsonpatch_inplace","text":"void patch_inplace ( const basic_json & json_patch ) const ; 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.","title":"nlohmann::basic_json::patch_inplace"},{"location":"api/basic_json/patch_inplace/#parameters","text":"json_patch (in) JSON patch document","title":"Parameters"},{"location":"api/basic_json/patch_inplace/#exception-safety","text":"No guarantees, value may be corrupted by an unsuccessful patch operation.","title":"Exception safety"},{"location":"api/basic_json/patch_inplace/#exceptions","text":"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.","title":"Exceptions"},{"location":"api/basic_json/patch_inplace/#complexity","text":"Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.","title":"Complexity"},{"location":"api/basic_json/patch_inplace/#notes","text":"Unlike patch , patch_inplace applies the operation \"in place\" and no copy of the JSON value is created. That makes it faster for large documents by avoiding the copy. However, the JSON value might be corrupted if the function throws an exception.","title":"Notes"},{"location":"api/basic_json/patch_inplace/#examples","text":"Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // output original document std :: cout << \"Before \\n \" << std :: setw ( 4 ) << doc << std :: endl ; // apply the patch doc . patch_inplace ( patch ); // output patched document std :: cout << \" \\n After \\n \" << std :: setw ( 4 ) << doc << std :: endl ; } Output: Be f ore { \"baz\" : \"qux\" , \"foo\" : \"bar\" } A fter { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Examples"},{"location":"api/basic_json/patch_inplace/#see-also","text":"RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch applies a JSON Merge Patch merge_patch applies a JSON Merge Patch","title":"See also"},{"location":"api/basic_json/patch_inplace/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/push_back/","text":"nlohmann::basic_json:: push_back \u00b6 // (1) void push_back ( basic_json && val ); void push_back ( const basic_json & val ); // (2) void push_back ( const typename object_t :: value_type & val ); // (3) void push_back ( initializer_list_t init ); 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&&) . Parameters \u00b6 val (in) the value to add to the JSON array/object init (in) an initializer list Exceptions \u00b6 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\" Complexity \u00b6 Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init . Notes \u00b6 (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 , see #235 for more information. Examples \u00b6 Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]] Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"push_back"},{"location":"api/basic_json/push_back/#nlohmannbasic_jsonpush_back","text":"// (1) void push_back ( basic_json && val ); void push_back ( const basic_json & val ); // (2) void push_back ( const typename object_t :: value_type & val ); // (3) void push_back ( initializer_list_t init ); 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&&) .","title":"nlohmann::basic_json::push_back"},{"location":"api/basic_json/push_back/#parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list","title":"Parameters"},{"location":"api/basic_json/push_back/#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\"","title":"Exceptions"},{"location":"api/basic_json/push_back/#complexity","text":"Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init .","title":"Complexity"},{"location":"api/basic_json/push_back/#notes","text":"(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list , see #235 for more information.","title":"Notes"},{"location":"api/basic_json/push_back/#examples","text":"Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]]","title":"Examples"},{"location":"api/basic_json/push_back/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"Version history"},{"location":"api/basic_json/rbegin/","text":"nlohmann::basic_json:: rbegin \u00b6 reverse_iterator rbegin () noexcept ; const_reverse_iterator rbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element. Return value \u00b6 reverse iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for rbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: reverse_iterator it = array . rbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"rbegin"},{"location":"api/basic_json/rbegin/#nlohmannbasic_jsonrbegin","text":"reverse_iterator rbegin () noexcept ; const_reverse_iterator rbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element.","title":"nlohmann::basic_json::rbegin"},{"location":"api/basic_json/rbegin/#return-value","text":"reverse iterator to the first element","title":"Return value"},{"location":"api/basic_json/rbegin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/rbegin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/rbegin/#examples","text":"Example The following code shows an example for rbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: reverse_iterator it = array . rbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/rbegin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/rend/","text":"nlohmann::basic_json:: rend \u00b6 reverse_iterator rend () noexcept ; const_reverse_iterator rend () const noexcept ; 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. Return value \u00b6 reverse iterator to the element following the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: reverse_iterator it = array . rend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"rend"},{"location":"api/basic_json/rend/#nlohmannbasic_jsonrend","text":"reverse_iterator rend () noexcept ; const_reverse_iterator rend () const noexcept ; 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.","title":"nlohmann::basic_json::rend"},{"location":"api/basic_json/rend/#return-value","text":"reverse iterator to the element following the last element","title":"Return value"},{"location":"api/basic_json/rend/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/rend/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/rend/#examples","text":"Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: reverse_iterator it = array . rend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/rend/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/sax_parse/","text":"nlohmann::basic_json:: sax_parse \u00b6 // (1) template < typename InputType , typename SAX > static bool sax_parse ( InputType && i , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); // (2) template < class IteratorType , class SAX > static bool sax_parse ( IteratorType first , IteratorType last , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); Read from input and generate SAX events Read from a compatible input. Read from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. The SAX event lister must follow the interface of json_sax . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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 Return value \u00b6 return value of the last processed SAX event Exception safety \u00b6 Complexity \u00b6 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. Notes \u00b6 A UTF-8 byte order mark is silently ignored. Examples \u00b6 Example The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0. 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 ); .","title":"sax_parse"},{"location":"api/basic_json/sax_parse/#nlohmannbasic_jsonsax_parse","text":"// (1) template < typename InputType , typename SAX > static bool sax_parse ( InputType && i , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); // (2) template < class IteratorType , class SAX > static bool sax_parse ( IteratorType first , IteratorType last , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); Read from input and generate SAX events Read from a compatible input. Read from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. The SAX event lister must follow the interface of json_sax .","title":"nlohmann::basic_json::sax_parse"},{"location":"api/basic_json/sax_parse/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/sax_parse/#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","title":"Parameters"},{"location":"api/basic_json/sax_parse/#return-value","text":"return value of the last processed SAX event","title":"Return value"},{"location":"api/basic_json/sax_parse/#exception-safety","text":"","title":"Exception safety"},{"location":"api/basic_json/sax_parse/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.","title":"Complexity"},{"location":"api/basic_json/sax_parse/#notes","text":"A UTF-8 byte order mark is silently ignored.","title":"Notes"},{"location":"api/basic_json/sax_parse/#examples","text":"Example The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/basic_json/sax_parse/#version-history","text":"Added in version 3.2.0. 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 ); .","title":"Version history"},{"location":"api/basic_json/size/","text":"nlohmann::basic_json:: size \u00b6 size_type size () const noexcept ; Returns the number of elements in a JSON value. Return value \u00b6 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() Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity. Notes \u00b6 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. Examples \u00b6 Example The following code calls size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call size() std :: cout << j_null . size () << '\\n' ; std :: cout << j_boolean . size () << '\\n' ; std :: cout << j_number_integer . size () << '\\n' ; std :: cout << j_number_float . size () << '\\n' ; std :: cout << j_object . size () << '\\n' ; std :: cout << j_object_empty . size () << '\\n' ; std :: cout << j_array . size () << '\\n' ; std :: cout << j_array_empty . size () << '\\n' ; std :: cout << j_string . size () << '\\n' ; } Output: 0 1 1 1 2 0 5 0 1 Version history \u00b6 Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"size"},{"location":"api/basic_json/size/#nlohmannbasic_jsonsize","text":"size_type size () const noexcept ; Returns the number of elements in a JSON value.","title":"nlohmann::basic_json::size"},{"location":"api/basic_json/size/#return-value","text":"The return value depends on the different types and is defined as follows: Value type return value null 0 boolean 1 string 1 number 1 binary 1 object result of function object_t::size() array result of function array_t::size()","title":"Return value"},{"location":"api/basic_json/size/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/size/#complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.","title":"Complexity"},{"location":"api/basic_json/size/#notes","text":"This function does not return the length of a string stored as JSON value -- it returns the number of elements in the JSON value which is 1 in the case of a string.","title":"Notes"},{"location":"api/basic_json/size/#examples","text":"Example The following code calls size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call size() std :: cout << j_null . size () << '\\n' ; std :: cout << j_boolean . size () << '\\n' ; std :: cout << j_number_integer . size () << '\\n' ; std :: cout << j_number_float . size () << '\\n' ; std :: cout << j_object . size () << '\\n' ; std :: cout << j_object_empty . size () << '\\n' ; std :: cout << j_array . size () << '\\n' ; std :: cout << j_array_empty . size () << '\\n' ; std :: cout << j_string . size () << '\\n' ; } Output: 0 1 1 1 2 0 5 0 1","title":"Examples"},{"location":"api/basic_json/size/#version-history","text":"Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/std_hash/","text":"std:: hash \u00b6 namespace std { struct hash < nlohmann :: basic_json > ; } 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. Examples \u00b6 Example The example shows how to calculate hash values for different JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { std :: cout << \"hash(null) = \" << std :: hash < json > {}( json ( nullptr )) << '\\n' << \"hash(false) = \" << std :: hash < json > {}( json ( false )) << '\\n' << \"hash(0) = \" << std :: hash < json > {}( json ( 0 )) << '\\n' << \"hash(0U) = \" << std :: hash < json > {}( json ( 0U )) << '\\n' << \"hash( \\\"\\\" ) = \" << std :: hash < json > {}( json ( \"\" )) << '\\n' << \"hash({}) = \" << std :: hash < json > {}( json :: object ()) << '\\n' << \"hash([]) = \" << std :: hash < json > {}( json :: array ()) << '\\n' << \"hash({ \\\" hello \\\" : \\\" world \\\" }) = \" << std :: hash < json > {}( \"{ \\\" hello \\\" : \\\" world \\\" }\" _json ) << std :: endl ; } Output: hash( null ) = 2654435769 hash( false ) = 2654436030 hash( 0 ) = 2654436095 hash( 0 U) = 2654436156 hash( \"\" ) = 6142509191626859748 hash( {} ) = 2654435832 hash( [] ) = 2654435899 hash( { \"hello\" : \"world\" } ) = 4469488738203676328 Note the output is platform-dependent. Version history \u00b6 Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"std::hash<basic_json>"},{"location":"api/basic_json/std_hash/#stdhashnlohmannbasic_json","text":"namespace std { struct hash < nlohmann :: basic_json > ; } 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.","title":"std::hash<nlohmann::basic_json>"},{"location":"api/basic_json/std_hash/#examples","text":"Example The example shows how to calculate hash values for different JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { std :: cout << \"hash(null) = \" << std :: hash < json > {}( json ( nullptr )) << '\\n' << \"hash(false) = \" << std :: hash < json > {}( json ( false )) << '\\n' << \"hash(0) = \" << std :: hash < json > {}( json ( 0 )) << '\\n' << \"hash(0U) = \" << std :: hash < json > {}( json ( 0U )) << '\\n' << \"hash( \\\"\\\" ) = \" << std :: hash < json > {}( json ( \"\" )) << '\\n' << \"hash({}) = \" << std :: hash < json > {}( json :: object ()) << '\\n' << \"hash([]) = \" << std :: hash < json > {}( json :: array ()) << '\\n' << \"hash({ \\\" hello \\\" : \\\" world \\\" }) = \" << std :: hash < json > {}( \"{ \\\" hello \\\" : \\\" world \\\" }\" _json ) << std :: endl ; } Output: hash( null ) = 2654435769 hash( false ) = 2654436030 hash( 0 ) = 2654436095 hash( 0 U) = 2654436156 hash( \"\" ) = 6142509191626859748 hash( {} ) = 2654435832 hash( [] ) = 2654435899 hash( { \"hello\" : \"world\" } ) = 4469488738203676328 Note the output is platform-dependent.","title":"Examples"},{"location":"api/basic_json/std_hash/#version-history","text":"Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"Version history"},{"location":"api/basic_json/std_swap/","text":"std::swap \u00b6 namespace std { void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ); } Exchanges the values of two JSON objects. Parameters \u00b6 j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1 Possible implementation \u00b6 void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ) { j1 . swap ( j2 ); } Examples \u00b6 Example The following code shows how two values are swapped with std::swap . #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j1 = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j2 = { 1 , 2 , 4 , 8 , 16 }; std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n' ; // swap values std :: swap ( j1 , j2 ); std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std :: endl ; } Output: j 1 = { \"one\" : 1 , \"two\" : 2 } | j 2 = [ 1 , 2 , 4 , 8 , 16 ] j 1 = [ 1 , 2 , 4 , 8 , 16 ] | j 2 = { \"one\" : 1 , \"two\" : 2 } See also \u00b6 swap Version history \u00b6 Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"std::swap<basic_json>"},{"location":"api/basic_json/std_swap/#stdswapbasic_json","text":"namespace std { void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ); } Exchanges the values of two JSON objects.","title":"std::swap<basic_json>"},{"location":"api/basic_json/std_swap/#parameters","text":"j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1","title":"Parameters"},{"location":"api/basic_json/std_swap/#possible-implementation","text":"void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ) { j1 . swap ( j2 ); }","title":"Possible implementation"},{"location":"api/basic_json/std_swap/#examples","text":"Example The following code shows how two values are swapped with std::swap . #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j1 = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j2 = { 1 , 2 , 4 , 8 , 16 }; std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n' ; // swap values std :: swap ( j1 , j2 ); std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std :: endl ; } Output: j 1 = { \"one\" : 1 , \"two\" : 2 } | j 2 = [ 1 , 2 , 4 , 8 , 16 ] j 1 = [ 1 , 2 , 4 , 8 , 16 ] | j 2 = { \"one\" : 1 , \"two\" : 2 }","title":"Examples"},{"location":"api/basic_json/std_swap/#see-also","text":"swap","title":"See also"},{"location":"api/basic_json/std_swap/#version-history","text":"Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"Version history"},{"location":"api/basic_json/string_t/","text":"nlohmann::basic_json:: string_t \u00b6 using string_t = StringType ; The type used to store JSON strings. RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. Template parameters \u00b6 StringType the container to store strings (e.g., std::string ). Note this container is used for keys/names in objects, see object_t . Notes \u00b6 Default type \u00b6 With the default values for StringType ( std::string ), the default value for string_t is std :: string . Encoding \u00b6 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. String comparison \u00b6 RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit. Storage \u00b6 String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced. Examples \u00b6 Example The following code shows that string_t is by default, a typedef to std :: string . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: string , json :: string_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"string_t"},{"location":"api/basic_json/string_t/#nlohmannbasic_jsonstring_t","text":"using string_t = StringType ; The type used to store JSON strings. RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.","title":"nlohmann::basic_json::string_t"},{"location":"api/basic_json/string_t/#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 .","title":"Template parameters"},{"location":"api/basic_json/string_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/string_t/#default-type","text":"With the default values for StringType ( std::string ), the default value for string_t is std :: string .","title":"Default type"},{"location":"api/basic_json/string_t/#encoding","text":"Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.","title":"Encoding"},{"location":"api/basic_json/string_t/#string-comparison","text":"RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit.","title":"String comparison"},{"location":"api/basic_json/string_t/#storage","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.","title":"Storage"},{"location":"api/basic_json/string_t/#examples","text":"Example The following code shows that string_t is by default, a typedef to std :: string . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: string , json :: string_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/string_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/swap/","text":"nlohmann::basic_json:: swap \u00b6 // (1) void swap ( reference other ) noexcept ; // (2) void swap ( reference left , reference right ) noexcept ; // (3) void swap ( array_t & other ); // (4) void swap ( object_t & other ); // (5) void swap ( string_t & other ); // (6) void swap ( binary_t & other ); // (7) void swap ( typename binary_t :: container_type & other ); 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. Parameters \u00b6 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 Exceptions \u00b6 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\" Complexity \u00b6 Constant. Examples \u00b6 Example: Swap JSON value (1, 2) The example below shows how JSON values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create two JSON values json j1 = { 1 , 2 , 3 , 4 , 5 }; json j2 = {{ \"pi\" , 3.141592653589793 }, { \"e\" , 2.718281828459045 }}; // swap the values j1 . swap ( j2 ); // output the values std :: cout << \"j1 = \" << j1 << '\\n' ; std :: cout << \"j2 = \" << j2 << '\\n' ; } Output: j 1 = { \"e\" : 2.718281828459045 , \"pi\" : 3.141592653589793 } j 2 = [ 1 , 2 , 3 , 4 , 5 ] Example: Swap array (3) The example below shows how arrays can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = {{ \"array\" , { 1 , 2 , 3 , 4 }}}; // create an array_t json :: array_t array = { \"Snap\" , \"Crackle\" , \"Pop\" }; // swap the array stored in the JSON value value [ \"array\" ]. swap ( array ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"array = \" << array << '\\n' ; } Output: value = { \"array\" :[ \"Snap\" , \"Crackle\" , \"Pop\" ]} array = [ 1 , 2 , 3 , 4 ] Example: Swap object (4) The example below shows how objects can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { { \"translation\" , {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}} }; // create an object_t json :: object_t object = {{ \"cow\" , \"Kuh\" }, { \"dog\" , \"Hund\" }}; // swap the object stored in the JSON value value [ \"translation\" ]. swap ( object ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"object = \" << object << '\\n' ; } Output: value = { \"translation\" :{ \"cow\" : \"Kuh\" , \"dog\" : \"Hund\" }} objec t = { \"one\" : \"eins\" , \"two\" : \"zwei\" } Example: Swap string (5) The example below shows how strings can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { \"the good\" , \"the bad\" , \"the ugly\" }; // create string_t json :: string_t string = \"the fast\" ; // swap the object stored in the JSON value value [ 1 ]. swap ( string ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"string = \" << string << '\\n' ; } Output: value = [ \"the good\" , \"the fast\" , \"the ugly\" ] s tr i n g = t he bad Example: Swap string (6) The example below shows how binary values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a binary value json value = json :: binary ({ 1 , 2 , 3 }); // create a binary_t json :: binary_t binary = {{ 4 , 5 , 6 }}; // swap the object stored in the JSON value value . swap ( binary ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"binary = \" << json ( binary ) << '\\n' ; } Output: value = { \"bytes\" :[ 4 , 5 , 6 ], \"subtype\" : null } bi nar y = { \"bytes\" :[ 1 , 2 , 3 ], \"subtype\" : null } See also \u00b6 std::swap Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 3.8.0. Since version 3.8.0.","title":"swap"},{"location":"api/basic_json/swap/#nlohmannbasic_jsonswap","text":"// (1) void swap ( reference other ) noexcept ; // (2) void swap ( reference left , reference right ) noexcept ; // (3) void swap ( array_t & other ); // (4) void swap ( object_t & other ); // (5) void swap ( string_t & other ); // (6) void swap ( binary_t & other ); // (7) void swap ( typename binary_t :: container_type & other ); 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.","title":"nlohmann::basic_json::swap"},{"location":"api/basic_json/swap/#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","title":"Parameters"},{"location":"api/basic_json/swap/#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\"","title":"Exceptions"},{"location":"api/basic_json/swap/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/swap/#examples","text":"Example: Swap JSON value (1, 2) The example below shows how JSON values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create two JSON values json j1 = { 1 , 2 , 3 , 4 , 5 }; json j2 = {{ \"pi\" , 3.141592653589793 }, { \"e\" , 2.718281828459045 }}; // swap the values j1 . swap ( j2 ); // output the values std :: cout << \"j1 = \" << j1 << '\\n' ; std :: cout << \"j2 = \" << j2 << '\\n' ; } Output: j 1 = { \"e\" : 2.718281828459045 , \"pi\" : 3.141592653589793 } j 2 = [ 1 , 2 , 3 , 4 , 5 ] Example: Swap array (3) The example below shows how arrays can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = {{ \"array\" , { 1 , 2 , 3 , 4 }}}; // create an array_t json :: array_t array = { \"Snap\" , \"Crackle\" , \"Pop\" }; // swap the array stored in the JSON value value [ \"array\" ]. swap ( array ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"array = \" << array << '\\n' ; } Output: value = { \"array\" :[ \"Snap\" , \"Crackle\" , \"Pop\" ]} array = [ 1 , 2 , 3 , 4 ] Example: Swap object (4) The example below shows how objects can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { { \"translation\" , {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}} }; // create an object_t json :: object_t object = {{ \"cow\" , \"Kuh\" }, { \"dog\" , \"Hund\" }}; // swap the object stored in the JSON value value [ \"translation\" ]. swap ( object ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"object = \" << object << '\\n' ; } Output: value = { \"translation\" :{ \"cow\" : \"Kuh\" , \"dog\" : \"Hund\" }} objec t = { \"one\" : \"eins\" , \"two\" : \"zwei\" } Example: Swap string (5) The example below shows how strings can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { \"the good\" , \"the bad\" , \"the ugly\" }; // create string_t json :: string_t string = \"the fast\" ; // swap the object stored in the JSON value value [ 1 ]. swap ( string ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"string = \" << string << '\\n' ; } Output: value = [ \"the good\" , \"the fast\" , \"the ugly\" ] s tr i n g = t he bad Example: Swap string (6) The example below shows how binary values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a binary value json value = json :: binary ({ 1 , 2 , 3 }); // create a binary_t json :: binary_t binary = {{ 4 , 5 , 6 }}; // swap the object stored in the JSON value value . swap ( binary ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"binary = \" << json ( binary ) << '\\n' ; } Output: value = { \"bytes\" :[ 4 , 5 , 6 ], \"subtype\" : null } bi nar y = { \"bytes\" :[ 1 , 2 , 3 ], \"subtype\" : null }","title":"Examples"},{"location":"api/basic_json/swap/#see-also","text":"std::swap","title":"See also"},{"location":"api/basic_json/swap/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 3.8.0. Since version 3.8.0.","title":"Version history"},{"location":"api/basic_json/to_bjdata/","text":"nlohmann::basic_json:: to_bjdata \u00b6 // (1) static std :: vector < std :: uint8_t > to_bjdata ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_bjdata ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_bjdata ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 . Parameters \u00b6 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. Return value \u00b6 BJData serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in BJData format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678 Version history \u00b6 Added in version 3.11.0.","title":"to_bjdata"},{"location":"api/basic_json/to_bjdata/#nlohmannbasic_jsonto_bjdata","text":"// (1) static std :: vector < std :: uint8_t > to_bjdata ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_bjdata ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_bjdata ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 .","title":"nlohmann::basic_json::to_bjdata"},{"location":"api/basic_json/to_bjdata/#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.","title":"Parameters"},{"location":"api/basic_json/to_bjdata/#return-value","text":"BJData serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_bjdata/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_bjdata/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_bjdata/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in BJData format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678","title":"Examples"},{"location":"api/basic_json/to_bjdata/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/to_bson/","text":"nlohmann::basic_json:: to_bson \u00b6 // (1) static std :: vector < std :: uint8_t > to_bson ( const basic_json & j ); // (2) static void to_bson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_bson ( const basic_json & j , detail :: output_adapter < char > o ); 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 . Parameters \u00b6 j (in) JSON value to serialize o (in) output adapter to write serialization to Return value \u00b6 BSON serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in BSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 1 b 0 x 00 0 x 00 0 x 00 0 x 08 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x 00 0 x 01 0 x 10 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00 Version history \u00b6 Added in version 3.4.0.","title":"to_bson"},{"location":"api/basic_json/to_bson/#nlohmannbasic_jsonto_bson","text":"// (1) static std :: vector < std :: uint8_t > to_bson ( const basic_json & j ); // (2) static void to_bson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_bson ( const basic_json & j , detail :: output_adapter < char > o ); 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 .","title":"nlohmann::basic_json::to_bson"},{"location":"api/basic_json/to_bson/#parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to","title":"Parameters"},{"location":"api/basic_json/to_bson/#return-value","text":"BSON serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_bson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_bson/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_bson/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in BSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 1 b 0 x 00 0 x 00 0 x 00 0 x 08 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x 00 0 x 01 0 x 10 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00","title":"Examples"},{"location":"api/basic_json/to_bson/#version-history","text":"Added in version 3.4.0.","title":"Version history"},{"location":"api/basic_json/to_cbor/","text":"nlohmann::basic_json:: to_cbor \u00b6 // (1) static std :: vector < std :: uint8_t > to_cbor ( const basic_json & j ); // (2) static void to_cbor ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_cbor ( const basic_json & j , detail :: output_adapter < char > o ); 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 . Parameters \u00b6 j (in) JSON value to serialize o (in) output adapter to write serialization to Return value \u00b6 CBOR serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in CBOR format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 xa 2 0 x 67 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x f 5 0 x 66 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 Version history \u00b6 Added in version 2.0.9. Compact representation of floating-point numbers added in version 3.8.0.","title":"to_cbor"},{"location":"api/basic_json/to_cbor/#nlohmannbasic_jsonto_cbor","text":"// (1) static std :: vector < std :: uint8_t > to_cbor ( const basic_json & j ); // (2) static void to_cbor ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_cbor ( const basic_json & j , detail :: output_adapter < char > o ); 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 .","title":"nlohmann::basic_json::to_cbor"},{"location":"api/basic_json/to_cbor/#parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to","title":"Parameters"},{"location":"api/basic_json/to_cbor/#return-value","text":"CBOR serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_cbor/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_cbor/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_cbor/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in CBOR format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 xa 2 0 x 67 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x f 5 0 x 66 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00","title":"Examples"},{"location":"api/basic_json/to_cbor/#version-history","text":"Added in version 2.0.9. Compact representation of floating-point numbers added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/to_msgpack/","text":"nlohmann::basic_json:: to_msgpack \u00b6 // (1) static std :: vector < std :: uint8_t > to_msgpack ( const basic_json & j ); // (2) static void to_msgpack ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_msgpack ( const basic_json & j , detail :: output_adapter < char > o ); 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 . Parameters \u00b6 j (in) JSON value to serialize o (in) output adapter to write serialization to Return value \u00b6 MessagePack serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in MessagePack format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 82 0 xa 7 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 xc 3 0 xa 6 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 Version history \u00b6 Added in version 2.0.9.","title":"to_msgpack"},{"location":"api/basic_json/to_msgpack/#nlohmannbasic_jsonto_msgpack","text":"// (1) static std :: vector < std :: uint8_t > to_msgpack ( const basic_json & j ); // (2) static void to_msgpack ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_msgpack ( const basic_json & j , detail :: output_adapter < char > o ); 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 .","title":"nlohmann::basic_json::to_msgpack"},{"location":"api/basic_json/to_msgpack/#parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to","title":"Parameters"},{"location":"api/basic_json/to_msgpack/#return-value","text":"MessagePack serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_msgpack/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_msgpack/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_msgpack/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in MessagePack format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 82 0 xa 7 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 xc 3 0 xa 6 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00","title":"Examples"},{"location":"api/basic_json/to_msgpack/#version-history","text":"Added in version 2.0.9.","title":"Version history"},{"location":"api/basic_json/to_string/","text":"to_string(basic_json) \u00b6 template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ); This function implements a user-defined to_string for JSON objects. Template parameters \u00b6 BasicJsonType a specialization of basic_json Return value \u00b6 string containing the serialization of the JSON value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Exceptions \u00b6 Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded Complexity \u00b6 Linear. Possible implementation \u00b6 template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ) { return j . dump (); } Examples \u00b6 Example The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup. #include #include using json = nlohmann :: json ; using std :: to_string ; int main () { // create values json j = {{ \"one\" , 1 }, { \"two\" , 2 }}; int i = 42 ; // use ADL to select best to_string function auto j_str = to_string ( j ); // calling nlohmann::to_string auto i_str = to_string ( i ); // calling std::to_string // serialize without indentation std :: cout << j_str << \" \\n\\n \" << i_str << std :: endl ; } Output: { \"one\" : 1 , \"two\" : 2 } 42 See also \u00b6 dump Version history \u00b6 Added in version 3.7.0.","title":"to_string"},{"location":"api/basic_json/to_string/#to_stringbasic_json","text":"template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ); This function implements a user-defined to_string for JSON objects.","title":"to_string(basic_json)"},{"location":"api/basic_json/to_string/#template-parameters","text":"BasicJsonType a specialization of basic_json","title":"Template parameters"},{"location":"api/basic_json/to_string/#return-value","text":"string containing the serialization of the JSON value","title":"Return value"},{"location":"api/basic_json/to_string/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_string/#exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded","title":"Exceptions"},{"location":"api/basic_json/to_string/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/to_string/#possible-implementation","text":"template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ) { return j . dump (); }","title":"Possible implementation"},{"location":"api/basic_json/to_string/#examples","text":"Example The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup. #include #include using json = nlohmann :: json ; using std :: to_string ; int main () { // create values json j = {{ \"one\" , 1 }, { \"two\" , 2 }}; int i = 42 ; // use ADL to select best to_string function auto j_str = to_string ( j ); // calling nlohmann::to_string auto i_str = to_string ( i ); // calling std::to_string // serialize without indentation std :: cout << j_str << \" \\n\\n \" << i_str << std :: endl ; } Output: { \"one\" : 1 , \"two\" : 2 } 42","title":"Examples"},{"location":"api/basic_json/to_string/#see-also","text":"dump","title":"See also"},{"location":"api/basic_json/to_string/#version-history","text":"Added in version 3.7.0.","title":"Version history"},{"location":"api/basic_json/to_ubjson/","text":"nlohmann::basic_json:: to_ubjson \u00b6 // (1) static std :: vector < std :: uint8_t > to_ubjson ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_ubjson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_ubjson ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 . Parameters \u00b6 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. Return value \u00b6 UBJSON serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in UBJSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678 Version history \u00b6 Added in version 3.1.0.","title":"to_ubjson"},{"location":"api/basic_json/to_ubjson/#nlohmannbasic_jsonto_ubjson","text":"// (1) static std :: vector < std :: uint8_t > to_ubjson ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_ubjson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_ubjson ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 .","title":"nlohmann::basic_json::to_ubjson"},{"location":"api/basic_json/to_ubjson/#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.","title":"Parameters"},{"location":"api/basic_json/to_ubjson/#return-value","text":"UBJSON serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_ubjson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_ubjson/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_ubjson/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in UBJSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678","title":"Examples"},{"location":"api/basic_json/to_ubjson/#version-history","text":"Added in version 3.1.0.","title":"Version history"},{"location":"api/basic_json/type/","text":"nlohmann::basic_json:: type \u00b6 constexpr value_t type () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration. Return value \u00b6 the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies type() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true Version history \u00b6 Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"type"},{"location":"api/basic_json/type/#nlohmannbasic_jsontype","text":"constexpr value_t type () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration.","title":"nlohmann::basic_json::type"},{"location":"api/basic_json/type/#return-value","text":"the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded","title":"Return value"},{"location":"api/basic_json/type/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/type/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/type/#examples","text":"Example The following code exemplifies type() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true","title":"Examples"},{"location":"api/basic_json/type/#version-history","text":"Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/type_error/","text":"nlohmann::basic_json:: type_error \u00b6 class type_error : public exception ; 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 ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n . t ype_error. 308 ] ca nn o t use push_back() wi t h s tr i n g excep t io n id : 308 See also \u00b6 List of type errors parse_error for exceptions indicating a parse error invalid_iterator for exceptions indicating errors with iterators out_of_range for exceptions indicating access out of the defined range other_error for exceptions indicating other library errors Version history \u00b6 Since version 3.0.0.","title":"type_error"},{"location":"api/basic_json/type_error/#nlohmannbasic_jsontype_error","text":"class type_error : public exception ; 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 ).","title":"nlohmann::basic_json::type_error"},{"location":"api/basic_json/type_error/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/type_error/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/type_error/#examples","text":"Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n . t ype_error. 308 ] ca nn o t use push_back() wi t h s tr i n g excep t io n id : 308","title":"Examples"},{"location":"api/basic_json/type_error/#see-also","text":"List of type errors parse_error for exceptions indicating a parse error invalid_iterator for exceptions indicating errors with iterators out_of_range for exceptions indicating access out of the defined range other_error for exceptions indicating other library errors","title":"See also"},{"location":"api/basic_json/type_error/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/type_name/","text":"nlohmann::basic_json:: type_name \u00b6 const char * type_name () const noexcept ; Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type. Return value \u00b6 a string representation of the type ( value_t ): Value type return value null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\" Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies type_name() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type_name() std :: cout << j_null << \" is a \" << j_null . type_name () << '\\n' ; std :: cout << j_boolean << \" is a \" << j_boolean . type_name () << '\\n' ; std :: cout << j_number_integer << \" is a \" << j_number_integer . type_name () << '\\n' ; std :: cout << j_number_unsigned << \" is a \" << j_number_unsigned . type_name () << '\\n' ; std :: cout << j_number_float << \" is a \" << j_number_float . type_name () << '\\n' ; std :: cout << j_object << \" is an \" << j_object . type_name () << '\\n' ; std :: cout << j_array << \" is an \" << j_array . type_name () << '\\n' ; std :: cout << j_string << \" is a \" << j_string . type_name () << '\\n' ; } Output: null is a null true is a boolea n -17 is a nu mber 42 is a nu mber 23.42 is a nu mber { \"one\" : 1 , \"two\" : 2 } is a n objec t [ 1 , 2 , 4 , 8 , 16 ] is a n array \"Hello, world\" is a s tr i n g Version history \u00b6 Added in version 1.0.0. Part of the public API version since 2.1.0. Changed return value to const char* and added noexcept in version 3.0.0. Added support for binary type in version 3.8.0.","title":"type_name"},{"location":"api/basic_json/type_name/#nlohmannbasic_jsontype_name","text":"const char * type_name () const noexcept ; Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type.","title":"nlohmann::basic_json::type_name"},{"location":"api/basic_json/type_name/#return-value","text":"a string representation of the type ( value_t ): Value type return value null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\"","title":"Return value"},{"location":"api/basic_json/type_name/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/type_name/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/type_name/#examples","text":"Example The following code exemplifies type_name() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type_name() std :: cout << j_null << \" is a \" << j_null . type_name () << '\\n' ; std :: cout << j_boolean << \" is a \" << j_boolean . type_name () << '\\n' ; std :: cout << j_number_integer << \" is a \" << j_number_integer . type_name () << '\\n' ; std :: cout << j_number_unsigned << \" is a \" << j_number_unsigned . type_name () << '\\n' ; std :: cout << j_number_float << \" is a \" << j_number_float . type_name () << '\\n' ; std :: cout << j_object << \" is an \" << j_object . type_name () << '\\n' ; std :: cout << j_array << \" is an \" << j_array . type_name () << '\\n' ; std :: cout << j_string << \" is a \" << j_string . type_name () << '\\n' ; } Output: null is a null true is a boolea n -17 is a nu mber 42 is a nu mber 23.42 is a nu mber { \"one\" : 1 , \"two\" : 2 } is a n objec t [ 1 , 2 , 4 , 8 , 16 ] is a n array \"Hello, world\" is a s tr i n g","title":"Examples"},{"location":"api/basic_json/type_name/#version-history","text":"Added in version 1.0.0. Part of the public API version since 2.1.0. Changed return value to const char* and added noexcept in version 3.0.0. Added support for binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/unflatten/","text":"nlohmann::basic_json:: unflatten \u00b6 basic_json unflatten () const ; The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints: The value must be an object. The keys must be JSON pointers (see RFC 6901 ) The mapped values must be primitive JSON types. Return value \u00b6 the original JSON from a flattened version Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.314 if value is not an object Throws type_error.315 if object values are not primitive Complexity \u00b6 Linear in the size the JSON value. Notes \u00b6 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 () . Examples \u00b6 Example The following code shows how a flattened JSON object is unflattened into the original nested JSON object. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j_flattened = { { \"/answer/everything\" , 42 }, { \"/happy\" , true }, { \"/list/0\" , 1 }, { \"/list/1\" , 0 }, { \"/list/2\" , 2 }, { \"/name\" , \"Niels\" }, { \"/nothing\" , nullptr }, { \"/object/currency\" , \"USD\" }, { \"/object/value\" , 42.99 }, { \"/pi\" , 3.141 } }; // call unflatten() std :: cout << std :: setw ( 4 ) << j_flattened . unflatten () << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 } See also \u00b6 flatten the reverse function Version history \u00b6 Added in version 2.0.0.","title":"unflatten"},{"location":"api/basic_json/unflatten/#nlohmannbasic_jsonunflatten","text":"basic_json unflatten () const ; The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints: The value must be an object. The keys must be JSON pointers (see RFC 6901 ) The mapped values must be primitive JSON types.","title":"nlohmann::basic_json::unflatten"},{"location":"api/basic_json/unflatten/#return-value","text":"the original JSON from a flattened version","title":"Return value"},{"location":"api/basic_json/unflatten/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/unflatten/#exceptions","text":"The function can throw the following exceptions: Throws type_error.314 if value is not an object Throws type_error.315 if object values are not primitive","title":"Exceptions"},{"location":"api/basic_json/unflatten/#complexity","text":"Linear in the size the JSON value.","title":"Complexity"},{"location":"api/basic_json/unflatten/#notes","text":"Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j , the following is always true: j == j . flatten (). unflatten () .","title":"Notes"},{"location":"api/basic_json/unflatten/#examples","text":"Example The following code shows how a flattened JSON object is unflattened into the original nested JSON object. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j_flattened = { { \"/answer/everything\" , 42 }, { \"/happy\" , true }, { \"/list/0\" , 1 }, { \"/list/1\" , 0 }, { \"/list/2\" , 2 }, { \"/name\" , \"Niels\" }, { \"/nothing\" , nullptr }, { \"/object/currency\" , \"USD\" }, { \"/object/value\" , 42.99 }, { \"/pi\" , 3.141 } }; // call unflatten() std :: cout << std :: setw ( 4 ) << j_flattened . unflatten () << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 }","title":"Examples"},{"location":"api/basic_json/unflatten/#see-also","text":"flatten the reverse function","title":"See also"},{"location":"api/basic_json/unflatten/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/update/","text":"nlohmann::basic_json:: update \u00b6 // (1) void update ( const_reference j , bool merge_objects = false ); // (2) void update ( const_iterator first , const_iterator last , bool merge_objects = false ); Inserts all values from JSON object j . Inserts all values from range [first, last) When merge_objects is false (default), existing keys are overwritten. When merge_objects is true , recursively merges objects with common keys. The function is motivated by Python's dict.update function. Parameters \u00b6 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 Exceptions \u00b6 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\" Complexity \u00b6 O(N*log(size() + N)), where N is the number of elements to insert. O(N*log(size() + N)), where N is the number of elements to insert. Examples \u00b6 Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 ); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 , true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 . begin (), o2 . end ()); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 . begin (), o2 . end (), true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects: { \"color\" : \"red\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" } } The user may override the default settings selectively: { \"color\" : \"blue\" , \"name\" : { \"es\" : \"rat\u00f3n\" }, } Then update manages the merging of default settings and user settings: auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings ); Now effective_settings contains the default settings, but those keys set by the user are overwritten: { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"es\" : \"rat\u00f3n\" } } Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true : auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings , true ); { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" , \"es\" : \"rat\u00f3n\" } } Version history \u00b6 Added in version 3.0.0. Added merge_objects parameter in 3.10.4.","title":"update"},{"location":"api/basic_json/update/#nlohmannbasic_jsonupdate","text":"// (1) void update ( const_reference j , bool merge_objects = false ); // (2) void update ( const_iterator first , const_iterator last , bool merge_objects = false ); Inserts all values from JSON object j . Inserts all values from range [first, last) When merge_objects is false (default), existing keys are overwritten. When merge_objects is true , recursively merges objects with common keys. The function is motivated by Python's dict.update function.","title":"nlohmann::basic_json::update"},{"location":"api/basic_json/update/#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","title":"Parameters"},{"location":"api/basic_json/update/#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\"","title":"Exceptions"},{"location":"api/basic_json/update/#complexity","text":"O(N*log(size() + N)), where N is the number of elements to insert. O(N*log(size() + N)), where N is the number of elements to insert.","title":"Complexity"},{"location":"api/basic_json/update/#examples","text":"Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 ); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 , true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 . begin (), o2 . end ()); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 . begin (), o2 . end (), true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects: { \"color\" : \"red\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" } } The user may override the default settings selectively: { \"color\" : \"blue\" , \"name\" : { \"es\" : \"rat\u00f3n\" }, } Then update manages the merging of default settings and user settings: auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings ); Now effective_settings contains the default settings, but those keys set by the user are overwritten: { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"es\" : \"rat\u00f3n\" } } Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true : auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings , true ); { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" , \"es\" : \"rat\u00f3n\" } }","title":"Examples"},{"location":"api/basic_json/update/#version-history","text":"Added in version 3.0.0. Added merge_objects parameter in 3.10.4.","title":"Version history"},{"location":"api/basic_json/value/","text":"nlohmann::basic_json:: value \u00b6 // (1) template < class ValueType > ValueType value ( const typename object_t :: key_type & key , ValueType && default_value ) const ; // (2) template < class ValueType , class KeyType > ValueType value ( KeyType && key , ValueType && default_value ) const ; // (3) template < class ValueType > ValueType value ( const json_pointer & ptr , const ValueType & default_value ) const ; Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists. The function is basically equivalent to executing try { return at ( key ); } catch ( out_of_range ) { return default_value ; } See 1. This overload is only available if KeyType is comparable with typename object_t :: key_type and typename object_comparator_t :: is_transparent denotes a type. Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists. The function is basically equivalent to executing try { return at ( ptr ); } catch ( out_of_range ) { return default_value ; } Differences to at and operator[] 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. Template parameters \u00b6 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. Parameters \u00b6 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 Return value \u00b6 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 Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at key Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense. See 1. The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at ptr Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense. Complexity \u00b6 Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container. Examples \u00b6 Example: (1) access specified object element with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" , 0 ); double v_floating = j . value ( \"floating\" , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (2) access specified object element using string_view with default value The example below shows how object elements can be queried with a default value. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" sv , 0 ); double v_floating = j . value ( \"floating\" sv , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" sv , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" sv , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (3) access specified object element via JSON Pointer with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"/integer\" _json_pointer , 0 ); double v_floating = j . value ( \"/floating\" _json_pointer , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"/nonexisting\" _json_pointer , \"oops\" ); bool v_boolean = j . value ( \"/nonexisting\" _json_pointer , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false See also \u00b6 see at for access by reference with range checking see operator[] for unchecked access by reference Version history \u00b6 Added in version 1.0.0. Changed parameter default_value type from const ValueType& to ValueType&& in version 3.11.0. Added in version 3.11.0. Made ValueType the first template parameter in version 3.11.2. Added in version 2.0.2.","title":"value"},{"location":"api/basic_json/value/#nlohmannbasic_jsonvalue","text":"// (1) template < class ValueType > ValueType value ( const typename object_t :: key_type & key , ValueType && default_value ) const ; // (2) template < class ValueType , class KeyType > ValueType value ( KeyType && key , ValueType && default_value ) const ; // (3) template < class ValueType > ValueType value ( const json_pointer & ptr , const ValueType & default_value ) const ; Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists. The function is basically equivalent to executing try { return at ( key ); } catch ( out_of_range ) { return default_value ; } See 1. This overload is only available if KeyType is comparable with typename object_t :: key_type and typename object_comparator_t :: is_transparent denotes a type. Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists. The function is basically equivalent to executing try { return at ( ptr ); } catch ( out_of_range ) { return default_value ; } Differences to at and operator[] 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.","title":"nlohmann::basic_json::value"},{"location":"api/basic_json/value/#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.","title":"Template parameters"},{"location":"api/basic_json/value/#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","title":"Parameters"},{"location":"api/basic_json/value/#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","title":"Return value"},{"location":"api/basic_json/value/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/value/#exceptions","text":"The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at key Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense. See 1. The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at ptr Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.","title":"Exceptions"},{"location":"api/basic_json/value/#complexity","text":"Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container.","title":"Complexity"},{"location":"api/basic_json/value/#examples","text":"Example: (1) access specified object element with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" , 0 ); double v_floating = j . value ( \"floating\" , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (2) access specified object element using string_view with default value The example below shows how object elements can be queried with a default value. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" sv , 0 ); double v_floating = j . value ( \"floating\" sv , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" sv , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" sv , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (3) access specified object element via JSON Pointer with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"/integer\" _json_pointer , 0 ); double v_floating = j . value ( \"/floating\" _json_pointer , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"/nonexisting\" _json_pointer , \"oops\" ); bool v_boolean = j . value ( \"/nonexisting\" _json_pointer , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false","title":"Examples"},{"location":"api/basic_json/value/#see-also","text":"see at for access by reference with range checking see operator[] for unchecked access by reference","title":"See also"},{"location":"api/basic_json/value/#version-history","text":"Added in version 1.0.0. Changed parameter default_value type from const ValueType& to ValueType&& in version 3.11.0. Added in version 3.11.0. Made ValueType the first template parameter in version 3.11.2. Added in version 2.0.2.","title":"Version history"},{"location":"api/basic_json/value_t/","text":"nlohmann::basic_json:: value_t \u00b6 enum class value_t : std :: uint8_t { null , object , array , string , boolean , number_integer , number_unsigned , number_float , binary , discarded }; 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. Notes \u00b6 Ordering The order of types is as follows: null boolean number_integer , number_unsigned , number_float object array string binary discarded is unordered. Types of numbers There are three enumerators for numbers ( number_integer , number_unsigned , and number_float ) to distinguish between different types of numbers: 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 Examples \u00b6 Example The following code how type() queries the value_t for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true Version history \u00b6 Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"value_t"},{"location":"api/basic_json/value_t/#nlohmannbasic_jsonvalue_t","text":"enum class value_t : std :: uint8_t { null , object , array , string , boolean , number_integer , number_unsigned , number_float , binary , discarded }; 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.","title":"nlohmann::basic_json::value_t"},{"location":"api/basic_json/value_t/#notes","text":"Ordering The order of types is as follows: null boolean number_integer , number_unsigned , number_float object array string binary discarded is unordered. Types of numbers There are three enumerators for numbers ( number_integer , number_unsigned , and number_float ) to distinguish between different types of numbers: 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","title":"Notes"},{"location":"api/basic_json/value_t/#examples","text":"Example The following code how type() queries the value_t for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true","title":"Examples"},{"location":"api/basic_json/value_t/#version-history","text":"Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/~basic_json/","text":"nlohmann::basic_json:: ~basic_json \u00b6 ~ basic_json () noexcept ; Destroys the JSON value and frees all allocated memory. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Linear. Version history \u00b6 Added in version 1.0.0.","title":"(Destructor)"},{"location":"api/basic_json/~basic_json/#nlohmannbasic_jsonbasic_json","text":"~ basic_json () noexcept ; Destroys the JSON value and frees all allocated memory.","title":"nlohmann::basic_json::~basic_json"},{"location":"api/basic_json/~basic_json/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/~basic_json/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/~basic_json/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/","text":"nlohmann:: byte_container_with_subtype \u00b6 template < typename BinaryType > class byte_container_with_subtype : public BinaryType ; 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. Template parameters \u00b6 BinaryType container to store bytes ( std :: vector < std :: uint8_t > by default) Member types \u00b6 container_type - the type of the underlying container ( BinaryType ) subtype_type - the type of the subtype ( std :: uint64_t ) Member functions \u00b6 (constructor) operator== - comparison: equal operator!= - comparison: not equal set_subtype - sets the binary subtype subtype - return the binary subtype has_subtype - return whether the value has a subtype clear_subtype - clears the binary subtype Version history \u00b6 Added in version 3.8.0. Changed type of subtypes to std :: uint64_t in 3.10.0.","title":"Overview"},{"location":"api/byte_container_with_subtype/#nlohmannbyte_container_with_subtype","text":"template < typename BinaryType > class byte_container_with_subtype : public BinaryType ; 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.","title":"nlohmann::byte_container_with_subtype"},{"location":"api/byte_container_with_subtype/#template-parameters","text":"BinaryType container to store bytes ( std :: vector < std :: uint8_t > by default)","title":"Template parameters"},{"location":"api/byte_container_with_subtype/#member-types","text":"container_type - the type of the underlying container ( BinaryType ) subtype_type - the type of the subtype ( std :: uint64_t )","title":"Member types"},{"location":"api/byte_container_with_subtype/#member-functions","text":"(constructor) operator== - comparison: equal operator!= - comparison: not equal set_subtype - sets the binary subtype subtype - return the binary subtype has_subtype - return whether the value has a subtype clear_subtype - clears the binary subtype","title":"Member functions"},{"location":"api/byte_container_with_subtype/#version-history","text":"Added in version 3.8.0. Changed type of subtypes to std :: uint64_t in 3.10.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/","text":"nlohmann::byte_container_with_subtype:: byte_container_with_subtype \u00b6 // (1) byte_container_with_subtype (); // (2) byte_container_with_subtype ( const container_type & container ); byte_container_with_subtype ( container_type && container ); // (3) byte_container_with_subtype ( const container_type & container , subtype_type subtype ); byte_container_with_subtype ( container_type && container , subtype_type subtype ); Create empty binary container without subtype. Create binary container without subtype. Create binary container with subtype. Parameters \u00b6 container (in) binary container subtype (in) subtype Examples \u00b6 Example The example below demonstrates how byte containers can be created. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { // (1) create empty container auto c1 = byte_container_with_subtype (); std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // (2) create container auto c2 = byte_container_with_subtype ( bytes ); // (3) create container with subtype auto c3 = byte_container_with_subtype ( bytes , 42 ); std :: cout << json ( c1 ) << \" \\n \" << json ( c2 ) << \" \\n \" << json ( c3 ) << std :: endl ; } Output: { \"bytes\" :[], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } Version history \u00b6 Since version 3.8.0.","title":"(constructor)"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#nlohmannbyte_container_with_subtypebyte_container_with_subtype","text":"// (1) byte_container_with_subtype (); // (2) byte_container_with_subtype ( const container_type & container ); byte_container_with_subtype ( container_type && container ); // (3) byte_container_with_subtype ( const container_type & container , subtype_type subtype ); byte_container_with_subtype ( container_type && container , subtype_type subtype ); Create empty binary container without subtype. Create binary container without subtype. Create binary container with subtype.","title":"nlohmann::byte_container_with_subtype::byte_container_with_subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#parameters","text":"container (in) binary container subtype (in) subtype","title":"Parameters"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","text":"Example The example below demonstrates how byte containers can be created. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { // (1) create empty container auto c1 = byte_container_with_subtype (); std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // (2) create container auto c2 = byte_container_with_subtype ( bytes ); // (3) create container with subtype auto c3 = byte_container_with_subtype ( bytes , 42 ); std :: cout << json ( c1 ) << \" \\n \" << json ( c2 ) << \" \\n \" << json ( c3 ) << std :: endl ; } Output: { \"bytes\" :[], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 }","title":"Examples"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/clear_subtype/","text":"nlohmann::byte_container_with_subtype:: clear_subtype \u00b6 void clear_subtype () noexcept ; 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. Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how clear_subtype can remove subtypes. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container with subtype auto c1 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"before calling clear_subtype(): \" << json ( c1 ) << '\\n' ; c1 . clear_subtype (); std :: cout << \"after calling clear_subtype(): \" << json ( c1 ) << '\\n' ; } Output: be f ore calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } a fter calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } Version history \u00b6 Since version 3.8.0.","title":"clear_subtype"},{"location":"api/byte_container_with_subtype/clear_subtype/#nlohmannbyte_container_with_subtypeclear_subtype","text":"void clear_subtype () noexcept ; 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.","title":"nlohmann::byte_container_with_subtype::clear_subtype"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","text":"Example The example below demonstrates how clear_subtype can remove subtypes. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container with subtype auto c1 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"before calling clear_subtype(): \" << json ( c1 ) << '\\n' ; c1 . clear_subtype (); std :: cout << \"after calling clear_subtype(): \" << json ( c1 ) << '\\n' ; } Output: be f ore calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } a fter calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null }","title":"Examples"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/has_subtype/","text":"nlohmann::byte_container_with_subtype:: has_subtype \u00b6 constexpr bool has_subtype () const noexcept ; Returns whether the value has a subtype. Return value \u00b6 whether the value has a subtype Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how has_subtype can check whether a subtype was set. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << std :: boolalpha << \"c1.has_subtype() = \" << c1 . has_subtype () << \" \\n c2.has_subtype() = \" << c2 . has_subtype () << std :: endl ; } Output: c 1. has_sub t ype() = false c 2. has_sub t ype() = true Version history \u00b6 Since version 3.8.0.","title":"has_subtype"},{"location":"api/byte_container_with_subtype/has_subtype/#nlohmannbyte_container_with_subtypehas_subtype","text":"constexpr bool has_subtype () const noexcept ; Returns whether the value has a subtype.","title":"nlohmann::byte_container_with_subtype::has_subtype"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","text":"whether the value has a subtype","title":"Return value"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","text":"Example The example below demonstrates how has_subtype can check whether a subtype was set. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << std :: boolalpha << \"c1.has_subtype() = \" << c1 . has_subtype () << \" \\n c2.has_subtype() = \" << c2 . has_subtype () << std :: endl ; } Output: c 1. has_sub t ype() = false c 2. has_sub t ype() = true","title":"Examples"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/set_subtype/","text":"nlohmann::byte_container_with_subtype:: set_subtype \u00b6 void set_subtype ( subtype_type subtype ) noexcept ; Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization. Parameters \u00b6 subtype (in) subtype to set Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how a subtype can be set with set_subtype . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container without subtype auto c = byte_container_with_subtype ( bytes ); std :: cout << \"before calling set_subtype(42): \" << json ( c ) << '\\n' ; // set the subtype c . set_subtype ( 42 ); std :: cout << \"after calling set_subtype(42): \" << json ( c ) << '\\n' ; } Output: be f ore calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } a fter calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } Version history \u00b6 Since version 3.8.0.","title":"set_subtype"},{"location":"api/byte_container_with_subtype/set_subtype/#nlohmannbyte_container_with_subtypeset_subtype","text":"void set_subtype ( subtype_type subtype ) noexcept ; Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.","title":"nlohmann::byte_container_with_subtype::set_subtype"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","text":"subtype (in) subtype to set","title":"Parameters"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","text":"Example The example below demonstrates how a subtype can be set with set_subtype . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container without subtype auto c = byte_container_with_subtype ( bytes ); std :: cout << \"before calling set_subtype(42): \" << json ( c ) << '\\n' ; // set the subtype c . set_subtype ( 42 ); std :: cout << \"after calling set_subtype(42): \" << json ( c ) << '\\n' ; } Output: be f ore calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } a fter calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 }","title":"Examples"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/subtype/","text":"nlohmann::byte_container_with_subtype:: subtype \u00b6 constexpr subtype_type subtype () const noexcept ; 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. Return value \u00b6 the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how the subtype can be retrieved with subtype . Note how subtype_type(-1) is returned for container c1 . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"c1.subtype() = \" << c1 . subtype () << \" \\n c2.subtype() = \" << c2 . subtype () << std :: endl ; // in case no subtype is set, return special value assert ( c1 . subtype () == static_cast < byte_container_with_subtype :: subtype_type > ( -1 )); } Output: c 1. sub t ype() = 18446744073709551615 c 2. sub t ype() = 42 Version history \u00b6 Added in version 3.8.0 Fixed return value to properly return subtype_type(-1) as documented in version 3.10.0.","title":"subtype"},{"location":"api/byte_container_with_subtype/subtype/#nlohmannbyte_container_with_subtypesubtype","text":"constexpr subtype_type subtype () const noexcept ; 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.","title":"nlohmann::byte_container_with_subtype::subtype"},{"location":"api/byte_container_with_subtype/subtype/#return-value","text":"the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set","title":"Return value"},{"location":"api/byte_container_with_subtype/subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/subtype/#examples","text":"Example The example below demonstrates how the subtype can be retrieved with subtype . Note how subtype_type(-1) is returned for container c1 . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"c1.subtype() = \" << c1 . subtype () << \" \\n c2.subtype() = \" << c2 . subtype () << std :: endl ; // in case no subtype is set, return special value assert ( c1 . subtype () == static_cast < byte_container_with_subtype :: subtype_type > ( -1 )); } Output: c 1. sub t ype() = 18446744073709551615 c 2. sub t ype() = 42","title":"Examples"},{"location":"api/byte_container_with_subtype/subtype/#version-history","text":"Added in version 3.8.0 Fixed return value to properly return subtype_type(-1) as documented in version 3.10.0.","title":"Version history"},{"location":"api/json_pointer/","text":"nlohmann:: json_pointer \u00b6 template < typename RefStringType > class json_pointer ; 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. Template parameters \u00b6 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. Member types \u00b6 string_t - the string type used for the reference tokens Member functions \u00b6 (constructor) to_string - return a string representation of the JSON pointer operator string_t - return a string representation of the JSON pointer operator== - compare: equal operator!= - compare: not equal operator/= - append to the end of the JSON pointer operator/ - create JSON Pointer by appending parent_pointer - returns the parent of this JSON pointer pop_back - remove last reference token back - return last reference token push_back - append an unescaped token at the end of the pointer empty - return whether pointer points to the root document Literals \u00b6 operator\"\"_json_pointer - user-defined string literal for JSON pointers See also \u00b6 RFC 6901 Version history \u00b6 Added in version 2.0.0. Changed template parameter from basic_json to string type in version 3.11.0.","title":"Overview"},{"location":"api/json_pointer/#nlohmannjson_pointer","text":"template < typename RefStringType > class json_pointer ; 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.","title":"nlohmann::json_pointer"},{"location":"api/json_pointer/#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.","title":"Template parameters"},{"location":"api/json_pointer/#member-types","text":"string_t - the string type used for the reference tokens","title":"Member types"},{"location":"api/json_pointer/#member-functions","text":"(constructor) to_string - return a string representation of the JSON pointer operator string_t - return a string representation of the JSON pointer operator== - compare: equal operator!= - compare: not equal operator/= - append to the end of the JSON pointer operator/ - create JSON Pointer by appending parent_pointer - returns the parent of this JSON pointer pop_back - remove last reference token back - return last reference token push_back - append an unescaped token at the end of the pointer empty - return whether pointer points to the root document","title":"Member functions"},{"location":"api/json_pointer/#literals","text":"operator\"\"_json_pointer - user-defined string literal for JSON pointers","title":"Literals"},{"location":"api/json_pointer/#see-also","text":"RFC 6901","title":"See also"},{"location":"api/json_pointer/#version-history","text":"Added in version 2.0.0. Changed template parameter from basic_json to string type in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/back/","text":"nlohmann::json_pointer:: back \u00b6 const string_t & back () const ; Return last reference token. Return value \u00b6 Last reference token. Exceptions \u00b6 Throws out_of_range.405 if JSON pointer has no parent. Complexity \u00b6 Constant. Examples \u00b6 Example The example shows the usage of back . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo\" ); json :: json_pointer ptr2 ( \"/foo/0\" ); // call empty() std :: cout << \"last reference token of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . back () << \" \\\"\\n \" << \"last reference token of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . back () << \" \\\" \" << std :: endl ; } Output: las t re feren ce t oke n o f \"/foo\" is \"foo\" las t re feren ce t oke n o f \"/foo/0\" is \"0\" Version history \u00b6 Added in version 3.6.0. Changed return type to string_t in version 3.11.0.","title":"back"},{"location":"api/json_pointer/back/#nlohmannjson_pointerback","text":"const string_t & back () const ; Return last reference token.","title":"nlohmann::json_pointer::back"},{"location":"api/json_pointer/back/#return-value","text":"Last reference token.","title":"Return value"},{"location":"api/json_pointer/back/#exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.","title":"Exceptions"},{"location":"api/json_pointer/back/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/json_pointer/back/#examples","text":"Example The example shows the usage of back . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo\" ); json :: json_pointer ptr2 ( \"/foo/0\" ); // call empty() std :: cout << \"last reference token of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . back () << \" \\\"\\n \" << \"last reference token of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . back () << \" \\\" \" << std :: endl ; } Output: las t re feren ce t oke n o f \"/foo\" is \"foo\" las t re feren ce t oke n o f \"/foo/0\" is \"0\"","title":"Examples"},{"location":"api/json_pointer/back/#version-history","text":"Added in version 3.6.0. Changed return type to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/empty/","text":"nlohmann::json_pointer:: empty \u00b6 bool empty () const noexcept ; Return whether pointer points to the root document. Return value \u00b6 true iff the JSON pointer points to the root document. Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example shows the result of empty for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call empty() std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" : \" << ptr0 . empty () << '\\n' << \" \\\" \" << ptr1 << \" \\\" : \" << ptr1 . empty () << '\\n' << \" \\\" \" << ptr2 << \" \\\" : \" << ptr2 . empty () << '\\n' << \" \\\" \" << ptr3 << \" \\\" : \" << ptr3 . empty () << std :: endl ; } Output: \"\" : true \"\" : true \"/foo\" : false \"/foo/0\" : false Version history \u00b6 Added in version 3.6.0.","title":"empty"},{"location":"api/json_pointer/empty/#nlohmannjson_pointerempty","text":"bool empty () const noexcept ; Return whether pointer points to the root document.","title":"nlohmann::json_pointer::empty"},{"location":"api/json_pointer/empty/#return-value","text":"true iff the JSON pointer points to the root document.","title":"Return value"},{"location":"api/json_pointer/empty/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/json_pointer/empty/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/json_pointer/empty/#examples","text":"Example The example shows the result of empty for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call empty() std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" : \" << ptr0 . empty () << '\\n' << \" \\\" \" << ptr1 << \" \\\" : \" << ptr1 . empty () << '\\n' << \" \\\" \" << ptr2 << \" \\\" : \" << ptr2 . empty () << '\\n' << \" \\\" \" << ptr3 << \" \\\" : \" << ptr3 . empty () << std :: endl ; } Output: \"\" : true \"\" : true \"/foo\" : false \"/foo/0\" : false","title":"Examples"},{"location":"api/json_pointer/empty/#version-history","text":"Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/json_pointer/","text":"nlohmann::json_pointer:: json_pointer \u00b6 explicit json_pointer ( const string_t & s = \"\" ); Create a JSON pointer according to the syntax described in Section 3 of RFC6901 . Parameters \u00b6 s (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value Exceptions \u00b6 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. Examples \u00b6 Example The example shows the construction several valid JSON pointers as well as the exceptional behavior. #include #include using json = nlohmann :: json ; int main () { // correct JSON pointers json :: json_pointer p1 ; json :: json_pointer p2 ( \"\" ); json :: json_pointer p3 ( \"/\" ); json :: json_pointer p4 ( \"//\" ); json :: json_pointer p5 ( \"/foo/bar\" ); json :: json_pointer p6 ( \"/foo/bar/-\" ); json :: json_pointer p7 ( \"/foo/~0\" ); json :: json_pointer p8 ( \"/foo/~1\" ); // error: JSON pointer does not begin with a slash try { json :: json_pointer p9 ( \"foo\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p10 ( \"/foo/~\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p11 ( \"/foo/~3\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ jso n .excep t io n .parse_error. 107 ] parse error a t by te 1 : JSON poi nter mus t be emp t y or begi n wi t h '/' - was : ' f oo' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 ' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 ' Version history \u00b6 Added in version 2.0.0. Changed type of s to string_t in version 3.11.0.","title":"(Constructor)"},{"location":"api/json_pointer/json_pointer/#nlohmannjson_pointerjson_pointer","text":"explicit json_pointer ( const string_t & s = \"\" ); Create a JSON pointer according to the syntax described in Section 3 of RFC6901 .","title":"nlohmann::json_pointer::json_pointer"},{"location":"api/json_pointer/json_pointer/#parameters","text":"s (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value","title":"Parameters"},{"location":"api/json_pointer/json_pointer/#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.","title":"Exceptions"},{"location":"api/json_pointer/json_pointer/#examples","text":"Example The example shows the construction several valid JSON pointers as well as the exceptional behavior. #include #include using json = nlohmann :: json ; int main () { // correct JSON pointers json :: json_pointer p1 ; json :: json_pointer p2 ( \"\" ); json :: json_pointer p3 ( \"/\" ); json :: json_pointer p4 ( \"//\" ); json :: json_pointer p5 ( \"/foo/bar\" ); json :: json_pointer p6 ( \"/foo/bar/-\" ); json :: json_pointer p7 ( \"/foo/~0\" ); json :: json_pointer p8 ( \"/foo/~1\" ); // error: JSON pointer does not begin with a slash try { json :: json_pointer p9 ( \"foo\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p10 ( \"/foo/~\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p11 ( \"/foo/~3\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ jso n .excep t io n .parse_error. 107 ] parse error a t by te 1 : JSON poi nter mus t be emp t y or begi n wi t h '/' - was : ' f oo' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 ' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 '","title":"Examples"},{"location":"api/json_pointer/json_pointer/#version-history","text":"Added in version 2.0.0. Changed type of s to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/operator_eq/","text":"nlohmann::json_pointer:: operator== \u00b6 // until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator == ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) // since C++20 class json_pointer { template < typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeRhs >& rhs ) const noexcept ; // (1) bool operator == ( const string_t & rhs ) const ; // (2) }; 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. Template parameters \u00b6 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 ) Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 (none) The function can throw the following exceptions: 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. Complexity \u00b6 Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens. Notes \u00b6 Deprecation Overload 2 is deprecated and will be removed in a future major version release. Examples \u00b6 Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 == ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 == ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 == ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 == ptr2 ) << std :: endl ; } Output: \"\" == \"\": true \"\" == \"\": true \"\" == \"/foo\": false \"/foo\" == \"/foo\": true Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << str0 << \" \\\" : \" << ( ptr0 == str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( str0 == ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << str1 << \" \\\" : \" << ( ptr2 == str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( str2 == ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" == \"\": true \"\" == \"\": true \"/foo\" == \"/foo\": true \"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar' Version history \u00b6 Added in version 2.1.0. Added C++20 member functions in version 3.11.2. Added for backward compatibility and deprecated in version 3.11.2.","title":"operator=="},{"location":"api/json_pointer/operator_eq/#nlohmannjson_pointeroperator","text":"// until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator == ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) // since C++20 class json_pointer { template < typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeRhs >& rhs ) const noexcept ; // (1) bool operator == ( const string_t & rhs ) const ; // (2) }; 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.","title":"nlohmann::json_pointer::operator=="},{"location":"api/json_pointer/operator_eq/#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 )","title":"Template parameters"},{"location":"api/json_pointer/operator_eq/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/json_pointer/operator_eq/#return-value","text":"whether the values lhs / *this and rhs are equal","title":"Return value"},{"location":"api/json_pointer/operator_eq/#exception-safety","text":"No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/json_pointer/operator_eq/#exceptions","text":"(none) The function can throw the following exceptions: 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.","title":"Exceptions"},{"location":"api/json_pointer/operator_eq/#complexity","text":"Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.","title":"Complexity"},{"location":"api/json_pointer/operator_eq/#notes","text":"Deprecation Overload 2 is deprecated and will be removed in a future major version release.","title":"Notes"},{"location":"api/json_pointer/operator_eq/#examples","text":"Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 == ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 == ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 == ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 == ptr2 ) << std :: endl ; } Output: \"\" == \"\": true \"\" == \"\": true \"\" == \"/foo\": false \"/foo\" == \"/foo\": true Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << str0 << \" \\\" : \" << ( ptr0 == str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( str0 == ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << str1 << \" \\\" : \" << ( ptr2 == str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( str2 == ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" == \"\": true \"\" == \"\": true \"/foo\" == \"/foo\": true \"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'","title":"Examples"},{"location":"api/json_pointer/operator_eq/#version-history","text":"Added in version 2.1.0. Added C++20 member functions in version 3.11.2. Added for backward compatibility and deprecated in version 3.11.2.","title":"Version history"},{"location":"api/json_pointer/operator_ne/","text":"nlohmann::json_pointer:: operator!= \u00b6 // until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator != ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) 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. Template parameters \u00b6 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 ) Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are not equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 (none) The function can throw the following exceptions: 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. Complexity \u00b6 Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens. Notes \u00b6 Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator== . Deprecation Overload 2 is deprecated and will be removed in a future major version release. Examples \u00b6 Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 != ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 != ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 != ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 != ptr2 ) << std :: endl ; } Output: \"\" != \"\": false \"\" != \"\": false \"\" != \"/foo\": true \"/foo\" != \"/foo\": false Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << str0 << \" \\\" : \" << ( ptr0 != str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( str0 != ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << str1 << \" \\\" : \" << ( ptr2 != str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( str2 != ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" != \"\": false \"\" != \"\": false \"/foo\" != \"/foo\": false \"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar' Version history \u00b6 Added in version 2.1.0. Added for backward compatibility and deprecated in version 3.11.2.","title":"operator!="},{"location":"api/json_pointer/operator_ne/#nlohmannjson_pointeroperator","text":"// until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator != ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) 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.","title":"nlohmann::json_pointer::operator!="},{"location":"api/json_pointer/operator_ne/#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 )","title":"Template parameters"},{"location":"api/json_pointer/operator_ne/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/json_pointer/operator_ne/#return-value","text":"whether the values lhs / *this and rhs are not equal","title":"Return value"},{"location":"api/json_pointer/operator_ne/#exception-safety","text":"No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/json_pointer/operator_ne/#exceptions","text":"(none) The function can throw the following exceptions: 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.","title":"Exceptions"},{"location":"api/json_pointer/operator_ne/#complexity","text":"Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.","title":"Complexity"},{"location":"api/json_pointer/operator_ne/#notes","text":"Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator== . Deprecation Overload 2 is deprecated and will be removed in a future major version release.","title":"Notes"},{"location":"api/json_pointer/operator_ne/#examples","text":"Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 != ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 != ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 != ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 != ptr2 ) << std :: endl ; } Output: \"\" != \"\": false \"\" != \"\": false \"\" != \"/foo\": true \"/foo\" != \"/foo\": false Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << str0 << \" \\\" : \" << ( ptr0 != str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( str0 != ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << str1 << \" \\\" : \" << ( ptr2 != str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( str2 != ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" != \"\": false \"\" != \"\": false \"/foo\" != \"/foo\": false \"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'","title":"Examples"},{"location":"api/json_pointer/operator_ne/#version-history","text":"Added in version 2.1.0. Added for backward compatibility and deprecated in version 3.11.2.","title":"Version history"},{"location":"api/json_pointer/operator_slash/","text":"nlohmann::json_pointer:: operator/ \u00b6 // (1) json_pointer operator / ( const json_pointer & lhs , const json_pointer & rhs ); // (2) json_pointer operator / ( const json_pointer & lhs , string_t token ); // (3) json_pointer operator / ( const json_pointer & lhs , std :: size_t array_idx ); create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer create a new JSON pointer by appending the unescaped token at the end of the JSON pointer create a new JSON pointer by appending the array-index-token at the end of the JSON pointer Parameters \u00b6 lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append Return value \u00b6 a new JSON pointer with rhs appended to lhs a new JSON pointer with unescaped token appended to lhs a new JSON pointer with array_idx appended to lhs Complexity \u00b6 Linear in the length of lhs and rhs . Linear in the length of lhs . Linear in the length of lhs . Examples \u00b6 Example The example shows the usage of operator/ . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); // append a JSON Pointer std :: cout << \" \\\" \" << ptr / json :: json_pointer ( \"/bar/baz\" ) << \" \\\"\\n \" ; // append a string std :: cout << \" \\\" \" << ptr / \"fob\" << \" \\\"\\n \" ; // append an array index std :: cout << \" \\\" \" << ptr / 42 << \" \\\" \" << std :: endl ; } Output: \"/foo/bar/baz\" \"/foo/fob\" \"/foo/42\" Version history \u00b6 Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"operator/"},{"location":"api/json_pointer/operator_slash/#nlohmannjson_pointeroperator","text":"// (1) json_pointer operator / ( const json_pointer & lhs , const json_pointer & rhs ); // (2) json_pointer operator / ( const json_pointer & lhs , string_t token ); // (3) json_pointer operator / ( const json_pointer & lhs , std :: size_t array_idx ); create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer create a new JSON pointer by appending the unescaped token at the end of the JSON pointer create a new JSON pointer by appending the array-index-token at the end of the JSON pointer","title":"nlohmann::json_pointer::operator/"},{"location":"api/json_pointer/operator_slash/#parameters","text":"lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append","title":"Parameters"},{"location":"api/json_pointer/operator_slash/#return-value","text":"a new JSON pointer with rhs appended to lhs a new JSON pointer with unescaped token appended to lhs a new JSON pointer with array_idx appended to lhs","title":"Return value"},{"location":"api/json_pointer/operator_slash/#complexity","text":"Linear in the length of lhs and rhs . Linear in the length of lhs . Linear in the length of lhs .","title":"Complexity"},{"location":"api/json_pointer/operator_slash/#examples","text":"Example The example shows the usage of operator/ . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); // append a JSON Pointer std :: cout << \" \\\" \" << ptr / json :: json_pointer ( \"/bar/baz\" ) << \" \\\"\\n \" ; // append a string std :: cout << \" \\\" \" << ptr / \"fob\" << \" \\\"\\n \" ; // append an array index std :: cout << \" \\\" \" << ptr / 42 << \" \\\" \" << std :: endl ; } Output: \"/foo/bar/baz\" \"/foo/fob\" \"/foo/42\"","title":"Examples"},{"location":"api/json_pointer/operator_slash/#version-history","text":"Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/operator_slasheq/","text":"nlohmann::json_pointer:: operator/= \u00b6 // (1) json_pointer & operator /= ( const json_pointer & ptr ); // (2) json_pointer & operator /= ( string_t token ); // (3) json_pointer & operator /= ( std :: size_t array_idx ) 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 Parameters \u00b6 ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append Return value \u00b6 JSON pointer with ptr appended JSON pointer with token appended without escaping token JSON pointer with array_idx appended Complexity \u00b6 Linear in the length of ptr . Amortized constant. Amortized constant. Examples \u00b6 Example The example shows the usage of operator/= . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a JSON Pointer ptr /= json :: json_pointer ( \"/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a string ptr /= \"fob\" ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append an array index ptr /= 42 ; std :: cout << \" \\\" \" << ptr << \" \\\" \" << std :: endl ; } Output: \"/foo\" \"/foo/bar/baz\" \"/foo/bar/baz/fob\" \"/foo/bar/baz/fob/42\" Version history \u00b6 Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"operator/="},{"location":"api/json_pointer/operator_slasheq/#nlohmannjson_pointeroperator","text":"// (1) json_pointer & operator /= ( const json_pointer & ptr ); // (2) json_pointer & operator /= ( string_t token ); // (3) json_pointer & operator /= ( std :: size_t array_idx ) 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","title":"nlohmann::json_pointer::operator/="},{"location":"api/json_pointer/operator_slasheq/#parameters","text":"ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append","title":"Parameters"},{"location":"api/json_pointer/operator_slasheq/#return-value","text":"JSON pointer with ptr appended JSON pointer with token appended without escaping token JSON pointer with array_idx appended","title":"Return value"},{"location":"api/json_pointer/operator_slasheq/#complexity","text":"Linear in the length of ptr . Amortized constant. Amortized constant.","title":"Complexity"},{"location":"api/json_pointer/operator_slasheq/#examples","text":"Example The example shows the usage of operator/= . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a JSON Pointer ptr /= json :: json_pointer ( \"/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a string ptr /= \"fob\" ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append an array index ptr /= 42 ; std :: cout << \" \\\" \" << ptr << \" \\\" \" << std :: endl ; } Output: \"/foo\" \"/foo/bar/baz\" \"/foo/bar/baz/fob\" \"/foo/bar/baz/fob/42\"","title":"Examples"},{"location":"api/json_pointer/operator_slasheq/#version-history","text":"Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/operator_string_t/","text":"nlohmann::json_pointer:: operator string_t \u00b6 operator string_t () const Return a string representation of the JSON pointer. Return value \u00b6 A string representation of the JSON pointer Possible implementation \u00b6 operator string_t () const { return to_string (); } Notes \u00b6 Deprecation This function is deprecated in favor of to_string and will be removed in a future major version release. Examples \u00b6 Example The example shows how JSON Pointers can be implicitly converted to strings. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo/0\" ); json :: json_pointer ptr2 ( \"/a~1b\" ); // implicit conversion to string std :: string s ; s += ptr1 ; s += \" \\n \" ; s += ptr2 ; std :: cout << s << std :: endl ; } Output: / f oo/ 0 /a~ 1 b Version history \u00b6 Since version 2.0.0. Changed type to string_t and deprecated in version 3.11.0.","title":"operator string_t"},{"location":"api/json_pointer/operator_string_t/#nlohmannjson_pointeroperator-string_t","text":"operator string_t () const Return a string representation of the JSON pointer.","title":"nlohmann::json_pointer::operator string_t"},{"location":"api/json_pointer/operator_string_t/#return-value","text":"A string representation of the JSON pointer","title":"Return value"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","text":"operator string_t () const { return to_string (); }","title":"Possible implementation"},{"location":"api/json_pointer/operator_string_t/#notes","text":"Deprecation This function is deprecated in favor of to_string and will be removed in a future major version release.","title":"Notes"},{"location":"api/json_pointer/operator_string_t/#examples","text":"Example The example shows how JSON Pointers can be implicitly converted to strings. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo/0\" ); json :: json_pointer ptr2 ( \"/a~1b\" ); // implicit conversion to string std :: string s ; s += ptr1 ; s += \" \\n \" ; s += ptr2 ; std :: cout << s << std :: endl ; } Output: / f oo/ 0 /a~ 1 b","title":"Examples"},{"location":"api/json_pointer/operator_string_t/#version-history","text":"Since version 2.0.0. Changed type to string_t and deprecated in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/parent_pointer/","text":"nlohmann::json_pointer:: parent_pointer \u00b6 json_pointer parent_pointer () const ; Returns the parent of this JSON pointer. Return value \u00b6 Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned. Complexity \u00b6 Linear in the length of the JSON pointer. Examples \u00b6 Example The example shows the result of parent_pointer for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call parent_pointer() std :: cout << std :: boolalpha << \"parent of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr3 << \" \\\" is \\\" \" << ptr3 . parent_pointer () << \" \\\" \" << std :: endl ; } Output: pare nt o f \"\" is \"\" pare nt o f \"/foo\" is \"\" pare nt o f \"/foo/0\" is \"/foo\" Version history \u00b6 Added in version 3.6.0.","title":"parent_pointer"},{"location":"api/json_pointer/parent_pointer/#nlohmannjson_pointerparent_pointer","text":"json_pointer parent_pointer () const ; Returns the parent of this JSON pointer.","title":"nlohmann::json_pointer::parent_pointer"},{"location":"api/json_pointer/parent_pointer/#return-value","text":"Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.","title":"Return value"},{"location":"api/json_pointer/parent_pointer/#complexity","text":"Linear in the length of the JSON pointer.","title":"Complexity"},{"location":"api/json_pointer/parent_pointer/#examples","text":"Example The example shows the result of parent_pointer for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call parent_pointer() std :: cout << std :: boolalpha << \"parent of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr3 << \" \\\" is \\\" \" << ptr3 . parent_pointer () << \" \\\" \" << std :: endl ; } Output: pare nt o f \"\" is \"\" pare nt o f \"/foo\" is \"\" pare nt o f \"/foo/0\" is \"/foo\"","title":"Examples"},{"location":"api/json_pointer/parent_pointer/#version-history","text":"Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/pop_back/","text":"nlohmann::json_pointer:: pop_back \u00b6 void pop_back (); Remove last reference token. Exceptions \u00b6 Throws out_of_range.405 if JSON pointer has no parent. Complexity \u00b6 Constant. Examples \u00b6 Example The example shows the usage of pop_back . #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ( \"/foo/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call pop_back() ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"/foo/bar/baz\" \"/foo/bar\" \"/foo\" \"\" Version history \u00b6 Added in version 3.6.0.","title":"pop_back"},{"location":"api/json_pointer/pop_back/#nlohmannjson_pointerpop_back","text":"void pop_back (); Remove last reference token.","title":"nlohmann::json_pointer::pop_back"},{"location":"api/json_pointer/pop_back/#exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.","title":"Exceptions"},{"location":"api/json_pointer/pop_back/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/json_pointer/pop_back/#examples","text":"Example The example shows the usage of pop_back . #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ( \"/foo/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call pop_back() ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"/foo/bar/baz\" \"/foo/bar\" \"/foo\" \"\"","title":"Examples"},{"location":"api/json_pointer/pop_back/#version-history","text":"Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/push_back/","text":"nlohmann::json_pointer:: push_back \u00b6 void push_back ( const string_t & token ); void push_back ( string_t && token ); Append an unescaped token at the end of the reference pointer. Parameters \u00b6 token (in) token to add Complexity \u00b6 Amortized constant. Examples \u00b6 Example The example shows the result of push_back for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call push_back() ptr . push_back ( \"foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"0\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"bar\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"\" \"/foo\" \"/foo/0\" \"/foo/0/bar\" Version history \u00b6 Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.","title":"push_back"},{"location":"api/json_pointer/push_back/#nlohmannjson_pointerpush_back","text":"void push_back ( const string_t & token ); void push_back ( string_t && token ); Append an unescaped token at the end of the reference pointer.","title":"nlohmann::json_pointer::push_back"},{"location":"api/json_pointer/push_back/#parameters","text":"token (in) token to add","title":"Parameters"},{"location":"api/json_pointer/push_back/#complexity","text":"Amortized constant.","title":"Complexity"},{"location":"api/json_pointer/push_back/#examples","text":"Example The example shows the result of push_back for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call push_back() ptr . push_back ( \"foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"0\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"bar\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"\" \"/foo\" \"/foo/0\" \"/foo/0/bar\"","title":"Examples"},{"location":"api/json_pointer/push_back/#version-history","text":"Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/string_t/","text":"nlohmann::json_pointer:: string_t \u00b6 using string_t = RefStringType ; The string type used for the reference tokens making up the JSON pointer. See basic_json::string_t for more information. Examples \u00b6 Example The example shows the type string_t and its relation to basic_json::string_t . #include #include using json = nlohmann :: json ; int main () { json :: json_pointer :: string_t s = \"This is a string.\" ; std :: cout << s << std :: endl ; std :: cout << std :: boolalpha << std :: is_same < json :: json_pointer :: string_t , json :: string_t >:: value << std :: endl ; } Output: This is a s tr i n g. true Version history \u00b6 Added in version 3.11.0.","title":"string_t"},{"location":"api/json_pointer/string_t/#nlohmannjson_pointerstring_t","text":"using string_t = RefStringType ; The string type used for the reference tokens making up the JSON pointer. See basic_json::string_t for more information.","title":"nlohmann::json_pointer::string_t"},{"location":"api/json_pointer/string_t/#examples","text":"Example The example shows the type string_t and its relation to basic_json::string_t . #include #include using json = nlohmann :: json ; int main () { json :: json_pointer :: string_t s = \"This is a string.\" ; std :: cout << s << std :: endl ; std :: cout << std :: boolalpha << std :: is_same < json :: json_pointer :: string_t , json :: string_t >:: value << std :: endl ; } Output: This is a s tr i n g. true","title":"Examples"},{"location":"api/json_pointer/string_t/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/to_string/","text":"nlohmann::json_pointer:: to_string \u00b6 string_t to_string () const ; Return a string representation of the JSON pointer. Return value \u00b6 A string representation of the JSON pointer Notes \u00b6 For each JSON pointer ptr , it holds: ptr == json_pointer ( ptr . to_string ()); Examples \u00b6 Example The example shows the result of to_string . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); json :: json_pointer ptr4 ( \"/\" ); json :: json_pointer ptr5 ( \"/a~1b\" ); json :: json_pointer ptr6 ( \"/c%d\" ); json :: json_pointer ptr7 ( \"/e^f\" ); json :: json_pointer ptr8 ( \"/g|h\" ); json :: json_pointer ptr9 ( \"/i \\\\ j\" ); json :: json_pointer ptr10 ( \"/k \\\" l\" ); json :: json_pointer ptr11 ( \"/ \" ); json :: json_pointer ptr12 ( \"/m~0n\" ); std :: cout << \" \\\" \" << ptr1 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr2 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr3 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr4 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr5 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr6 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr7 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr8 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr9 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr10 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr11 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr12 . to_string () << \" \\\" \" << std :: endl ; } Output: \"\" \"/foo\" \"/foo/0\" \"/\" \"/a~1b\" \"/c%d\" \"/e^f\" \"/g|h\" \"/i\\j\" \"/k\" l \" \" / \" \" /m~ 0 n \" Version history \u00b6 Since version 2.0.0. Changed return type to string_t in version 3.11.0.","title":"to_string"},{"location":"api/json_pointer/to_string/#nlohmannjson_pointerto_string","text":"string_t to_string () const ; Return a string representation of the JSON pointer.","title":"nlohmann::json_pointer::to_string"},{"location":"api/json_pointer/to_string/#return-value","text":"A string representation of the JSON pointer","title":"Return value"},{"location":"api/json_pointer/to_string/#notes","text":"For each JSON pointer ptr , it holds: ptr == json_pointer ( ptr . to_string ());","title":"Notes"},{"location":"api/json_pointer/to_string/#examples","text":"Example The example shows the result of to_string . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); json :: json_pointer ptr4 ( \"/\" ); json :: json_pointer ptr5 ( \"/a~1b\" ); json :: json_pointer ptr6 ( \"/c%d\" ); json :: json_pointer ptr7 ( \"/e^f\" ); json :: json_pointer ptr8 ( \"/g|h\" ); json :: json_pointer ptr9 ( \"/i \\\\ j\" ); json :: json_pointer ptr10 ( \"/k \\\" l\" ); json :: json_pointer ptr11 ( \"/ \" ); json :: json_pointer ptr12 ( \"/m~0n\" ); std :: cout << \" \\\" \" << ptr1 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr2 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr3 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr4 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr5 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr6 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr7 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr8 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr9 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr10 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr11 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr12 . to_string () << \" \\\" \" << std :: endl ; } Output: \"\" \"/foo\" \"/foo/0\" \"/\" \"/a~1b\" \"/c%d\" \"/e^f\" \"/g|h\" \"/i\\j\" \"/k\" l \" \" / \" \" /m~ 0 n \"","title":"Examples"},{"location":"api/json_pointer/to_string/#version-history","text":"Since version 2.0.0. Changed return type to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_sax/","text":"nlohmann:: json_sax \u00b6 template < typename BasicJsonType > struct json_sax ; 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. Template parameters \u00b6 BasicJsonType a specialization of basic_json Member types \u00b6 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) string_t - BasicJsonType 's type for strings binary_t - BasicJsonType 's type for binary arrays Member functions \u00b6 binary ( virtual ) - a binary value was read boolean ( virtual ) - a boolean value was read end_array ( virtual ) - the end of an array was read end_object ( virtual ) - the end of an object was read key ( virtual ) - an object key was read null ( virtual ) - a null value was read number_float ( virtual ) - a floating-point number was read number_integer ( virtual ) - an integer number was read number_unsigned ( virtual ) - an unsigned integer number was read parse_error ( virtual ) - a parse error occurred start_array ( virtual ) - the beginning of an array was read start_object ( virtual ) - the beginning of an object was read string ( virtual ) - a string value was read Version history \u00b6 Added in version 3.2.0. Support for binary values ( binary_t , binary ) added in version 3.8.0.","title":"Overview"},{"location":"api/json_sax/#nlohmannjson_sax","text":"template < typename BasicJsonType > struct json_sax ; 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.","title":"nlohmann::json_sax"},{"location":"api/json_sax/#template-parameters","text":"BasicJsonType a specialization of basic_json","title":"Template parameters"},{"location":"api/json_sax/#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) string_t - BasicJsonType 's type for strings binary_t - BasicJsonType 's type for binary arrays","title":"Member types"},{"location":"api/json_sax/#member-functions","text":"binary ( virtual ) - a binary value was read boolean ( virtual ) - a boolean value was read end_array ( virtual ) - the end of an array was read end_object ( virtual ) - the end of an object was read key ( virtual ) - an object key was read null ( virtual ) - a null value was read number_float ( virtual ) - a floating-point number was read number_integer ( virtual ) - an integer number was read number_unsigned ( virtual ) - an unsigned integer number was read parse_error ( virtual ) - a parse error occurred start_array ( virtual ) - the beginning of an array was read start_object ( virtual ) - the beginning of an object was read string ( virtual ) - a string value was read","title":"Member functions"},{"location":"api/json_sax/#version-history","text":"Added in version 3.2.0. Support for binary values ( binary_t , binary ) added in version 3.8.0.","title":"Version history"},{"location":"api/json_sax/binary/","text":"nlohmann::json_sax:: binary \u00b6 virtual bool binary ( binary_t & val ) = 0 ; A binary value was read. Parameters \u00b6 val (in) binary value Return value \u00b6 Whether parsing should proceed. Notes \u00b6 It is safe to move the passed binary value. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true Version history \u00b6 Added in version 3.8.0.","title":"binary"},{"location":"api/json_sax/binary/#nlohmannjson_saxbinary","text":"virtual bool binary ( binary_t & val ) = 0 ; A binary value was read.","title":"nlohmann::json_sax::binary"},{"location":"api/json_sax/binary/#parameters","text":"val (in) binary value","title":"Parameters"},{"location":"api/json_sax/binary/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/binary/#notes","text":"It is safe to move the passed binary value.","title":"Notes"},{"location":"api/json_sax/binary/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true","title":"Examples"},{"location":"api/json_sax/binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/json_sax/boolean/","text":"nlohmann::json_sax:: boolean \u00b6 virtual bool boolean ( bool val ) = 0 ; A boolean value was read. Parameters \u00b6 val (in) boolean value Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"boolean"},{"location":"api/json_sax/boolean/#nlohmannjson_saxboolean","text":"virtual bool boolean ( bool val ) = 0 ; A boolean value was read.","title":"nlohmann::json_sax::boolean"},{"location":"api/json_sax/boolean/#parameters","text":"val (in) boolean value","title":"Parameters"},{"location":"api/json_sax/boolean/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/boolean/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/boolean/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/end_array/","text":"nlohmann::json_sax:: end_array \u00b6 virtual bool end_array () = 0 ; The end of an array was read. Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"end_array"},{"location":"api/json_sax/end_array/#nlohmannjson_saxend_array","text":"virtual bool end_array () = 0 ; The end of an array was read.","title":"nlohmann::json_sax::end_array"},{"location":"api/json_sax/end_array/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/end_array/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/end_array/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/end_object/","text":"nlohmann::json_sax:: end_object \u00b6 virtual bool end_object () = 0 ; The end of an object was read. Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"end_object"},{"location":"api/json_sax/end_object/#nlohmannjson_saxend_object","text":"virtual bool end_object () = 0 ; The end of an object was read.","title":"nlohmann::json_sax::end_object"},{"location":"api/json_sax/end_object/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/end_object/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/end_object/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/key/","text":"nlohmann::json_sax:: key \u00b6 virtual bool key ( string_t & val ) = 0 ; An object key was read. Parameters \u00b6 val (in) object key Return value \u00b6 Whether parsing should proceed. Notes \u00b6 It is safe to move the passed object key value. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"key"},{"location":"api/json_sax/key/#nlohmannjson_saxkey","text":"virtual bool key ( string_t & val ) = 0 ; An object key was read.","title":"nlohmann::json_sax::key"},{"location":"api/json_sax/key/#parameters","text":"val (in) object key","title":"Parameters"},{"location":"api/json_sax/key/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/key/#notes","text":"It is safe to move the passed object key value.","title":"Notes"},{"location":"api/json_sax/key/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/key/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/null/","text":"nlohmann::json_sax:: null \u00b6 virtual bool null () = 0 ; A null value was read. Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"null"},{"location":"api/json_sax/null/#nlohmannjson_saxnull","text":"virtual bool null () = 0 ; A null value was read.","title":"nlohmann::json_sax::null"},{"location":"api/json_sax/null/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/null/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/null/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/number_float/","text":"nlohmann::json_sax:: number_float \u00b6 virtual bool number_float ( number_float_t val , const string_t & s ) = 0 ; A floating-point number was read. Parameters \u00b6 val (in) floating-point value s (in) string representation of the original input Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"number_float"},{"location":"api/json_sax/number_float/#nlohmannjson_saxnumber_float","text":"virtual bool number_float ( number_float_t val , const string_t & s ) = 0 ; A floating-point number was read.","title":"nlohmann::json_sax::number_float"},{"location":"api/json_sax/number_float/#parameters","text":"val (in) floating-point value s (in) string representation of the original input","title":"Parameters"},{"location":"api/json_sax/number_float/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/number_float/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/number_float/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/number_integer/","text":"nlohmann::json_sax:: number_integer \u00b6 virtual bool number_integer ( number_integer_t val ) = 0 ; An integer number was read. Parameters \u00b6 val (in) integer value Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"number_integer"},{"location":"api/json_sax/number_integer/#nlohmannjson_saxnumber_integer","text":"virtual bool number_integer ( number_integer_t val ) = 0 ; An integer number was read.","title":"nlohmann::json_sax::number_integer"},{"location":"api/json_sax/number_integer/#parameters","text":"val (in) integer value","title":"Parameters"},{"location":"api/json_sax/number_integer/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/number_integer/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/number_integer/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/number_unsigned/","text":"nlohmann::json_sax:: number_unsigned \u00b6 virtual bool number_unsigned ( number_unsigned_t val ) = 0 ; An unsigned integer number was read. Parameters \u00b6 val (in) unsigned integer value Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"number_unsigned"},{"location":"api/json_sax/number_unsigned/#nlohmannjson_saxnumber_unsigned","text":"virtual bool number_unsigned ( number_unsigned_t val ) = 0 ; An unsigned integer number was read.","title":"nlohmann::json_sax::number_unsigned"},{"location":"api/json_sax/number_unsigned/#parameters","text":"val (in) unsigned integer value","title":"Parameters"},{"location":"api/json_sax/number_unsigned/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/number_unsigned/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/number_unsigned/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/parse_error/","text":"nlohmann::json_sax:: parse_error \u00b6 virtual bool parse_error ( std :: size_t position , const std :: string & last_token , const detail :: exception & ex ) = 0 ; A parse error occurred. Parameters \u00b6 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 Return value \u00b6 Whether parsing should proceed ( must return false ). Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"parse_error"},{"location":"api/json_sax/parse_error/#nlohmannjson_saxparse_error","text":"virtual bool parse_error ( std :: size_t position , const std :: string & last_token , const detail :: exception & ex ) = 0 ; A parse error occurred.","title":"nlohmann::json_sax::parse_error"},{"location":"api/json_sax/parse_error/#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","title":"Parameters"},{"location":"api/json_sax/parse_error/#return-value","text":"Whether parsing should proceed ( must return false ).","title":"Return value"},{"location":"api/json_sax/parse_error/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/parse_error/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/start_array/","text":"nlohmann::json_sax:: start_array \u00b6 virtual bool start_array ( std :: size_t elements ) = 0 ; The beginning of an array was read. Parameters \u00b6 elements (in) number of object elements or -1 if unknown Return value \u00b6 Whether parsing should proceed. Notes \u00b6 Binary formats may report the number of elements. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"start_array"},{"location":"api/json_sax/start_array/#nlohmannjson_saxstart_array","text":"virtual bool start_array ( std :: size_t elements ) = 0 ; The beginning of an array was read.","title":"nlohmann::json_sax::start_array"},{"location":"api/json_sax/start_array/#parameters","text":"elements (in) number of object elements or -1 if unknown","title":"Parameters"},{"location":"api/json_sax/start_array/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/start_array/#notes","text":"Binary formats may report the number of elements.","title":"Notes"},{"location":"api/json_sax/start_array/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/start_array/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/start_object/","text":"nlohmann::json_sax:: start_object \u00b6 virtual bool start_object ( std :: size_t elements ) = 0 ; The beginning of an object was read. Parameters \u00b6 elements (in) number of object elements or -1 if unknown Return value \u00b6 Whether parsing should proceed. Notes \u00b6 Binary formats may report the number of elements. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"start_object"},{"location":"api/json_sax/start_object/#nlohmannjson_saxstart_object","text":"virtual bool start_object ( std :: size_t elements ) = 0 ; The beginning of an object was read.","title":"nlohmann::json_sax::start_object"},{"location":"api/json_sax/start_object/#parameters","text":"elements (in) number of object elements or -1 if unknown","title":"Parameters"},{"location":"api/json_sax/start_object/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/start_object/#notes","text":"Binary formats may report the number of elements.","title":"Notes"},{"location":"api/json_sax/start_object/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/start_object/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/string/","text":"nlohmann::json_sax:: string \u00b6 virtual bool string ( string_t & val ) = 0 ; A string value was read. Parameters \u00b6 val (in) string value Return value \u00b6 Whether parsing should proceed. Notes \u00b6 It is safe to move the passed string value. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"string"},{"location":"api/json_sax/string/#nlohmannjson_saxstring","text":"virtual bool string ( string_t & val ) = 0 ; A string value was read.","title":"nlohmann::json_sax::string"},{"location":"api/json_sax/string/#parameters","text":"val (in) string value","title":"Parameters"},{"location":"api/json_sax/string/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/string/#notes","text":"It is safe to move the passed string value.","title":"Notes"},{"location":"api/json_sax/string/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/string/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/macros/","text":"Macros \u00b6 Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page . Runtime assertions \u00b6 JSON_ASSERT(x) - control behavior of runtime assertions Exceptions \u00b6 JSON_CATCH_USER(exception) JSON_THROW_USER(exception) JSON_TRY_USER - control exceptions JSON_DIAGNOSTICS - control extended diagnostics JSON_NOEXCEPTION - switch off exceptions Language support \u00b6 JSON_HAS_CPP_11 JSON_HAS_CPP_14 JSON_HAS_CPP_17 JSON_HAS_CPP_20 - set supported C++ standard JSON_HAS_FILESYSTEM JSON_HAS_EXPERIMENTAL_FILESYSTEM - control std::filesystem support JSON_HAS_RANGES - control std::ranges support JSON_HAS_THREE_WAY_COMPARISON - control 3-way comparison support JSON_NO_IO - switch off functions relying on certain C++ I/O headers JSON_SKIP_UNSUPPORTED_COMPILER_CHECK - do not warn about unsupported compilers JSON_USE_GLOBAL_UDLS - place user-defined string literals (UDLs) into the global namespace Library version \u00b6 JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check NLOHMANN_JSON_VERSION_MAJOR NLOHMANN_JSON_VERSION_MINOR NLOHMANN_JSON_VERSION_PATCH - library version information Library namespace \u00b6 NLOHMANN_JSON_NAMESPACE - full name of the nlohmann namespace NLOHMANN_JSON_NAMESPACE_BEGIN NLOHMANN_JSON_NAMESPACE_END - open and close the library namespace NLOHMANN_JSON_NAMESPACE_NO_VERSION - disable the version component of the inline namespace Type conversions \u00b6 JSON_DISABLE_ENUM_SERIALIZATION - switch off default serialization/deserialization functions for enums JSON_USE_IMPLICIT_CONVERSIONS - control implicit conversions Comparison behavior \u00b6 JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - control comparison of discarded values Serialization/deserialization macros \u00b6 NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types with access to private variables NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types without access to private variables NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) - serialization/deserialization of enum types","title":"Overview"},{"location":"api/macros/#macros","text":"Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page .","title":"Macros"},{"location":"api/macros/#runtime-assertions","text":"JSON_ASSERT(x) - control behavior of runtime assertions","title":"Runtime assertions"},{"location":"api/macros/#exceptions","text":"JSON_CATCH_USER(exception) JSON_THROW_USER(exception) JSON_TRY_USER - control exceptions JSON_DIAGNOSTICS - control extended diagnostics JSON_NOEXCEPTION - switch off exceptions","title":"Exceptions"},{"location":"api/macros/#language-support","text":"JSON_HAS_CPP_11 JSON_HAS_CPP_14 JSON_HAS_CPP_17 JSON_HAS_CPP_20 - set supported C++ standard JSON_HAS_FILESYSTEM JSON_HAS_EXPERIMENTAL_FILESYSTEM - control std::filesystem support JSON_HAS_RANGES - control std::ranges support JSON_HAS_THREE_WAY_COMPARISON - control 3-way comparison support JSON_NO_IO - switch off functions relying on certain C++ I/O headers JSON_SKIP_UNSUPPORTED_COMPILER_CHECK - do not warn about unsupported compilers JSON_USE_GLOBAL_UDLS - place user-defined string literals (UDLs) into the global namespace","title":"Language support"},{"location":"api/macros/#library-version","text":"JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check NLOHMANN_JSON_VERSION_MAJOR NLOHMANN_JSON_VERSION_MINOR NLOHMANN_JSON_VERSION_PATCH - library version information","title":"Library version"},{"location":"api/macros/#library-namespace","text":"NLOHMANN_JSON_NAMESPACE - full name of the nlohmann namespace NLOHMANN_JSON_NAMESPACE_BEGIN NLOHMANN_JSON_NAMESPACE_END - open and close the library namespace NLOHMANN_JSON_NAMESPACE_NO_VERSION - disable the version component of the inline namespace","title":"Library namespace"},{"location":"api/macros/#type-conversions","text":"JSON_DISABLE_ENUM_SERIALIZATION - switch off default serialization/deserialization functions for enums JSON_USE_IMPLICIT_CONVERSIONS - control implicit conversions","title":"Type conversions"},{"location":"api/macros/#comparison-behavior","text":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - control comparison of discarded values","title":"Comparison behavior"},{"location":"api/macros/#serializationdeserialization-macros","text":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types with access to private variables NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types without access to private variables NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) - serialization/deserialization of enum types","title":"Serialization/deserialization macros"},{"location":"api/macros/json_assert/","text":"JSON_ASSERT \u00b6 #define JSON_ASSERT(x) /* value */ This macro controls which code is executed for runtime assertions of the library. Parameters \u00b6 x (in) expression of scalar type Default definition \u00b6 The default value is assert ( x ) . #define JSON_ASSERT(x) assert(x) Therefore, assertions can be switched off by defining NDEBUG . Notes \u00b6 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. The macro is undefined outside the library. Examples \u00b6 Example 1: default behavior The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. Example 2: user-defined behavior The assertion reporting can be changed by defining JSON_ASSERT(x) differently. #include #include #define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();} #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: assertion error in operator[] Version history \u00b6 Added in version 3.9.0.","title":"JSON_ASSERT"},{"location":"api/macros/json_assert/#json_assert","text":"#define JSON_ASSERT(x) /* value */ This macro controls which code is executed for runtime assertions of the library.","title":"JSON_ASSERT"},{"location":"api/macros/json_assert/#parameters","text":"x (in) expression of scalar type","title":"Parameters"},{"location":"api/macros/json_assert/#default-definition","text":"The default value is assert ( x ) . #define JSON_ASSERT(x) assert(x) Therefore, assertions can be switched off by defining NDEBUG .","title":"Default definition"},{"location":"api/macros/json_assert/#notes","text":"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. The macro is undefined outside the library.","title":"Notes"},{"location":"api/macros/json_assert/#examples","text":"Example 1: default behavior The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. Example 2: user-defined behavior The assertion reporting can be changed by defining JSON_ASSERT(x) differently. #include #include #define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();} #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: assertion error in operator[]","title":"Examples"},{"location":"api/macros/json_assert/#version-history","text":"Added in version 3.9.0.","title":"Version history"},{"location":"api/macros/json_diagnostics/","text":"JSON_DIAGNOSTICS \u00b6 #define JSON_DIAGNOSTICS /* value */ 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. Default definition \u00b6 The default value is 0 (extended diagnostics are switched off). #define JSON_DIAGNOSTICS 0 When the macro is not defined, the library will define it to its default value. Notes \u00b6 ABI compatibility As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names. This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior. Where possible, it is still recommended that all code define this the same way for maximum interoperability. CMake option Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which defines JSON_DIAGNOSTICS accordingly. Examples \u00b6 Example 1: default behavior #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. Example 2: extended diagnostic messages #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type. Version history \u00b6 Added in version 3.10.0. As of version 3.11.0 the definition is allowed to vary between translation units.","title":"JSON_DIAGNOSTICS"},{"location":"api/macros/json_diagnostics/#json_diagnostics","text":"#define JSON_DIAGNOSTICS /* value */ 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.","title":"JSON_DIAGNOSTICS"},{"location":"api/macros/json_diagnostics/#default-definition","text":"The default value is 0 (extended diagnostics are switched off). #define JSON_DIAGNOSTICS 0 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_diagnostics/#notes","text":"ABI compatibility As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names. This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior. Where possible, it is still recommended that all code define this the same way for maximum interoperability. CMake option Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which defines JSON_DIAGNOSTICS accordingly.","title":"Notes"},{"location":"api/macros/json_diagnostics/#examples","text":"Example 1: default behavior #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. Example 2: extended diagnostic messages #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.","title":"Examples"},{"location":"api/macros/json_diagnostics/#version-history","text":"Added in version 3.10.0. As of version 3.11.0 the definition is allowed to vary between translation units.","title":"Version history"},{"location":"api/macros/json_disable_enum_serialization/","text":"JSON_DISABLE_ENUM_SERIALIZATION \u00b6 #define JSON_DISABLE_ENUM_SERIALIZATION /* value */ When defined to 1 , default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details). Parsing or serializing an enum will result in a compiler error. This works for both unscoped and scoped enums. Default definition \u00b6 The default value is 0 . #define JSON_DISABLE_ENUM_SERIALIZATION 0 Notes \u00b6 CMake option Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization ( OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly. Examples \u00b6 Example 1: Disabled behavior The code below forces the library not to create default serialization/deserialization functions from_json and to_json , meaning the code below does not compile. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; int main () { // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not const json j = Choice :: first ; // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not Choice ch = j . template get < Choice > (); } 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 #include using json = nlohmann :: json ; enum class Choice { first , second , }; NLOHMANN_JSON_SERIALIZE_ENUM ( Choice , { { Choice :: first , \"first\" }, { Choice :: second , \"second\" }, }) int main () { // uses user-defined to_json function defined by macro const json j = Choice :: first ; // uses user-defined from_json function defined by macro Choice ch = j . template get < Choice > (); } Example 3: User-defined serialization/deserialization functions The code below forces the library not to create default serialization/deserialization functions from_json and to_json , but uses user-defined functions to parse and serialize the enum. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; void from_json ( const json & j , Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } void to_json ( json & j , const Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } int main () { // uses user-defined to_json function const json j = Choice :: first ; // uses user-defined from_json function Choice ch = j . template get < Choice > (); } See also \u00b6 NLOHMANN_JSON_SERIALIZE_ENUM Version history \u00b6 Added in version 3.11.0.","title":"JSON_DISABLE_ENUM_SERIALIZATION"},{"location":"api/macros/json_disable_enum_serialization/#json_disable_enum_serialization","text":"#define JSON_DISABLE_ENUM_SERIALIZATION /* value */ When defined to 1 , default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details). Parsing or serializing an enum will result in a compiler error. This works for both unscoped and scoped enums.","title":"JSON_DISABLE_ENUM_SERIALIZATION"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","text":"The default value is 0 . #define JSON_DISABLE_ENUM_SERIALIZATION 0","title":"Default definition"},{"location":"api/macros/json_disable_enum_serialization/#notes","text":"CMake option Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization ( OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.","title":"Notes"},{"location":"api/macros/json_disable_enum_serialization/#examples","text":"Example 1: Disabled behavior The code below forces the library not to create default serialization/deserialization functions from_json and to_json , meaning the code below does not compile. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; int main () { // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not const json j = Choice :: first ; // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not Choice ch = j . template get < Choice > (); } 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 #include using json = nlohmann :: json ; enum class Choice { first , second , }; NLOHMANN_JSON_SERIALIZE_ENUM ( Choice , { { Choice :: first , \"first\" }, { Choice :: second , \"second\" }, }) int main () { // uses user-defined to_json function defined by macro const json j = Choice :: first ; // uses user-defined from_json function defined by macro Choice ch = j . template get < Choice > (); } Example 3: User-defined serialization/deserialization functions The code below forces the library not to create default serialization/deserialization functions from_json and to_json , but uses user-defined functions to parse and serialize the enum. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; void from_json ( const json & j , Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } void to_json ( json & j , const Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } int main () { // uses user-defined to_json function const json j = Choice :: first ; // uses user-defined from_json function Choice ch = j . template get < Choice > (); }","title":"Examples"},{"location":"api/macros/json_disable_enum_serialization/#see-also","text":"NLOHMANN_JSON_SERIALIZE_ENUM","title":"See also"},{"location":"api/macros/json_disable_enum_serialization/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_has_cpp_11/","text":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20 \u00b6 #define JSON_HAS_CPP_11 #define JSON_HAS_CPP_14 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_20 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. Default definition \u00b6 The default value is detected based on preprocessor macros such as __cplusplus , _HAS_CXX17 , or _MSVC_LANG . Notes \u00b6 JSON_HAS_CPP_11 is always defined. All macros are undefined outside the library. Examples \u00b6 Example The code below forces the library to use the C++14 standard: #define JSON_HAS_CPP_14 1 #include ... Version history \u00b6 Added in version 3.10.5.","title":"JSON_HAS_CPP_20"},{"location":"api/macros/json_has_cpp_11/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","text":"#define JSON_HAS_CPP_11 #define JSON_HAS_CPP_14 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_20 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.","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20"},{"location":"api/macros/json_has_cpp_11/#default-definition","text":"The default value is detected based on preprocessor macros such as __cplusplus , _HAS_CXX17 , or _MSVC_LANG .","title":"Default definition"},{"location":"api/macros/json_has_cpp_11/#notes","text":"JSON_HAS_CPP_11 is always defined. All macros are undefined outside the library.","title":"Notes"},{"location":"api/macros/json_has_cpp_11/#examples","text":"Example The code below forces the library to use the C++14 standard: #define JSON_HAS_CPP_14 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_cpp_11/#version-history","text":"Added in version 3.10.5.","title":"Version history"},{"location":"api/macros/json_has_filesystem/","text":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM \u00b6 #define JSON_HAS_FILESYSTEM /* value */ #define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */ 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 / std::filesystem ( JSON_HAS_FILESYSTEM ) or / 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 . Default definition \u00b6 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 > ) . Notes \u00b6 Note that older compilers or older versions of libstd++ also require the library stdc++fs to be linked to for filesystem support. Both macros are undefined outside the library. Examples \u00b6 Example The code below forces the library to use the header . #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #include ... Version history \u00b6 Added in version 3.10.5.","title":"JSON_HAS_FILESYSTEM"},{"location":"api/macros/json_has_filesystem/#json_has_filesystem-json_has_experimental_filesystem","text":"#define JSON_HAS_FILESYSTEM /* value */ #define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */ 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 / std::filesystem ( JSON_HAS_FILESYSTEM ) or / 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 .","title":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM"},{"location":"api/macros/json_has_filesystem/#default-definition","text":"The default value is detected based on the preprocessor macros __cpp_lib_filesystem , __cpp_lib_experimental_filesystem , __has_include ( < filesystem > ) , or __has_include ( < experimental / filesystem > ) .","title":"Default definition"},{"location":"api/macros/json_has_filesystem/#notes","text":"Note that older compilers or older versions of libstd++ also require the library stdc++fs to be linked to for filesystem support. Both macros are undefined outside the library.","title":"Notes"},{"location":"api/macros/json_has_filesystem/#examples","text":"Example The code below forces the library to use the header . #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_filesystem/#version-history","text":"Added in version 3.10.5.","title":"Version history"},{"location":"api/macros/json_has_ranges/","text":"JSON_HAS_RANGES \u00b6 #define JSON_HAS_RANGES /* value */ 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. Default definition \u00b6 The default value is detected based on the preprocessor macro __cpp_lib_ranges . When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The code below forces the library to enable support for ranges: #define JSON_HAS_RANGES 1 #include ... Version history \u00b6 Added in version 3.11.0.","title":"JSON_HAS_RANGES"},{"location":"api/macros/json_has_ranges/#json_has_ranges","text":"#define JSON_HAS_RANGES /* value */ 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.","title":"JSON_HAS_RANGES"},{"location":"api/macros/json_has_ranges/#default-definition","text":"The default value is detected based on the preprocessor macro __cpp_lib_ranges . When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_has_ranges/#examples","text":"Example The code below forces the library to enable support for ranges: #define JSON_HAS_RANGES 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_ranges/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_has_three_way_comparison/","text":"JSON_HAS_THREE_WAY_COMPARISON \u00b6 #define JSON_HAS_THREE_WAY_COMPARISON /* value */ This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported. Default definition \u00b6 The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison . When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The code below forces the library to use 3-way comparison: #define JSON_HAS_THREE_WAY_COMPARISON 1 #include ... Version history \u00b6 Added in version 3.11.0.","title":"JSON_HAS_THREE_WAY_COMPARISON"},{"location":"api/macros/json_has_three_way_comparison/#json_has_three_way_comparison","text":"#define JSON_HAS_THREE_WAY_COMPARISON /* value */ This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.","title":"JSON_HAS_THREE_WAY_COMPARISON"},{"location":"api/macros/json_has_three_way_comparison/#default-definition","text":"The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison . When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_has_three_way_comparison/#examples","text":"Example The code below forces the library to use 3-way comparison: #define JSON_HAS_THREE_WAY_COMPARISON 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_three_way_comparison/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_no_io/","text":"JSON_NO_IO \u00b6 #define JSON_NO_IO When defined, headers , , , , and 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)). Default definition \u00b6 By default, JSON_NO_IO is not defined. #undef JSON_NO_IO Examples \u00b6 Example The code below forces the library not to use the headers , , , , and . #define JSON_NO_IO 1 #include ... Version history \u00b6 Added in version 3.10.0.","title":"JSON_NO_IO"},{"location":"api/macros/json_no_io/#json_no_io","text":"#define JSON_NO_IO When defined, headers , , , , and 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)).","title":"JSON_NO_IO"},{"location":"api/macros/json_no_io/#default-definition","text":"By default, JSON_NO_IO is not defined. #undef JSON_NO_IO","title":"Default definition"},{"location":"api/macros/json_no_io/#examples","text":"Example The code below forces the library not to use the headers , , , , and . #define JSON_NO_IO 1 #include ...","title":"Examples"},{"location":"api/macros/json_no_io/#version-history","text":"Added in version 3.10.0.","title":"Version history"},{"location":"api/macros/json_noexception/","text":"JSON_NOEXCEPTION \u00b6 #define JSON_NOEXCEPTION 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 . Default definition \u00b6 By default, the macro is not defined. #undef JSON_NOEXCEPTION Notes \u00b6 The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 . Examples \u00b6 Example The code below switches off exceptions in the library. #define JSON_NOEXCEPTION 1 #include ... See also \u00b6 Switch off exceptions for more information how to switch off exceptions Version history \u00b6 Added in version 2.1.0.","title":"JSON_NOEXCEPTION"},{"location":"api/macros/json_noexception/#json_noexception","text":"#define JSON_NOEXCEPTION 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 .","title":"JSON_NOEXCEPTION"},{"location":"api/macros/json_noexception/#default-definition","text":"By default, the macro is not defined. #undef JSON_NOEXCEPTION","title":"Default definition"},{"location":"api/macros/json_noexception/#notes","text":"The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 .","title":"Notes"},{"location":"api/macros/json_noexception/#examples","text":"Example The code below switches off exceptions in the library. #define JSON_NOEXCEPTION 1 #include ...","title":"Examples"},{"location":"api/macros/json_noexception/#see-also","text":"Switch off exceptions for more information how to switch off exceptions","title":"See also"},{"location":"api/macros/json_noexception/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/macros/json_skip_library_version_check/","text":"JSON_SKIP_LIBRARY_VERSION_CHECK \u00b6 #define JSON_SKIP_LIBRARY_VERSION_CHECK When defined, the library will not create a compiler warning when a different version of the library was already included. Default definition \u00b6 By default, the macro is not defined. #undef JSON_SKIP_LIBRARY_VERSION_CHECK Notes \u00b6 ABI compatibility Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible. Examples \u00b6 Example The following warning will be shown in case a different version of the library was already included: Already included a different version of the library! Version history \u00b6 Added in version 3.11.0.","title":"JSON_SKIP_LIBRARY_VERSION_CHECK"},{"location":"api/macros/json_skip_library_version_check/#json_skip_library_version_check","text":"#define JSON_SKIP_LIBRARY_VERSION_CHECK When defined, the library will not create a compiler warning when a different version of the library was already included.","title":"JSON_SKIP_LIBRARY_VERSION_CHECK"},{"location":"api/macros/json_skip_library_version_check/#default-definition","text":"By default, the macro is not defined. #undef JSON_SKIP_LIBRARY_VERSION_CHECK","title":"Default definition"},{"location":"api/macros/json_skip_library_version_check/#notes","text":"ABI compatibility Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.","title":"Notes"},{"location":"api/macros/json_skip_library_version_check/#examples","text":"Example The following warning will be shown in case a different version of the library was already included: Already included a different version of the library!","title":"Examples"},{"location":"api/macros/json_skip_library_version_check/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_skip_unsupported_compiler_check/","text":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK \u00b6 #define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 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. Default definition \u00b6 By default, the macro is not defined. #undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK Examples \u00b6 Example The code below switches off the check whether the compiler is supported. #define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1 #include ... Version history \u00b6 Added in version 3.2.0.","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK"},{"location":"api/macros/json_skip_unsupported_compiler_check/#json_skip_unsupported_compiler_check","text":"#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 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.","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","text":"By default, the macro is not defined. #undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","title":"Default definition"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","text":"Example The code below switches off the check whether the compiler is supported. #define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1 #include ...","title":"Examples"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/macros/json_throw_user/","text":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER \u00b6 // (1) #define JSON_CATCH_USER(exception) /* value */ // (2) #define JSON_THROW_USER(exception) /* value */ // (3) #define JSON_TRY_USER /* value */ 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. Parameters \u00b6 exception (in) an exception type Default definition \u00b6 By default, the macros map to their respective C++ keywords: #define JSON_CATCH_USER(exception) catch(exception) #define JSON_THROW_USER(exception) throw exception #define JSON_TRY_USER try 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() #define JSON_TRY_USER if (true) #define JSON_CATCH_USER(exception) if (false) Examples \u00b6 Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include See also \u00b6 Switch off exceptions for more information how to switch off exceptions JSON_NOEXCEPTION - switch off exceptions Version history \u00b6 Added in version 3.1.0.","title":"JSON_TRY_USER"},{"location":"api/macros/json_throw_user/#json_catch_user-json_throw_user-json_try_user","text":"// (1) #define JSON_CATCH_USER(exception) /* value */ // (2) #define JSON_THROW_USER(exception) /* value */ // (3) #define JSON_TRY_USER /* value */ 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.","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER"},{"location":"api/macros/json_throw_user/#parameters","text":"exception (in) an exception type","title":"Parameters"},{"location":"api/macros/json_throw_user/#default-definition","text":"By default, the macros map to their respective C++ keywords: #define JSON_CATCH_USER(exception) catch(exception) #define JSON_THROW_USER(exception) throw exception #define JSON_TRY_USER try 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() #define JSON_TRY_USER if (true) #define JSON_CATCH_USER(exception) if (false)","title":"Default definition"},{"location":"api/macros/json_throw_user/#examples","text":"Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include ","title":"Examples"},{"location":"api/macros/json_throw_user/#see-also","text":"Switch off exceptions for more information how to switch off exceptions JSON_NOEXCEPTION - switch off exceptions","title":"See also"},{"location":"api/macros/json_throw_user/#version-history","text":"Added in version 3.1.0.","title":"Version history"},{"location":"api/macros/json_use_global_udls/","text":"JSON_USE_GLOBAL_UDLS \u00b6 #define JSON_USE_GLOBAL_UDLS /* value */ When defined to 1 , the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals . Default definition \u00b6 The default value is 1 . #define JSON_USE_GLOBAL_UDLS 1 When the macro is not defined, the library will define it to its default value. Notes \u00b6 Future behavior change The user-defined string literals will be removed from the global namespace in the next major release of the library. To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details. CMake option The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs ( ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly. Examples \u00b6 Example 1: Default behavior The code below shows the default behavior using the _json UDL. #include #include int main () { auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42 Example 2: Namespaced UDLs The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0 . #define JSON_USE_GLOBAL_UDLS 0 #include #include int main () { // auto j = \"42\"_json; // This line would fail to compile, // because the UDLs are not in the global namespace // Bring the UDLs into scope using namespace nlohmann :: json_literals ; auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42 See also \u00b6 operator\"\"_json operator\"\"_json_pointer Version history \u00b6 Added in version 3.11.0.","title":"JSON_USE_GLOBAL_UDLS"},{"location":"api/macros/json_use_global_udls/#json_use_global_udls","text":"#define JSON_USE_GLOBAL_UDLS /* value */ When defined to 1 , the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals .","title":"JSON_USE_GLOBAL_UDLS"},{"location":"api/macros/json_use_global_udls/#default-definition","text":"The default value is 1 . #define JSON_USE_GLOBAL_UDLS 1 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_use_global_udls/#notes","text":"Future behavior change The user-defined string literals will be removed from the global namespace in the next major release of the library. To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details. CMake option The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs ( ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.","title":"Notes"},{"location":"api/macros/json_use_global_udls/#examples","text":"Example 1: Default behavior The code below shows the default behavior using the _json UDL. #include #include int main () { auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42 Example 2: Namespaced UDLs The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0 . #define JSON_USE_GLOBAL_UDLS 0 #include #include int main () { // auto j = \"42\"_json; // This line would fail to compile, // because the UDLs are not in the global namespace // Bring the UDLs into scope using namespace nlohmann :: json_literals ; auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42","title":"Examples"},{"location":"api/macros/json_use_global_udls/#see-also","text":"operator\"\"_json operator\"\"_json_pointer","title":"See also"},{"location":"api/macros/json_use_global_udls/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_use_implicit_conversions/","text":"JSON_USE_IMPLICIT_CONVERSIONS \u00b6 #define JSON_USE_IMPLICIT_CONVERSIONS /* value */ When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType . Default definition \u00b6 By default, implicit conversions are enabled. #define JSON_USE_IMPLICIT_CONVERSIONS 1 Notes \u00b6 Future behavior change Implicit conversions will be switched off by default in the next major release of the library. You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get . CMake option Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions ( ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly. Examples \u00b6 Example This is an example for an implicit conversion: json j = \"Hello, world!\" ; std :: string s = j ; When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0 , the code above does no longer compile. Instead, it must be written like this: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > (); See also \u00b6 operator ValueType - get a value (implicit) get - get a value (explicit) Version history \u00b6 Added in version 3.9.0.","title":"JSON_USE_IMPLICIT_CONVERSIONS"},{"location":"api/macros/json_use_implicit_conversions/#json_use_implicit_conversions","text":"#define JSON_USE_IMPLICIT_CONVERSIONS /* value */ When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType .","title":"JSON_USE_IMPLICIT_CONVERSIONS"},{"location":"api/macros/json_use_implicit_conversions/#default-definition","text":"By default, implicit conversions are enabled. #define JSON_USE_IMPLICIT_CONVERSIONS 1","title":"Default definition"},{"location":"api/macros/json_use_implicit_conversions/#notes","text":"Future behavior change Implicit conversions will be switched off by default in the next major release of the library. You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get . CMake option Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions ( ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.","title":"Notes"},{"location":"api/macros/json_use_implicit_conversions/#examples","text":"Example This is an example for an implicit conversion: json j = \"Hello, world!\" ; std :: string s = j ; When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0 , the code above does no longer compile. Instead, it must be written like this: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > ();","title":"Examples"},{"location":"api/macros/json_use_implicit_conversions/#see-also","text":"operator ValueType - get a value (implicit) get - get a value (explicit)","title":"See also"},{"location":"api/macros/json_use_implicit_conversions/#version-history","text":"Added in version 3.9.0.","title":"Version history"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/","text":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON \u00b6 #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */ This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default). When enabled, comparisons involving at least one discarded JSON value yield results as follows: Operator Result == false != true < false <= true >= true > false Otherwise, comparisons involving at least one discarded JSON value always yield false . Default definition \u00b6 The default value is 0 . #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 When the macro is not defined, the library will define it to its default value. Notes \u00b6 Inconsistent behavior in C++20 and beyond 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. Examples \u00b6 Example The code below switches on the legacy discarded value comparison behavior in the library. #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include ... Version history \u00b6 Added in version 3.11.0.","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#json_use_legacy_discarded_value_comparison","text":"#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */ This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default). When enabled, comparisons involving at least one discarded JSON value yield results as follows: Operator Result == false != true < false <= true >= true > false Otherwise, comparisons involving at least one discarded JSON value always yield false .","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#default-definition","text":"The default value is 0 . #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","text":"Inconsistent behavior in C++20 and beyond 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.","title":"Notes"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#examples","text":"Example The code below switches on the legacy discarded value comparison behavior in the library. #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include ...","title":"Examples"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/nlohmann_define_type_intrusive/","text":"NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT \u00b6 #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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. Parameters \u00b6 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 Default definition \u00b6 The macros add two friend functions to the class which take care of the serialization and deserialization: friend void to_json ( nlohmann :: json & , const type & ); friend void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code. Notes \u00b6 Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Examples \u00b6 Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values. See also \u00b6 NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined outside the type. Arbitrary Type Conversions for an overview. Version history \u00b6 Added in version 3.9.0. Added in version 3.11.0.","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_intrusive/#nlohmann_define_type_intrusive-nlohmann_define_type_intrusive_with_default","text":"#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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.","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_intrusive/#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","title":"Parameters"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization: friend void to_json ( nlohmann :: json & , const type & ); friend void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code.","title":"Default definition"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","text":"Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.","title":"Notes"},{"location":"api/macros/nlohmann_define_type_intrusive/#examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values.","title":"Examples"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","text":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined outside the type. Arbitrary Type Conversions for an overview.","title":"See also"},{"location":"api/macros/nlohmann_define_type_intrusive/#version-history","text":"Added in version 3.9.0. Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/nlohmann_define_type_non_intrusive/","text":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT \u00b6 #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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. Parameters \u00b6 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 Default definition \u00b6 The macros add two functions to the namespace which take care of the serialization and deserialization: void to_json ( nlohmann :: json & , const type & ); void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code. Notes \u00b6 Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Examples \u00b6 Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable. 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable. The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns . A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value -1 is used. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values. See also \u00b6 NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined inside the type. Arbitrary Type Conversions for an overview. Version history \u00b6 Added in version 3.9.0. Added in version 3.11.0.","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#nlohmann_define_type_non_intrusive-nlohmann_define_type_non_intrusive_with_default","text":"#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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.","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#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","title":"Parameters"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","text":"The macros add two functions to the namespace which take care of the serialization and deserialization: void to_json ( nlohmann :: json & , const type & ); void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code.","title":"Default definition"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","text":"Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.","title":"Notes"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable. 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable. The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns . A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value -1 is used. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values.","title":"Examples"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","text":"NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined inside the type. Arbitrary Type Conversions for an overview.","title":"See also"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#version-history","text":"Added in version 3.9.0. Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/nlohmann_json_namespace/","text":"NLOHMANN_JSON_NAMESPACE \u00b6 #define NLOHMANN_JSON_NAMESPACE /* value */ This macro evaluates to the full name of the nlohmann namespace. Default definition \u00b6 The default value consists of the root namespace ( nlohmann ) and an inline ABI namespace. See nlohmann Namespace for details. When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library. Examples \u00b6 Example The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann , as well as how to output the value of NLOHMANN_JSON_NAMESPACE . #include #include // possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann using json = NLOHMANN_JSON_NAMESPACE :: json ; // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi_v 3 _ 11 _ 2 See also \u00b6 NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END NLOHMANN_JSON_NAMESPACE_NO_VERSION Version history \u00b6 Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"NLOHMANN_JSON_NAMESPACE"},{"location":"api/macros/nlohmann_json_namespace/#nlohmann_json_namespace","text":"#define NLOHMANN_JSON_NAMESPACE /* value */ This macro evaluates to the full name of the nlohmann namespace.","title":"NLOHMANN_JSON_NAMESPACE"},{"location":"api/macros/nlohmann_json_namespace/#default-definition","text":"The default value consists of the root namespace ( nlohmann ) and an inline ABI namespace. See nlohmann Namespace for details. When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.","title":"Default definition"},{"location":"api/macros/nlohmann_json_namespace/#examples","text":"Example The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann , as well as how to output the value of NLOHMANN_JSON_NAMESPACE . #include #include // possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann using json = NLOHMANN_JSON_NAMESPACE :: json ; // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi_v 3 _ 11 _ 2","title":"Examples"},{"location":"api/macros/nlohmann_json_namespace/#see-also","text":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END NLOHMANN_JSON_NAMESPACE_NO_VERSION","title":"See also"},{"location":"api/macros/nlohmann_json_namespace/#version-history","text":"Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"Version history"},{"location":"api/macros/nlohmann_json_namespace_begin/","text":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END \u00b6 #define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1) #define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2) These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details. Opens the namespace. Closes the namespace. Default definition \u00b6 The default definitions open and close the nlohmann namespace. The precise definition of [ NLOHMANN_JSON_NAMESPACE_BEGIN ] varies as described here . Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN : namespace nlohmann { inline namespace json_abi_v3_11_2 { Default definition of NLOHMANN_JSON_NAMESPACE_END : } // namespace json_abi_v3_11_2 } // namespace nlohmann When these macros are not defined, the library will define them to their default definitions. Examples \u00b6 Example The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN / NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page. #include #include #include // partial specialization (see https://json.nlohmann.me/features/arbitrary_types/) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < std :: optional < T >> { static void to_json ( json & j , const std :: optional < T >& opt ) { if ( opt == std :: nullopt ) { j = nullptr ; } else { j = * opt ; } } }; NLOHMANN_JSON_NAMESPACE_END int main () { std :: optional < int > o1 = 1 ; std :: optional < int > o2 = std :: nullopt ; NLOHMANN_JSON_NAMESPACE :: json j ; j . push_back ( o1 ); j . push_back ( o2 ); std :: cout << j << std :: endl ; } Output: [ 1 , null ] See also \u00b6 nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_NO_VERSION Version history \u00b6 Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"NLOHMANN_JSON_NAMESPACE_END"},{"location":"api/macros/nlohmann_json_namespace_begin/#nlohmann_json_namespace_begin-nlohmann_json_namespace_end","text":"#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1) #define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2) These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details. Opens the namespace. Closes the namespace.","title":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END"},{"location":"api/macros/nlohmann_json_namespace_begin/#default-definition","text":"The default definitions open and close the nlohmann namespace. The precise definition of [ NLOHMANN_JSON_NAMESPACE_BEGIN ] varies as described here . Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN : namespace nlohmann { inline namespace json_abi_v3_11_2 { Default definition of NLOHMANN_JSON_NAMESPACE_END : } // namespace json_abi_v3_11_2 } // namespace nlohmann When these macros are not defined, the library will define them to their default definitions.","title":"Default definition"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","text":"Example The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN / NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page. #include #include #include // partial specialization (see https://json.nlohmann.me/features/arbitrary_types/) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < std :: optional < T >> { static void to_json ( json & j , const std :: optional < T >& opt ) { if ( opt == std :: nullopt ) { j = nullptr ; } else { j = * opt ; } } }; NLOHMANN_JSON_NAMESPACE_END int main () { std :: optional < int > o1 = 1 ; std :: optional < int > o2 = std :: nullopt ; NLOHMANN_JSON_NAMESPACE :: json j ; j . push_back ( o1 ); j . push_back ( o2 ); std :: cout << j << std :: endl ; } Output: [ 1 , null ]","title":"Examples"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","text":"nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_NO_VERSION","title":"See also"},{"location":"api/macros/nlohmann_json_namespace_begin/#version-history","text":"Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"Version history"},{"location":"api/macros/nlohmann_json_namespace_no_version/","text":"NLOHMANN_JSON_NAMESPACE_NO_VERSION \u00b6 #define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */ If defined to 1 , the version component is omitted from the inline namespace. See nlohmann Namespace for details. Default definition \u00b6 The default value is 0 . #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace. #include #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1 #include // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi See also \u00b6 nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END Version history \u00b6 Added in version 3.11.2.","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION"},{"location":"api/macros/nlohmann_json_namespace_no_version/#nlohmann_json_namespace_no_version","text":"#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */ If defined to 1 , the version component is omitted from the inline namespace. See nlohmann Namespace for details.","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION"},{"location":"api/macros/nlohmann_json_namespace_no_version/#default-definition","text":"The default value is 0 . #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","text":"Example The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace. #include #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1 #include // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi","title":"Examples"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","text":"nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END","title":"See also"},{"location":"api/macros/nlohmann_json_namespace_no_version/#version-history","text":"Added in version 3.11.2.","title":"Version history"},{"location":"api/macros/nlohmann_json_serialize_enum/","text":"NLOHMANN_JSON_SERIALIZE_ENUM \u00b6 #define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...) 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. Parameters \u00b6 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 Default definition \u00b6 The macros add two friend functions to the class which take care of the serialization and deserialization: template < typename BasicJsonType > inline void to_json ( BasicJsonType & j , const type & e ); template < typename BasicJsonType > inline void from_json ( const BasicJsonType & j , type & e ); Notes \u00b6 Prerequisites The macro must be used inside the namespace of the enum. Important notes When using template get() , 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. Examples \u00b6 Example 1: Basic usage The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes: #include #include using json = nlohmann :: json ; namespace ns { enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 }; NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" } }) enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" } }) } // namespace ns int main () { // serialization json j_stopped = ns :: TS_STOPPED ; json j_red = ns :: Color :: red ; std :: cout << \"ns::TS_STOPPED -> \" << j_stopped << \", ns::Color::red -> \" << j_red << std :: endl ; // deserialization json j_running = \"running\" ; json j_blue = \"blue\" ; auto running = j_running . template get < ns :: TaskState > (); auto blue = j_blue . template get < ns :: Color > (); std :: cout << j_running << \" -> \" << running << \", \" << j_blue << \" -> \" << static_cast < int > ( blue ) << std :: endl ; // deserializing undefined JSON value to enum // (where the first map entry above is the default) json j_pi = 3.14 ; auto invalid = j_pi . template get < ns :: TaskState > (); auto unknown = j_pi . template get < ns :: Color > (); std :: cout << j_pi << \" -> \" << invalid << \", \" << j_pi << \" -> \" << static_cast < int > ( unknown ) << std :: endl ; } Output: ns :: TS_STOPPED - > \"stopped\" , ns :: Color :: red - > \"red\" \"running\" - > 1 , \"blue\" - > 2 3.14 - > -1 , 3.14 - > 3 Example 2: Multiple conversions for one enumerator The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\" , because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red . #include #include using json = nlohmann :: json ; namespace ns { enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" }, { Color :: red , \"rot\" } // a second conversion for Color::red }) } int main () { // serialization json j_red = ns :: Color :: red ; std :: cout << static_cast < int > ( ns :: Color :: red ) << \" -> \" << j_red << std :: endl ; // deserialization json j_rot = \"rot\" ; auto rot = j_rot . template get < ns :: Color > (); auto red = j_red . template get < ns :: Color > (); std :: cout << j_rot << \" -> \" << static_cast < int > ( rot ) << std :: endl ; std :: cout << j_red << \" -> \" << static_cast < int > ( red ) << std :: endl ; } Output: 0 - > \"red\" \"rot\" - > 0 \"red\" - > 0 See also \u00b6 Specializing enum conversion JSON_DISABLE_ENUM_SERIALIZATION Version history \u00b6 Added in version 3.4.0.","title":"NLOHMANN_JSON_SERIALIZE_ENUM"},{"location":"api/macros/nlohmann_json_serialize_enum/#nlohmann_json_serialize_enum","text":"#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...) 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.","title":"NLOHMANN_JSON_SERIALIZE_ENUM"},{"location":"api/macros/nlohmann_json_serialize_enum/#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","title":"Parameters"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization: template < typename BasicJsonType > inline void to_json ( BasicJsonType & j , const type & e ); template < typename BasicJsonType > inline void from_json ( const BasicJsonType & j , type & e );","title":"Default definition"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","text":"Prerequisites The macro must be used inside the namespace of the enum. Important notes When using template get() , 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.","title":"Notes"},{"location":"api/macros/nlohmann_json_serialize_enum/#examples","text":"Example 1: Basic usage The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes: #include #include using json = nlohmann :: json ; namespace ns { enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 }; NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" } }) enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" } }) } // namespace ns int main () { // serialization json j_stopped = ns :: TS_STOPPED ; json j_red = ns :: Color :: red ; std :: cout << \"ns::TS_STOPPED -> \" << j_stopped << \", ns::Color::red -> \" << j_red << std :: endl ; // deserialization json j_running = \"running\" ; json j_blue = \"blue\" ; auto running = j_running . template get < ns :: TaskState > (); auto blue = j_blue . template get < ns :: Color > (); std :: cout << j_running << \" -> \" << running << \", \" << j_blue << \" -> \" << static_cast < int > ( blue ) << std :: endl ; // deserializing undefined JSON value to enum // (where the first map entry above is the default) json j_pi = 3.14 ; auto invalid = j_pi . template get < ns :: TaskState > (); auto unknown = j_pi . template get < ns :: Color > (); std :: cout << j_pi << \" -> \" << invalid << \", \" << j_pi << \" -> \" << static_cast < int > ( unknown ) << std :: endl ; } Output: ns :: TS_STOPPED - > \"stopped\" , ns :: Color :: red - > \"red\" \"running\" - > 1 , \"blue\" - > 2 3.14 - > -1 , 3.14 - > 3 Example 2: Multiple conversions for one enumerator The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\" , because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red . #include #include using json = nlohmann :: json ; namespace ns { enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" }, { Color :: red , \"rot\" } // a second conversion for Color::red }) } int main () { // serialization json j_red = ns :: Color :: red ; std :: cout << static_cast < int > ( ns :: Color :: red ) << \" -> \" << j_red << std :: endl ; // deserialization json j_rot = \"rot\" ; auto rot = j_rot . template get < ns :: Color > (); auto red = j_red . template get < ns :: Color > (); std :: cout << j_rot << \" -> \" << static_cast < int > ( rot ) << std :: endl ; std :: cout << j_red << \" -> \" << static_cast < int > ( red ) << std :: endl ; } Output: 0 - > \"red\" \"rot\" - > 0 \"red\" - > 0","title":"Examples"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","text":"Specializing enum conversion JSON_DISABLE_ENUM_SERIALIZATION","title":"See also"},{"location":"api/macros/nlohmann_json_serialize_enum/#version-history","text":"Added in version 3.4.0.","title":"Version history"},{"location":"api/macros/nlohmann_json_version_major/","text":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH \u00b6 #define NLOHMANN_JSON_VERSION_MAJOR /* value */ #define NLOHMANN_JSON_VERSION_MINOR /* value */ #define NLOHMANN_JSON_VERSION_PATCH /* value */ These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 . Default definition \u00b6 The macros are defined according to the current library version. Examples \u00b6 Example The example below shows how NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH are defined by the library. #include #include using json = nlohmann :: json ; int main () { std :: cout << \"JSON for Modern C++ version \" << NLOHMANN_JSON_VERSION_MAJOR << \".\" << NLOHMANN_JSON_VERSION_MINOR << \".\" << NLOHMANN_JSON_VERSION_PATCH << std :: endl ; } Output: JSON f or Moder n C++ versio n 3.11.2 See also \u00b6 meta - returns version information on the library JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check Version history \u00b6 Added in version 3.1.0.","title":"NLOHMANN_JSON_VERSION_PATCH"},{"location":"api/macros/nlohmann_json_version_major/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","text":"#define NLOHMANN_JSON_VERSION_MAJOR /* value */ #define NLOHMANN_JSON_VERSION_MINOR /* value */ #define NLOHMANN_JSON_VERSION_PATCH /* value */ These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 .","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","text":"The macros are defined according to the current library version.","title":"Default definition"},{"location":"api/macros/nlohmann_json_version_major/#examples","text":"Example The example below shows how NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH are defined by the library. #include #include using json = nlohmann :: json ; int main () { std :: cout << \"JSON for Modern C++ version \" << NLOHMANN_JSON_VERSION_MAJOR << \".\" << NLOHMANN_JSON_VERSION_MINOR << \".\" << NLOHMANN_JSON_VERSION_PATCH << std :: endl ; } Output: JSON f or Moder n C++ versio n 3.11.2","title":"Examples"},{"location":"api/macros/nlohmann_json_version_major/#see-also","text":"meta - returns version information on the library JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check","title":"See also"},{"location":"api/macros/nlohmann_json_version_major/#version-history","text":"Added in version 3.1.0.","title":"Version history"},{"location":"features/arbitrary_types/","text":"Arbitrary Type Conversions \u00b6 Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines: namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // convert to JSON: copy each value into the JSON object json j ; j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; // ... // convert from JSON: copy each value from the JSON object ns :: person p { j [ \"name\" ]. template get < std :: string > (), j [ \"address\" ]. template get < std :: string > (), j [ \"age\" ]. template get < int > () }; It works, but that's quite a lot of boilerplate... Fortunately, there's a better way: // create a person ns :: person p { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // conversion: person -> json json j = p ; std :: cout << j << std :: endl ; // {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"} // conversion: json -> person auto p2 = j . template get < ns :: person > (); // that's it assert ( p == p2 ); Basic usage \u00b6 To make this work with one of your types, you only need to provide two functions: using json = nlohmann :: json ; namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns 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() 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 issue 1108 for errors that may occur otherwise. When using template get() , 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. Simplify your life with macros \u00b6 If you just want to serialize/deserialize some structs, the to_json / from_json functions can be a lot of boilerplate. There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object: NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here . Implementation limits 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Example The to_json / from_json functions for the person struct above can be created with: namespace ns { NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed: namespace ns { class address { private : std :: string street ; int housenumber ; int postcode ; public : NLOHMANN_DEFINE_TYPE_INTRUSIVE ( address , street , housenumber , postcode ) }; } How do I convert third-party types? \u00b6 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 > struct adl_serializer { static void to_json ( json & j , const T & value ) { // calls the \"to_json\" method in T's namespace } static void from_json ( const json & j , T & value ) { // same thing, but with the \"from_json\" method } }; 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) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < boost :: optional < T >> { static void to_json ( json & j , const boost :: optional < T >& opt ) { if ( opt == boost :: none ) { j = nullptr ; } else { j = * opt ; // this will call adl_serializer::to_json which will // find the free function to_json in T's namespace! } } static void from_json ( const json & j , boost :: optional < T >& opt ) { if ( j . is_null ()) { opt = boost :: none ; } else { opt = j . template get < T > (); // same as above, but with // adl_serializer::from_json } } }; NLOHMANN_JSON_NAMESPACE_END 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. How can I use get() for non-default constructible/non-copyable types? \u00b6 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 { move_only_type () = delete ; move_only_type ( int ii ) : i ( ii ) {} move_only_type ( const move_only_type & ) = delete ; move_only_type ( move_only_type && ) = default ; int i ; }; namespace nlohmann { template <> struct adl_serializer < move_only_type > { // note: the return type is no longer 'void', and the method only takes // one argument static move_only_type from_json ( const json & j ) { return { j . template get < int > ()}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert move_only_type to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , move_only_type t ) { j = t . i ; } }; } Can I write my own serializer? (Advanced use) \u00b6 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 // if you don't need compile-time checks on T template < typename T , typename SFINAE = typename std :: enable_if < sizeof ( T ) <= 32 >:: type > struct less_than_32_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , T value ) { // we want to use ADL, and call the correct to_json overload using nlohmann :: to_json ; // this method is called by adl_serializer, // this is where the magic happens to_json ( j , value ); } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing here using nlohmann :: from_json ; from_json ( j , value ); } }; Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention: template < typename T , void > struct bad_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // this calls BasicJsonType::json_serializer::to_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! j = value ; } template < typename BasicJsonType > static void to_json ( const BasicJsonType & j , T & value ) { // this calls BasicJsonType::json_serializer::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j . template template get < T > (); // oops! } };","title":"Arbitrary Type Conversions"},{"location":"features/arbitrary_types/#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 { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // convert to JSON: copy each value into the JSON object json j ; j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; // ... // convert from JSON: copy each value from the JSON object ns :: person p { j [ \"name\" ]. template get < std :: string > (), j [ \"address\" ]. template get < std :: string > (), j [ \"age\" ]. template get < int > () }; It works, but that's quite a lot of boilerplate... Fortunately, there's a better way: // create a person ns :: person p { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // conversion: person -> json json j = p ; std :: cout << j << std :: endl ; // {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"} // conversion: json -> person auto p2 = j . template get < ns :: person > (); // that's it assert ( p == p2 );","title":"Arbitrary Type Conversions"},{"location":"features/arbitrary_types/#basic-usage","text":"To make this work with one of your types, you only need to provide two functions: using json = nlohmann :: json ; namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns 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() 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 issue 1108 for errors that may occur otherwise. When using template get() , 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.","title":"Basic usage"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","text":"If you just want to serialize/deserialize some structs, the to_json / from_json functions can be a lot of boilerplate. There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object: NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here . Implementation limits 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Example The to_json / from_json functions for the person struct above can be created with: namespace ns { NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed: namespace ns { class address { private : std :: string street ; int housenumber ; int postcode ; public : NLOHMANN_DEFINE_TYPE_INTRUSIVE ( address , street , housenumber , postcode ) }; }","title":"Simplify your life with macros"},{"location":"features/arbitrary_types/#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 > struct adl_serializer { static void to_json ( json & j , const T & value ) { // calls the \"to_json\" method in T's namespace } static void from_json ( const json & j , T & value ) { // same thing, but with the \"from_json\" method } }; 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) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < boost :: optional < T >> { static void to_json ( json & j , const boost :: optional < T >& opt ) { if ( opt == boost :: none ) { j = nullptr ; } else { j = * opt ; // this will call adl_serializer::to_json which will // find the free function to_json in T's namespace! } } static void from_json ( const json & j , boost :: optional < T >& opt ) { if ( j . is_null ()) { opt = boost :: none ; } else { opt = j . template get < T > (); // same as above, but with // adl_serializer::from_json } } }; NLOHMANN_JSON_NAMESPACE_END 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.","title":"How do I convert third-party types?"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-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 { move_only_type () = delete ; move_only_type ( int ii ) : i ( ii ) {} move_only_type ( const move_only_type & ) = delete ; move_only_type ( move_only_type && ) = default ; int i ; }; namespace nlohmann { template <> struct adl_serializer < move_only_type > { // note: the return type is no longer 'void', and the method only takes // one argument static move_only_type from_json ( const json & j ) { return { j . template get < int > ()}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert move_only_type to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , move_only_type t ) { j = t . i ; } }; }","title":"How can I use get() for non-default constructible/non-copyable types?"},{"location":"features/arbitrary_types/#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 // if you don't need compile-time checks on T template < typename T , typename SFINAE = typename std :: enable_if < sizeof ( T ) <= 32 >:: type > struct less_than_32_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , T value ) { // we want to use ADL, and call the correct to_json overload using nlohmann :: to_json ; // this method is called by adl_serializer, // this is where the magic happens to_json ( j , value ); } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing here using nlohmann :: from_json ; from_json ( j , value ); } }; Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention: template < typename T , void > struct bad_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // this calls BasicJsonType::json_serializer::to_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! j = value ; } template < typename BasicJsonType > static void to_json ( const BasicJsonType & j , T & value ) { // this calls BasicJsonType::json_serializer::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j . template template get < T > (); // oops! } };","title":"Can I write my own serializer? (Advanced use)"},{"location":"features/assertions/","text":"Runtime Assertions \u00b6 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. Switch off runtime assertions \u00b6 Runtime assertions can be switched off by defining the preprocessor macro NDEBUG (see the documentation of assert ) which is the default for release builds. Change assertion behavior \u00b6 The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header. Function with runtime assertions \u00b6 Unchecked object access to a const value \u00b6 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 using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. Constructing from an uninitialized iterator range \u00b6 Constructing a JSON value from an iterator range (see constructor ) with an uninitialized iterator is undefined behavior and yields a runtime assertion. Example 2: Uninitialized iterator range The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it1 , it2 ; json j ( it1 , it2 ); } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368. Operations on uninitialized iterators \u00b6 Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion. Example 3: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it ; ++ it ; } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368. Reading from a null FILE pointer \u00b6 Reading from a null FILE pointer is undefined behavior and yields a runtime assertion. This can happen when calling std :: fopen on a nonexistent file. Example 4: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { std :: FILE * f = std :: fopen ( \"nonexistent_file.json\" , \"r\" ); json j = json :: parse ( f ); } Output: Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.","title":"Runtime Assertions"},{"location":"features/assertions/#runtime-assertions","text":"The code contains numerous debug assertions to ensure class invariants are valid or to detect undefined behavior. Whereas the former class invariants are nothing to be concerned of, the latter checks for undefined behavior are to detect bugs in client code.","title":"Runtime Assertions"},{"location":"features/assertions/#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.","title":"Switch off runtime assertions"},{"location":"features/assertions/#change-assertion-behavior","text":"The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header.","title":"Change assertion behavior"},{"location":"features/assertions/#function-with-runtime-assertions","text":"","title":"Function with runtime assertions"},{"location":"features/assertions/#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 using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.","title":"Unchecked object access to a const value"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","text":"Constructing a JSON value from an iterator range (see constructor ) with an uninitialized iterator is undefined behavior and yields a runtime assertion. Example 2: Uninitialized iterator range The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it1 , it2 ; json j ( it1 , it2 ); } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.","title":"Constructing from an uninitialized iterator range"},{"location":"features/assertions/#operations-on-uninitialized-iterators","text":"Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion. Example 3: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it ; ++ it ; } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.","title":"Operations on uninitialized iterators"},{"location":"features/assertions/#reading-from-a-null-file-pointer","text":"Reading from a null FILE pointer is undefined behavior and yields a runtime assertion. This can happen when calling std :: fopen on a nonexistent file. Example 4: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { std :: FILE * f = std :: fopen ( \"nonexistent_file.json\" , \"r\" ); json j = json :: parse ( f ); } Output: Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.","title":"Reading from a null FILE pointer"},{"location":"features/binary_values/","text":"Binary Values \u00b6 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. API for binary values \u00b6 By default, binary values are stored as std::vector . This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t : auto binary = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }); auto binary_with_subtype = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); There are several convenience functions to check and set the subtype: binary . has_subtype (); // returns false binary_with_subtype . has_subtype (); // returns true binary_with_subtype . clear_subtype (); binary_with_subtype . has_subtype (); // returns true binary_with_subtype . set_subtype ( 42 ); binary . set_subtype ( 23 ); binary . subtype (); // returns 23 As json::binary_t is subclassing std::vector , all member functions are available: binary . size (); // returns 4 binary [ 1 ]; // returns 0xFE JSON values can be constructed from json::binary_t : json j = binary ; Binary values are primitive values just like numbers or strings: j . is_binary (); // returns true j . is_primitive (); // returns true Given a binary JSON value, the binary_t can be accessed by reference as via get_binary() : j . get_binary (). has_subtype (); // returns true j . get_binary (). size (); // returns 4 For convenience, binary JSON values can be constructed via json::binary : auto j2 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 23 ); auto j3 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }); j2 == j ; // returns true j3 . get_binary (). has_subtype (); // returns false j3 . get_binary (). subtype (); // returns std::uint64_t(-1) as j3 has no subtype Serialization \u00b6 Binary values are serialized differently according to the formats. JSON \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // serialize to standard output std :: cout << j . dump ( 2 ) << std :: endl ; Output: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } No roundtrip for binary values The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes. BJData \u00b6 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) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BJData auto v = json :: to_bjdata ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_bjdata ( j , true , true ); The resulting vector has 22 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' array 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] } BSON \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BSON auto v = json :: to_bson ( j ); v is a std::vector with the following 22 elements: 0x16 0x00 0x00 0x00 // number of bytes in the document 0x05 // binary value 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte 0x04 0x00 0x00 0x00 // number of bytes 0x2a // subtype 0xCA 0xFE 0xBA 0xBE // content 0x00 // end of the document Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } CBOR \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to CBOR auto v = json :: to_cbor ( j ); v is a std::vector with the following 15 elements: 0xA1 // map(1) 0x66 // text(6) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD8 0x2A // tag(42) 0x44 // bytes(4) 0xCA 0xFE 0xBA 0xBE // content 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 . { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : null } } MessagePack \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to MessagePack auto v = json :: to_msgpack ( j ); v is a std::vector with the following 14 elements: 0x81 // fixmap1 0xA6 // fixstr6 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD6 // fixext4 0x2A // subtype 0xCA 0xFE 0xBA 0xBE // content Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } UBJSON \u00b6 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) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to UBJSON auto v = json :: to_ubjson ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_ubjson ( j , true , true ); The resulting vector has 23 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x24 // '$' type of the object elements 0x5B // '[' array 0x23 0x69 0x01 // '#' i 1 number of object elements 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] }","title":"Binary Values"},{"location":"features/binary_values/#binary-values","text":"The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored. JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.","title":"Binary Values"},{"location":"features/binary_values/#api-for-binary-values","text":"By default, binary values are stored as std::vector . This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t : auto binary = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }); auto binary_with_subtype = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); There are several convenience functions to check and set the subtype: binary . has_subtype (); // returns false binary_with_subtype . has_subtype (); // returns true binary_with_subtype . clear_subtype (); binary_with_subtype . has_subtype (); // returns true binary_with_subtype . set_subtype ( 42 ); binary . set_subtype ( 23 ); binary . subtype (); // returns 23 As json::binary_t is subclassing std::vector , all member functions are available: binary . size (); // returns 4 binary [ 1 ]; // returns 0xFE JSON values can be constructed from json::binary_t : json j = binary ; Binary values are primitive values just like numbers or strings: j . is_binary (); // returns true j . is_primitive (); // returns true Given a binary JSON value, the binary_t can be accessed by reference as via get_binary() : j . get_binary (). has_subtype (); // returns true j . get_binary (). size (); // returns 4 For convenience, binary JSON values can be constructed via json::binary : auto j2 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 23 ); auto j3 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }); j2 == j ; // returns true j3 . get_binary (). has_subtype (); // returns false j3 . get_binary (). subtype (); // returns std::uint64_t(-1) as j3 has no subtype","title":"API for binary values"},{"location":"features/binary_values/#serialization","text":"Binary values are serialized differently according to the formats.","title":"Serialization"},{"location":"features/binary_values/#json","text":"JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: bytes holds an array of integers, and subtype is an integer or null . Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // serialize to standard output std :: cout << j . dump ( 2 ) << std :: endl ; Output: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } No roundtrip for binary values The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes.","title":"JSON"},{"location":"features/binary_values/#bjdata","text":"BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library. Example Code: // create a binary value of subtype 42 (will be ignored in BJData) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BJData auto v = json :: to_bjdata ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_bjdata ( j , true , true ); The resulting vector has 22 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' array 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] }","title":"BJData"},{"location":"features/binary_values/#bson","text":"BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used. Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BSON auto v = json :: to_bson ( j ); v is a std::vector with the following 22 elements: 0x16 0x00 0x00 0x00 // number of bytes in the document 0x05 // binary value 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte 0x04 0x00 0x00 0x00 // number of bytes 0x2a // subtype 0xCA 0xFE 0xBA 0xBE // content 0x00 // end of the document Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } }","title":"BSON"},{"location":"features/binary_values/#cbor","text":"CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array. Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to CBOR auto v = json :: to_cbor ( j ); v is a std::vector with the following 15 elements: 0xA1 // map(1) 0x66 // text(6) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD8 0x2A // tag(42) 0x44 // bytes(4) 0xCA 0xFE 0xBA 0xBE // content 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 . { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : null } }","title":"CBOR"},{"location":"features/binary_values/#messagepack","text":"MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer. If no subtype is given, the bin family (bin8, bin16, bin32) is used. Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to MessagePack auto v = json :: to_msgpack ( j ); v is a std::vector with the following 14 elements: 0x81 // fixmap1 0xA6 // fixstr6 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD6 // fixext4 0x2A // subtype 0xCA 0xFE 0xBA 0xBE // content Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } }","title":"MessagePack"},{"location":"features/binary_values/#ubjson","text":"UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library. Example Code: // create a binary value of subtype 42 (will be ignored in UBJSON) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to UBJSON auto v = json :: to_ubjson ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_ubjson ( j , true , true ); The resulting vector has 23 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x24 // '$' type of the object elements 0x5B // '[' array 0x23 0x69 0x01 // '#' i 1 number of object elements 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] }","title":"UBJSON"},{"location":"features/comments/","text":"Comments \u00b6 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. Example Consider the following JSON with comments. { // update in 2006: removed Pluto \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" /*, \"Pluto\" */ ] } When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true , the comments are ignored during parsing: #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { std :: string s = R \" ( { // update in 2006: removed Pluto \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */] } ) \" ; try { json j = json :: parse ( s ); } catch ( json :: exception & e ) { std :: cout << e . what () << std :: endl ; } json j = json :: parse ( s , /* callback */ nullptr , /* allow exceptions */ true , /* ignore_comments */ true ); std :: cout << j . dump ( 2 ) << '\\n' ; } Output: [json.exception.parse_error.101] parse error at line 3, column 9: syntax error while parsing object key - invalid literal; last read: ' { /'; expected string literal { \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" ] }","title":"Comments"},{"location":"features/comments/#comments","text":"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. Example Consider the following JSON with comments. { // update in 2006: removed Pluto \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" /*, \"Pluto\" */ ] } When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true , the comments are ignored during parsing: #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { std :: string s = R \" ( { // update in 2006: removed Pluto \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */] } ) \" ; try { json j = json :: parse ( s ); } catch ( json :: exception & e ) { std :: cout << e . what () << std :: endl ; } json j = json :: parse ( s , /* callback */ nullptr , /* allow exceptions */ true , /* ignore_comments */ true ); std :: cout << j . dump ( 2 ) << '\\n' ; } Output: [json.exception.parse_error.101] parse error at line 3, column 9: syntax error while parsing object key - invalid literal; last read: ' { /'; expected string literal { \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" ] }","title":"Comments"},{"location":"features/enum_conversion/","text":"Specializing enum conversion \u00b6 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 enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 , }; // map TaskState values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" }, }) 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. Usage \u00b6 // enum to JSON as string json j = TS_STOPPED ; assert ( j == \"stopped\" ); // json string to enum json j3 = \"running\" ; assert ( j3 . template get < TaskState > () == TS_RUNNING ); // undefined json value to enum (where the first map entry above is the default) json jPi = 3.14 ; assert ( jPi . template get < TaskState > () == TS_INVALID ); Notes \u00b6 Just as in Arbitrary Type Conversions above, NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization. It MUST be available (e.g., proper headers must be included) everywhere you use the conversions. Other Important points: When using template get() , 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 .","title":"Specializing enum conversion"},{"location":"features/enum_conversion/#specializing-enum-conversion","text":"By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended. It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below: // example enum type declaration enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 , }; // map TaskState values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" }, }) 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.","title":"Specializing enum conversion"},{"location":"features/enum_conversion/#usage","text":"// enum to JSON as string json j = TS_STOPPED ; assert ( j == \"stopped\" ); // json string to enum json j3 = \"running\" ; assert ( j3 . template get < TaskState > () == TS_RUNNING ); // undefined json value to enum (where the first map entry above is the default) json jPi = 3.14 ; assert ( jPi . template get < TaskState > () == TS_INVALID );","title":"Usage"},{"location":"features/enum_conversion/#notes","text":"Just as in Arbitrary Type Conversions above, NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization. It MUST be available (e.g., proper headers must be included) everywhere you use the conversions. Other Important points: When using template get() , 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 .","title":"Notes"},{"location":"features/iterators/","text":"Iterators \u00b6 Overview \u00b6 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() . Iteration order for objects \u00b6 When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less . See the types documentation for more information. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 1 3 2 The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\". Access object key during iteration \u00b6 The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << it . key () << \" : \" << it . value () << std :: endl ; } Output: o ne : 1 t hree : 3 t wo : 2 Range-based for loops \u00b6 C++11 allows using range-based for loops to iterate over a container. for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\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 ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; } Note When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string. Warning Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information. Reverse iteration order \u00b6 rbegin() and rend() return iterators in the reverse sequence. Example json j = { 1 , 2 , 3 , 4 }; for ( auto it = j . rbegin (); it != j . rend (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 4 3 2 1 Iterating strings and binary values \u00b6 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\" ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: \"Hello, world\" Iterator invalidation \u00b6 Operations invalidated iterators clear all","title":"Iterators"},{"location":"features/iterators/#iterators","text":"","title":"Iterators"},{"location":"features/iterators/#overview","text":"A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values. As for other containers, begin() returns an iterator to the first value and end() returns an iterator to the value following the last value. The latter iterator is a placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, begin() will return end() .","title":"Overview"},{"location":"features/iterators/#iteration-order-for-objects","text":"When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less . See the types documentation for more information. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 1 3 2 The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".","title":"Iteration order for objects"},{"location":"features/iterators/#access-object-key-during-iteration","text":"The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << it . key () << \" : \" << it . value () << std :: endl ; } Output: o ne : 1 t hree : 3 t wo : 2","title":"Access object key during iteration"},{"location":"features/iterators/#range-based-for-loops","text":"C++11 allows using range-based for loops to iterate over a container. for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\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 ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; } Note When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string. Warning Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.","title":"Range-based for loops"},{"location":"features/iterators/#reverse-iteration-order","text":"rbegin() and rend() return iterators in the reverse sequence. Example json j = { 1 , 2 , 3 , 4 }; for ( auto it = j . rbegin (); it != j . rend (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 4 3 2 1","title":"Reverse iteration order"},{"location":"features/iterators/#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\" ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: \"Hello, world\"","title":"Iterating strings and binary values"},{"location":"features/iterators/#iterator-invalidation","text":"Operations invalidated iterators clear all","title":"Iterator invalidation"},{"location":"features/json_patch/","text":"JSON Patch and Diff \u00b6 Patches \u00b6 JSON Patch ( RFC 6902 ) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } Diff \u00b6 The library can also calculate a JSON patch (i.e., a diff ) given two JSON values. Invariant For two JSON values source and target , the following code yields always true: source.patch(diff(source, target)) == target; Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"JSON Patch and Diff"},{"location":"features/json_patch/#json-patch-and-diff","text":"","title":"JSON Patch and Diff"},{"location":"features/json_patch/#patches","text":"JSON Patch ( RFC 6902 ) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Patches"},{"location":"features/json_patch/#diff","text":"The library can also calculate a JSON patch (i.e., a diff ) given two JSON values. Invariant For two JSON values source and target , the following code yields always true: source.patch(diff(source, target)) == target; Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Diff"},{"location":"features/json_pointer/","text":"JSON Pointer \u00b6 Introduction \u00b6 The library supports JSON Pointer ( RFC 6901 ) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document. Consider the following JSON document { \"array\" : [ \"A\" , \"B\" , \"C\" ], \"nested\" : { \"one\" : 1 , \"two\" : 2 , \"three\" : [ true , false ] } } Then every value inside the JSON document can be identified as follows: JSON Pointer JSON value `` { \"array\" :[ \"A\" , \"B\" , \"C\" ], \"nested\" :{ \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]}} /array [ \"A\" , \"B\" , \"C\" ] /array/0 A /array/1 B /array/2 C /nested { \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]} /nested/one 1 /nested/two 2 /nested/three [ true , false ] /nested/three/0 true /nested/three/1 false Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\" . See RFC 6901 for more information. JSON Pointer creation \u00b6 JSON Pointers can be created from a string: json :: json_pointer p = \"/nested/one\" ; Furthermore, a user-defined string literal can be used to achieve the same result: auto p = \"/nested/one\" _json_pointer ; The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information. Value access \u00b6 JSON Pointers can be used in the at , operator[] , and value functions just like object keys or array indices. // the JSON value from above auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // access values auto val = j [ \"/\" _json_pointer ]; // {\"array\":[\"A\",\"B\",\"C\"],...} auto val1 = j [ \"/nested/one\" _json_pointer ]; // 1 auto val2 = j . at [ json :: json_pointer ( \"/nested/three/1\" )]; // false auto val3 = j . value [ json :: json_pointer ( \"/nested/four\" , 0 )]; // 0 Flatten / unflatten \u00b6 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 auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // create flattened value auto j_flat = j . flatten (); The resulting value j_flat is: { \"/array/0\" : \"A\" , \"/array/1\" : \"B\" , \"/array/2\" : \"C\" , \"/nested/one\" : 1 , \"/nested/two\" : 2 , \"/nested/three/0\" : true , \"/nested/three/1\" : false } The reverse function, unflatten recreates the original value. auto j_original = j_flat . unflatten (); See also \u00b6 Class json_pointer Function flatten Function unflatten JSON Patch","title":"JSON Pointer"},{"location":"features/json_pointer/#json-pointer","text":"","title":"JSON Pointer"},{"location":"features/json_pointer/#introduction","text":"The library supports JSON Pointer ( RFC 6901 ) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document. Consider the following JSON document { \"array\" : [ \"A\" , \"B\" , \"C\" ], \"nested\" : { \"one\" : 1 , \"two\" : 2 , \"three\" : [ true , false ] } } Then every value inside the JSON document can be identified as follows: JSON Pointer JSON value `` { \"array\" :[ \"A\" , \"B\" , \"C\" ], \"nested\" :{ \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]}} /array [ \"A\" , \"B\" , \"C\" ] /array/0 A /array/1 B /array/2 C /nested { \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]} /nested/one 1 /nested/two 2 /nested/three [ true , false ] /nested/three/0 true /nested/three/1 false Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\" . See RFC 6901 for more information.","title":"Introduction"},{"location":"features/json_pointer/#json-pointer-creation","text":"JSON Pointers can be created from a string: json :: json_pointer p = \"/nested/one\" ; Furthermore, a user-defined string literal can be used to achieve the same result: auto p = \"/nested/one\" _json_pointer ; The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.","title":"JSON Pointer creation"},{"location":"features/json_pointer/#value-access","text":"JSON Pointers can be used in the at , operator[] , and value functions just like object keys or array indices. // the JSON value from above auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // access values auto val = j [ \"/\" _json_pointer ]; // {\"array\":[\"A\",\"B\",\"C\"],...} auto val1 = j [ \"/nested/one\" _json_pointer ]; // 1 auto val2 = j . at [ json :: json_pointer ( \"/nested/three/1\" )]; // false auto val3 = j . value [ json :: json_pointer ( \"/nested/four\" , 0 )]; // 0","title":"Value access"},{"location":"features/json_pointer/#flatten-unflatten","text":"The library implements a function flatten to convert any JSON document into a JSON object where each key is a JSON Pointer and each value is a primitive JSON value (i.e., a string, boolean, number, or null). // the JSON value from above auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // create flattened value auto j_flat = j . flatten (); The resulting value j_flat is: { \"/array/0\" : \"A\" , \"/array/1\" : \"B\" , \"/array/2\" : \"C\" , \"/nested/one\" : 1 , \"/nested/two\" : 2 , \"/nested/three/0\" : true , \"/nested/three/1\" : false } The reverse function, unflatten recreates the original value. auto j_original = j_flat . unflatten ();","title":"Flatten / unflatten"},{"location":"features/json_pointer/#see-also","text":"Class json_pointer Function flatten Function unflatten JSON Patch","title":"See also"},{"location":"features/macros/","text":"Supported Macros \u00b6 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. JSON_ASSERT(x) \u00b6 This macro controls which code is executed for runtime assertions of the library. See full documentation of JSON_ASSERT(x) . JSON_CATCH_USER(exception) \u00b6 This macro overrides catch calls inside the library. See full documentation of JSON_CATCH_USER(exception) . JSON_DIAGNOSTICS \u00b6 This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default). When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead. The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which sets JSON_DIAGNOSTICS accordingly. See full documentation of JSON_DIAGNOSTICS . JSON_HAS_CPP_11 , JSON_HAS_CPP_14 , JSON_HAS_CPP_17 , JSON_HAS_CPP_20 \u00b6 The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly. See full documentation of JSON_HAS_CPP_11 , JSON_HAS_CPP_14 , JSON_HAS_CPP_17 , and JSON_HAS_CPP_20 . JSON_HAS_FILESYSTEM , JSON_HAS_EXPERIMENTAL_FILESYSTEM \u00b6 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 / std::filesystem ( JSON_HAS_FILESYSTEM ) or / std::experimental::filesystem ( JSON_HAS_EXPERIMENTAL_FILESYSTEM ) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1 . See full documentation of JSON_HAS_FILESYSTEM and JSON_HAS_EXPERIMENTAL_FILESYSTEM . JSON_NOEXCEPTION \u00b6 Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION . See full documentation of JSON_NOEXCEPTION . JSON_DISABLE_ENUM_SERIALIZATION \u00b6 When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM . See full documentation of JSON_DISABLE_ENUM_SERIALIZATION . JSON_NO_IO \u00b6 When defined, headers , , , , and are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)). See full documentation of JSON_NO_IO . JSON_SKIP_LIBRARY_VERSION_CHECK \u00b6 When defined, the library will not create a compiler warning when a different version of the library was already included. See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK . JSON_SKIP_UNSUPPORTED_COMPILER_CHECK \u00b6 When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used. See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK . JSON_THROW_USER(exception) \u00b6 This macro overrides throw calls inside the library. The argument is the exception to be thrown. See full documentation of JSON_THROW_USER(exception) . JSON_TRY_USER \u00b6 This macro overrides try calls inside the library. See full documentation of JSON_TRY_USER . JSON_USE_IMPLICIT_CONVERSIONS \u00b6 When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. See full documentation of JSON_USE_IMPLICIT_CONVERSIONS . NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) \u00b6 This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE , it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE . NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) \u00b6 This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT . NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) \u00b6 This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) \u00b6 This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT . NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) \u00b6 This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information. See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM . NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , NLOHMANN_JSON_VERSION_PATCH \u00b6 These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 . See full documentation of NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH .","title":"Supported Macros"},{"location":"features/macros/#supported-macros","text":"Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.","title":"Supported Macros"},{"location":"features/macros/#json_assertx","text":"This macro controls which code is executed for runtime assertions of the library. See full documentation of JSON_ASSERT(x) .","title":"JSON_ASSERT(x)"},{"location":"features/macros/#json_catch_userexception","text":"This macro overrides catch calls inside the library. See full documentation of JSON_CATCH_USER(exception) .","title":"JSON_CATCH_USER(exception)"},{"location":"features/macros/#json_diagnostics","text":"This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default). When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead. The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which sets JSON_DIAGNOSTICS accordingly. See full documentation of JSON_DIAGNOSTICS .","title":"JSON_DIAGNOSTICS"},{"location":"features/macros/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","text":"The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly. See full documentation of JSON_HAS_CPP_11 , JSON_HAS_CPP_14 , JSON_HAS_CPP_17 , and JSON_HAS_CPP_20 .","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20"},{"location":"features/macros/#json_has_filesystem-json_has_experimental_filesystem","text":"When compiling with C++17, the library provides conversions from and to std::filesystem::path . As compiler support for filesystem is limited, the library tries to detect whether / std::filesystem ( JSON_HAS_FILESYSTEM ) or / 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 .","title":"JSON_HAS_FILESYSTEM, JSON_HAS_EXPERIMENTAL_FILESYSTEM"},{"location":"features/macros/#json_noexception","text":"Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION . See full documentation of JSON_NOEXCEPTION .","title":"JSON_NOEXCEPTION"},{"location":"features/macros/#json_disable_enum_serialization","text":"When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM . See full documentation of JSON_DISABLE_ENUM_SERIALIZATION .","title":"JSON_DISABLE_ENUM_SERIALIZATION"},{"location":"features/macros/#json_no_io","text":"When defined, headers , , , , and are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)). See full documentation of JSON_NO_IO .","title":"JSON_NO_IO"},{"location":"features/macros/#json_skip_library_version_check","text":"When defined, the library will not create a compiler warning when a different version of the library was already included. See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK .","title":"JSON_SKIP_LIBRARY_VERSION_CHECK"},{"location":"features/macros/#json_skip_unsupported_compiler_check","text":"When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used. See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK .","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK"},{"location":"features/macros/#json_throw_userexception","text":"This macro overrides throw calls inside the library. The argument is the exception to be thrown. See full documentation of JSON_THROW_USER(exception) .","title":"JSON_THROW_USER(exception)"},{"location":"features/macros/#json_try_user","text":"This macro overrides try calls inside the library. See full documentation of JSON_TRY_USER .","title":"JSON_TRY_USER"},{"location":"features/macros/#json_use_implicit_conversions","text":"When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. See full documentation of JSON_USE_IMPLICIT_CONVERSIONS .","title":"JSON_USE_IMPLICIT_CONVERSIONS"},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE , it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE .","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)"},{"location":"features/macros/#nlohmann_define_type_intrusive_with_defaulttype-member","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT .","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)"},{"location":"features/macros/#nlohmann_define_type_non_intrusivetype-member","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE .","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_with_defaulttype-member","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT .","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)"},{"location":"features/macros/#nlohmann_json_serialize_enumtype","text":"This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information. See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM .","title":"NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)"},{"location":"features/macros/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","text":"These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 . See full documentation of NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH .","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH"},{"location":"features/merge_patch/","text":"JSON Merge Patch \u00b6 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 #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" }","title":"JSON Merge Patch"},{"location":"features/merge_patch/#json-merge-patch","text":"The library supports JSON Merge Patch ( RFC 7386 ) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value. Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified. Example The following code shows how a JSON Merge Patch is applied to a JSON document. #include #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" }","title":"JSON Merge Patch"},{"location":"features/namespace/","text":"nlohmann Namespace \u00b6 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. Structure \u00b6 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: nlohmann :: json_abi_diag_v3_11_2 Purpose \u00b6 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. Limitations \u00b6 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. Disabling the version component \u00b6 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! Disabling the inline namespace completely \u00b6 When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows: #define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann { #define NLOHMANN_JSON_NAMESPACE_END } Use at your own risk Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned! Version history \u00b6 Introduced inline namespace ( json_v3_11_0[_abi-tag]* ) in version 3.11.0. Changed structure of inline namespace in version 3.11.2.","title":"nlohmann Namespace"},{"location":"features/namespace/#nlohmann-namespace","text":"The 3.11.0 release introduced an inline namespace to allow different parts of a codebase to safely use different versions of the JSON library as long as they never exchange instances of library types.","title":"nlohmann Namespace"},{"location":"features/namespace/#structure","text":"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: nlohmann :: json_abi_diag_v3_11_2","title":"Structure"},{"location":"features/namespace/#purpose","text":"Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS . This is illustrated in the diagram below. In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.","title":"Purpose"},{"location":"features/namespace/#limitations","text":"Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types. There is an exception when forward declarations are used (i.e., when including json_fwd.hpp ) in which case the linker may complain about undefined references.","title":"Limitations"},{"location":"features/namespace/#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!","title":"Disabling the version component"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","text":"When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows: #define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann { #define NLOHMANN_JSON_NAMESPACE_END } Use at your own risk Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!","title":"Disabling the inline namespace completely"},{"location":"features/namespace/#version-history","text":"Introduced inline namespace ( json_v3_11_0[_abi-tag]* ) in version 3.11.0. Changed structure of inline namespace in version 3.11.2.","title":"Version history"},{"location":"features/object_order/","text":"Object Order \u00b6 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. Default behavior: sort keys \u00b6 The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically . Example #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Alternative behavior: preserve insertion order \u00b6 If you do want to preserve the insertion order , you can try the type nlohmann::ordered_json . Example #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map ( integration ) or nlohmann::fifo_map ( integration ). Notes on parsing \u00b6 Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Right way The following code correctly calls the parse function from nlohmann::ordered_json : std :: ifstream i ( \"input.json\" ); auto j = nlohmann :: ordered_json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Wrong way The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file. std :: ifstream i ( \"input.json\" ); nlohmann :: ordered_json j = nlohmann :: json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"three\" : 3 \"two\" : 2 , }","title":"Object Order"},{"location":"features/object_order/#object-order","text":"The JSON standard defines objects as \"an unordered collection of zero or more name/value pairs\". As such, an implementation does not need to preserve any specific order of object keys.","title":"Object Order"},{"location":"features/object_order/#default-behavior-sort-keys","text":"The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically . Example #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 }","title":"Default behavior: sort keys"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","text":"If you do want to preserve the insertion order , you can try the type nlohmann::ordered_json . Example #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map ( integration ) or nlohmann::fifo_map ( integration ).","title":"Alternative behavior: preserve insertion order"},{"location":"features/object_order/#notes-on-parsing","text":"Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Right way The following code correctly calls the parse function from nlohmann::ordered_json : std :: ifstream i ( \"input.json\" ); auto j = nlohmann :: ordered_json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Wrong way The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file. std :: ifstream i ( \"input.json\" ); nlohmann :: ordered_json j = nlohmann :: json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"three\" : 3 \"two\" : 2 , }","title":"Notes on parsing"},{"location":"features/binary_formats/","text":"Binary Formats \u00b6 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. Comparison \u00b6 Completeness \u00b6 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 Binary values \u00b6 Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported See binary values for more information. Sizes \u00b6 Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 % Sizes compared to minified JSON value.","title":"Binary Formats"},{"location":"features/binary_formats/#binary-formats","text":"Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports 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.","title":"Binary Formats"},{"location":"features/binary_formats/#comparison","text":"","title":"Comparison"},{"location":"features/binary_formats/#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","title":"Completeness"},{"location":"features/binary_formats/#binary-values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported See binary values for more information.","title":"Binary values"},{"location":"features/binary_formats/#sizes","text":"Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 % Sizes compared to minified JSON value.","title":"Sizes"},{"location":"features/binary_formats/bjdata/","text":"BJData \u00b6 The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays ( ND-arrays ); it also adds 4 new type markers - [u] - uint16 , [m] - uint32 , [M] - uint64 and [h] - float16 - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms. Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable . This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing. References BJData Specification Serialization \u00b6 The library uses the following mapping from JSON values types to BJData types according to the BJData specification: JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a BJData value. Any BJData output created by to_bjdata can be successfully parsed by from_bjdata . Size constraints The following values can not be converted to a BJData value: strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 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 { \"_ArrayType_\" : \"uint8\" , \"_ArraySize_\" : [ 2 , 3 ], \"_ArrayData_\" : [ 1 , 2 , 3 , 4 , 5 , 6 ] } Likewise, when a JSON object in the above form is serialzed using to_bjdata , it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated. The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array. Restrictions in optimized data types for arrays and objects Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of UiuImlMLhdDC . This also means other variable ( [{SH ) or zero-length types ( TFN ) can not be used in an optimized array or object in BJData. Binary values If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678 Deserialization \u00b6 The library maps BJData types to JSON value types as follows: BJData type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any BJData value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"BJData"},{"location":"features/binary_formats/bjdata/#bjdata","text":"The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays ( ND-arrays ); it also adds 4 new type markers - [u] - uint16 , [m] - uint32 , [M] - uint64 and [h] - float16 - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms. Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable . This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing. References BJData Specification","title":"BJData"},{"location":"features/binary_formats/bjdata/#serialization","text":"The library uses the following mapping from JSON values types to BJData types according to the BJData specification: JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a BJData value. Any BJData output created by to_bjdata can be successfully parsed by from_bjdata . Size constraints The following values can not be converted to a BJData value: strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 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 { \"_ArrayType_\" : \"uint8\" , \"_ArraySize_\" : [ 2 , 3 ], \"_ArrayData_\" : [ 1 , 2 , 3 , 4 , 5 , 6 ] } Likewise, when a JSON object in the above form is serialzed using to_bjdata , it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated. The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array. Restrictions in optimized data types for arrays and objects Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of UiuImlMLhdDC . This also means other variable ( [{SH ) or zero-length types ( TFN ) can not be used in an optimized array or object in BJData. Binary values If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678","title":"Serialization"},{"location":"features/binary_formats/bjdata/#deserialization","text":"The library maps BJData types to JSON value types as follows: BJData type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any BJData value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/bson/","text":"BSON \u00b6 BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. References BSON Website - the main source on BSON BSON Specification - the specification Serialization \u00b6 The library uses the following mapping from JSON values types to BSON types: JSON value type value/range BSON type marker null null null 0x0A boolean true , false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 Incomplete mapping The mapping is incomplete , since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 Deserialization \u00b6 The library maps BSON record types to JSON value types as follows: BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported Incomplete mapping The mapping is incomplete . The unsupported mappings are indicated in the table above. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"BSON"},{"location":"features/binary_formats/bson/#bson","text":"BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. References BSON Website - the main source on BSON BSON Specification - the specification","title":"BSON"},{"location":"features/binary_formats/bson/#serialization","text":"The library uses the following mapping from JSON values types to BSON types: JSON value type value/range BSON type marker null null null 0x0A boolean true , false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 Incomplete mapping The mapping is incomplete , since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00","title":"Serialization"},{"location":"features/binary_formats/bson/#deserialization","text":"The library maps BSON record types to JSON value types as follows: BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported Incomplete mapping The mapping is incomplete . The unsupported mappings are indicated in the table above. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/cbor/","text":"CBOR \u00b6 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 RFC 7049 - the CBOR specification Serialization \u00b6 The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification ( RFC 7049 ): JSON value type value/range CBOR type first byte null null Null 0xF6 boolean true True 0xF5 boolean false False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length : 0..23 UTF-8 string 0x60..0x77 string length : 23..255 UTF-8 string (1 byte follow) 0x78 string length : 256..65535 UTF-8 string (2 bytes follow) 0x79 string length : 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length : 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size : 0..23 array 0x80..0x97 array size : 23..255 array (1 byte follow) 0x98 array size : 256..65535 array (2 bytes follow) 0x99 array size : 65536..4294967295 array (4 bytes follow) 0x9A array size : 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size : 0..23 map 0xA0..0xB7 object size : 23..255 map (1 byte follow) 0xB8 object size : 256..65535 map (2 bytes follow) 0xB9 object size : 65536..4294967295 map (4 bytes follow) 0xBA object size : 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size : 0..23 byte string 0x40..0x57 binary size : 23..255 byte string (1 byte follow) 0x58 binary size : 256..65535 byte string (2 bytes follow) 0x59 binary size : 65536..4294967295 byte string (4 bytes follow) 0x5A binary size : 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above. Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a CBOR value. NaN/infinity handling If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to null . Unused CBOR types The following CBOR types are not used in the conversion: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 Deserialization \u00b6 The library maps CBOR types to JSON value types as follows: CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF False false 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB Incomplete mapping The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors: 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 . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"CBOR"},{"location":"features/binary_formats/cbor/#cbor","text":"The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation. References CBOR Website - the main source on CBOR CBOR Playground - an interactive webpage to translate between JSON and CBOR RFC 7049 - the CBOR specification","title":"CBOR"},{"location":"features/binary_formats/cbor/#serialization","text":"The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification ( RFC 7049 ): JSON value type value/range CBOR type first byte null null Null 0xF6 boolean true True 0xF5 boolean false False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length : 0..23 UTF-8 string 0x60..0x77 string length : 23..255 UTF-8 string (1 byte follow) 0x78 string length : 256..65535 UTF-8 string (2 bytes follow) 0x79 string length : 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length : 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size : 0..23 array 0x80..0x97 array size : 23..255 array (1 byte follow) 0x98 array size : 256..65535 array (2 bytes follow) 0x99 array size : 65536..4294967295 array (4 bytes follow) 0x9A array size : 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size : 0..23 map 0xA0..0xB7 object size : 23..255 map (1 byte follow) 0xB8 object size : 256..65535 map (2 bytes follow) 0xB9 object size : 65536..4294967295 map (4 bytes follow) 0xBA object size : 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size : 0..23 byte string 0x40..0x57 binary size : 23..255 byte string (1 byte follow) 0x58 binary size : 256..65535 byte string (2 bytes follow) 0x59 binary size : 65536..4294967295 byte string (4 bytes follow) 0x5A binary size : 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above. Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a CBOR value. NaN/infinity handling If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to null . Unused CBOR types The following CBOR types are not used in the conversion: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00","title":"Serialization"},{"location":"features/binary_formats/cbor/#deserialization","text":"The library maps CBOR types to JSON value types as follows: CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF False false 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB Incomplete mapping The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors: 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 . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/messagepack/","text":"MessagePack \u00b6 MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. References MessagePack website MessagePack specification Serialization \u00b6 The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type value/range MessagePack type first byte null null nil 0xC0 boolean true true 0xC3 boolean false false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length : 0..31 fixstr 0xA0..0xBF string length : 32..255 str 8 0xD9 string length : 256..65535 str 16 0xDA string length : 65536..4294967295 str 32 0xDB array size : 0..15 fixarray 0x90..0x9F array size : 16..65535 array 16 0xDC array size : 65536..4294967295 array 32 0xDD object size : 0..15 fix map 0x80..0x8F object size : 16..65535 map 16 0xDE object size : 65536..4294967295 map 32 0xDF binary size : 0..255 bin 8 0xC4 binary size : 256..65535 bin 16 0xC5 binary size : 65536..4294967295 bin 32 0xC6 Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value. Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Size constraints The following values can not be converted to a MessagePack value: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 Deserialization \u00b6 The library maps MessagePack types to JSON value types as follows: MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nil null 0xC0 false false 0xC2 true true 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF Info Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"MessagePack"},{"location":"features/binary_formats/messagepack/#messagepack","text":"MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. References MessagePack website MessagePack specification","title":"MessagePack"},{"location":"features/binary_formats/messagepack/#serialization","text":"The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type value/range MessagePack type first byte null null nil 0xC0 boolean true true 0xC3 boolean false false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length : 0..31 fixstr 0xA0..0xBF string length : 32..255 str 8 0xD9 string length : 256..65535 str 16 0xDA string length : 65536..4294967295 str 32 0xDB array size : 0..15 fixarray 0x90..0x9F array size : 16..65535 array 16 0xDC array size : 65536..4294967295 array 32 0xDD object size : 0..15 fix map 0x80..0x8F object size : 16..65535 map 16 0xDE object size : 65536..4294967295 map 32 0xDF binary size : 0..255 bin 8 0xC4 binary size : 256..65535 bin 16 0xC5 binary size : 65536..4294967295 bin 32 0xC6 Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value. Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Size constraints The following values can not be converted to a MessagePack value: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00","title":"Serialization"},{"location":"features/binary_formats/messagepack/#deserialization","text":"The library maps MessagePack types to JSON value types as follows: MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nil null 0xC0 false false 0xC2 true true 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF Info Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/ubjson/","text":"UBJSON \u00b6 Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON. References UBJSON Website Serialization \u00b6 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678 Deserialization \u00b6 The library maps UBJSON types to JSON value types as follows: UBJSON type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any UBJSON value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"UBJSON"},{"location":"features/binary_formats/ubjson/#ubjson","text":"Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON. References UBJSON Website","title":"UBJSON"},{"location":"features/binary_formats/ubjson/#serialization","text":"The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification: JSON value type value/range UBJSON type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map { Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value. Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson . Size constraints The following values can not be converted to a UBJSON value: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678","title":"Serialization"},{"location":"features/binary_formats/ubjson/#deserialization","text":"The library maps UBJSON types to JSON value types as follows: UBJSON type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any UBJSON value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/element_access/","text":"Element Access \u00b6 There are many ways elements in a JSON value can be accessed: unchecked access via operator[] checked access via at access with default value via value iterators JSON pointers","title":"Element Access"},{"location":"features/element_access/#element-access","text":"There are many ways elements in a JSON value can be accessed: unchecked access via operator[] checked access via at access with default value via value iterators JSON pointers","title":"Element Access"},{"location":"features/element_access/checked_access/","text":"Checked access: at \u00b6 Overview \u00b6 The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j . at ( \"name\" ) \"Mary Smith\" j . at ( \"age\" ) 42 j . at ( \"hobbies\" ) [ \"hiking\" , \"reading\" ] j . at ( \"hobbies\" ). at ( 0 ) \"hiking\" j . at ( \"hobbies\" ). at ( 1 ) \"reading\" The return value is a reference, so it can be modified by the original value. Write access j . at ( \"name\" ) = \"John Smith\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } 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\" ; This code produces the following exception: [json.exception.out_of_range.401] array index 3 is out of range 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 Notes \u00b6 Exceptions at can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown. basic_json::out_of_range exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid. Summary \u00b6 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","title":"Checked access: at"},{"location":"features/element_access/checked_access/#checked-access-at","text":"","title":"Checked access: at"},{"location":"features/element_access/checked_access/#overview","text":"The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j . at ( \"name\" ) \"Mary Smith\" j . at ( \"age\" ) 42 j . at ( \"hobbies\" ) [ \"hiking\" , \"reading\" ] j . at ( \"hobbies\" ). at ( 0 ) \"hiking\" j . at ( \"hobbies\" ). at ( 1 ) \"reading\" The return value is a reference, so it can be modified by the original value. Write access j . at ( \"name\" ) = \"John Smith\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } 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\" ; This code produces the following exception: [json.exception.out_of_range.401] array index 3 is out of range 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","title":"Overview"},{"location":"features/element_access/checked_access/#notes","text":"Exceptions at can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown. basic_json::out_of_range exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid.","title":"Notes"},{"location":"features/element_access/checked_access/#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","title":"Summary"},{"location":"features/element_access/default_value/","text":"Access with default value: value \u00b6 Overview \u00b6 In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. Example Consider the following JSON value: { \"logOutput\" : \"result.log\" , \"append\" : true } Assume the value is parsed to a json variable j . expression value j { \"logOutput\" : \"result.log\" , \"append\" : true } j . value ( \"logOutput\" , \"logfile.log\" ) \"result.log\" j . value ( \"append\" , true ) true j . value ( \"append\" , false ) true j . value ( \"logLevel\" , \"verbose\" ) \"verbose\" Note \u00b6 Exceptions value can only be used with objects. For other types, a basic_json::type_error is thrown.","title":"Access with default value: value"},{"location":"features/element_access/default_value/#access-with-default-value-value","text":"","title":"Access with default value: value"},{"location":"features/element_access/default_value/#overview","text":"In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. Example Consider the following JSON value: { \"logOutput\" : \"result.log\" , \"append\" : true } Assume the value is parsed to a json variable j . expression value j { \"logOutput\" : \"result.log\" , \"append\" : true } j . value ( \"logOutput\" , \"logfile.log\" ) \"result.log\" j . value ( \"append\" , true ) true j . value ( \"append\" , false ) true j . value ( \"logLevel\" , \"verbose\" ) \"verbose\"","title":"Overview"},{"location":"features/element_access/default_value/#note","text":"Exceptions value can only be used with objects. For other types, a basic_json::type_error is thrown.","title":"Note"},{"location":"features/element_access/unchecked_access/","text":"Unchecked access: operator[] \u00b6 Overview \u00b6 Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std :: map and a std :: vector , respectively. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j [ \"name\" ] \"Mary Smith\" j [ \"age\" ] 42 j [ \"hobbies\" ] [ \"hiking\" , \"reading\" ] j [ \"hobbies\" ][ 0 ] \"hiking\" j [ \"hobbies\" ][ 1 ] \"reading\" The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten. Write access j [ \"name\" ] = \"John Smith\" ; j [ \"maidenName\" ] = \"Jones\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with null . Filling up arrays with null values j [ \"hobbies\" ][ 0 ] = \"running\" ; j [ \"hobbies\" ][ 3 ] = \"cooking\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"running\" , \"reading\" , null , \"cooking\" ] } Notes \u00b6 Design rationale The library behaves differently to std :: vector and std :: map : std :: vector :: operator [] never inserts a new element. std :: map :: operator [] is not available for const values. The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects. Info The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown. Danger 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. Summary \u00b6 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","title":"Unchecked access: operator[]"},{"location":"features/element_access/unchecked_access/#unchecked-access-operator","text":"","title":"Unchecked access: operator[]"},{"location":"features/element_access/unchecked_access/#overview","text":"Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std :: map and a std :: vector , respectively. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j [ \"name\" ] \"Mary Smith\" j [ \"age\" ] 42 j [ \"hobbies\" ] [ \"hiking\" , \"reading\" ] j [ \"hobbies\" ][ 0 ] \"hiking\" j [ \"hobbies\" ][ 1 ] \"reading\" The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten. Write access j [ \"name\" ] = \"John Smith\" ; j [ \"maidenName\" ] = \"Jones\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with null . Filling up arrays with null values j [ \"hobbies\" ][ 0 ] = \"running\" ; j [ \"hobbies\" ][ 3 ] = \"cooking\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"running\" , \"reading\" , null , \"cooking\" ] }","title":"Overview"},{"location":"features/element_access/unchecked_access/#notes","text":"Design rationale The library behaves differently to std :: vector and std :: map : std :: vector :: operator [] never inserts a new element. std :: map :: operator [] is not available for const values. The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects. Info The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown. Danger 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.","title":"Notes"},{"location":"features/element_access/unchecked_access/#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","title":"Summary"},{"location":"features/parsing/","text":"Parsing \u00b6 Note This page is under construction. Input \u00b6 SAX vs. DOM parsing \u00b6 Exceptions \u00b6 See parsing and exceptions .","title":"Parsing"},{"location":"features/parsing/#parsing","text":"Note This page is under construction.","title":"Parsing"},{"location":"features/parsing/#input","text":"","title":"Input"},{"location":"features/parsing/#sax-vs-dom-parsing","text":"","title":"SAX vs. DOM parsing"},{"location":"features/parsing/#exceptions","text":"See parsing and exceptions .","title":"Exceptions"},{"location":"features/parsing/json_lines/","text":"JSON Lines \u00b6 The JSON Lines format is a text format of newline-delimited JSON. In particular: The input must be UTF-8 encoded. Every line must be a valid JSON value. The line separator must be \\n . As \\r is silently ignored, \\r\\n is also supported. The final character may be \\n , but is not required to be one. JSON Text example { \"name\" : \"Gilbert\" , \"wins\" : [[ \"straight\" , \"7\u2663\" ], [ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" : [[ \"two pair\" , \"4\u2660\" ], [ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" : []} { \"name\" : \"Deloise\" , \"wins\" : [[ \"three of a kind\" , \"5\u2663\" ]]} JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used: Example: Parse JSON Text input line by line The example below demonstrates how JSON Lines can be processed. #include #include #include using json = nlohmann :: json ; int main () { // JSON Lines (see https://jsonlines.org) std :: stringstream input ; input << R \" ( {\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]} {\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]} {\"name\": \"May\", \"wins\": []} {\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]} ) \" ; std :: string line ; while ( std :: getline ( input , line )) { std :: cout << json :: parse ( line ) << std :: endl ; } } Output: { \"name\" : \"Gilbert\" , \"wins\" :[[ \"straight\" , \"7\u2663\" ],[ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" :[[ \"two pair\" , \"4\u2660\" ],[ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" :[]} { \"name\" : \"Deloise\" , \"wins\" :[[ \"three of a kind\" , \"5\u2663\" ]]} Note Using operator>> like json j ; while ( input >> j ) { std :: cout << j << std :: endl ; } with a JSON Lines input does not work, because the parser will try to parse one value after the last one.","title":"JSON Lines"},{"location":"features/parsing/json_lines/#json-lines","text":"The JSON Lines format is a text format of newline-delimited JSON. In particular: The input must be UTF-8 encoded. Every line must be a valid JSON value. The line separator must be \\n . As \\r is silently ignored, \\r\\n is also supported. The final character may be \\n , but is not required to be one. JSON Text example { \"name\" : \"Gilbert\" , \"wins\" : [[ \"straight\" , \"7\u2663\" ], [ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" : [[ \"two pair\" , \"4\u2660\" ], [ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" : []} { \"name\" : \"Deloise\" , \"wins\" : [[ \"three of a kind\" , \"5\u2663\" ]]} JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used: Example: Parse JSON Text input line by line The example below demonstrates how JSON Lines can be processed. #include #include #include using json = nlohmann :: json ; int main () { // JSON Lines (see https://jsonlines.org) std :: stringstream input ; input << R \" ( {\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]} {\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]} {\"name\": \"May\", \"wins\": []} {\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]} ) \" ; std :: string line ; while ( std :: getline ( input , line )) { std :: cout << json :: parse ( line ) << std :: endl ; } } Output: { \"name\" : \"Gilbert\" , \"wins\" :[[ \"straight\" , \"7\u2663\" ],[ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" :[[ \"two pair\" , \"4\u2660\" ],[ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" :[]} { \"name\" : \"Deloise\" , \"wins\" :[[ \"three of a kind\" , \"5\u2663\" ]]} Note Using operator>> like json j ; while ( input >> j ) { std :: cout << j << std :: endl ; } with a JSON Lines input does not work, because the parser will try to parse one value after the last one.","title":"JSON Lines"},{"location":"features/parsing/parse_exceptions/","text":"Parsing and Exceptions \u00b6 When the input is not valid JSON, an exception of type parse_error is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions . In case you process untrusted input, always enclose your code with a try / catch block, like json j ; try { j = json :: parse ( my_input ); } catch ( json :: parse_error & ex ) { std :: cerr << \"parse error at byte \" << ex . byte << std :: endl ; } In case exceptions are undesired or not supported by the environment, there are different ways to proceed: Switch off exceptions \u00b6 The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs ( true , default) or whether a discarded value should be returned ( false ). json j = json :: parse ( my_input , nullptr , false ); if ( j . is_discarded ()) { std :: cerr << \"parse error\" << std :: endl ; } Note there is no diagnostic information available in this scenario. Use accept() function \u00b6 Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON. if ( ! json :: accept ( my_input )) { std :: cerr << \"parse error\" << std :: endl ; } Again, there is no diagnostic information available. User-defined SAX interface \u00b6 Finally, you can implement the SAX interface and decide what should happen in case of a parse error. This function has the following interface: bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); The return value indicates whether the parsing should continue, so the function should usually return false . Example #include #include \"json.hpp\" using json = nlohmann :: json ; class sax_no_exception : public nlohmann :: detail :: json_sax_dom_parser < json > { public : sax_no_exception ( json & j ) : nlohmann :: detail :: json_sax_dom_parser < json > ( j , false ) {} bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) { std :: cerr << \"parse error at input byte \" << position << \" \\n \" << ex . what () << \" \\n \" << \"last read: \\\" \" << last_token << \" \\\" \" << std :: endl ; return false ; } }; int main () { std :: string myinput = \"[1,2,3,]\" ; json result ; sax_no_exception sax ( result ); bool parse_result = json :: sax_parse ( myinput , & sax ); if ( ! parse_result ) { std :: cerr << \"parsing unsuccessful!\" << std :: endl ; } std :: cout << \"parsed value: \" << result << std :: endl ; } Output: parse error at input byte 8 [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal last read: \"3,]\" parsing unsuccessful! parsed value: [1,2,3]","title":"Parsing and Exceptions"},{"location":"features/parsing/parse_exceptions/#parsing-and-exceptions","text":"When the input is not valid JSON, an exception of type parse_error is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions . In case you process untrusted input, always enclose your code with a try / catch block, like json j ; try { j = json :: parse ( my_input ); } catch ( json :: parse_error & ex ) { std :: cerr << \"parse error at byte \" << ex . byte << std :: endl ; } In case exceptions are undesired or not supported by the environment, there are different ways to proceed:","title":"Parsing and Exceptions"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","text":"The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs ( true , default) or whether a discarded value should be returned ( false ). json j = json :: parse ( my_input , nullptr , false ); if ( j . is_discarded ()) { std :: cerr << \"parse error\" << std :: endl ; } Note there is no diagnostic information available in this scenario.","title":"Switch off exceptions"},{"location":"features/parsing/parse_exceptions/#use-accept-function","text":"Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON. if ( ! json :: accept ( my_input )) { std :: cerr << \"parse error\" << std :: endl ; } Again, there is no diagnostic information available.","title":"Use accept() function"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","text":"Finally, you can implement the SAX interface and decide what should happen in case of a parse error. This function has the following interface: bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); The return value indicates whether the parsing should continue, so the function should usually return false . Example #include #include \"json.hpp\" using json = nlohmann :: json ; class sax_no_exception : public nlohmann :: detail :: json_sax_dom_parser < json > { public : sax_no_exception ( json & j ) : nlohmann :: detail :: json_sax_dom_parser < json > ( j , false ) {} bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) { std :: cerr << \"parse error at input byte \" << position << \" \\n \" << ex . what () << \" \\n \" << \"last read: \\\" \" << last_token << \" \\\" \" << std :: endl ; return false ; } }; int main () { std :: string myinput = \"[1,2,3,]\" ; json result ; sax_no_exception sax ( result ); bool parse_result = json :: sax_parse ( myinput , & sax ); if ( ! parse_result ) { std :: cerr << \"parsing unsuccessful!\" << std :: endl ; } std :: cout << \"parsed value: \" << result << std :: endl ; } Output: parse error at input byte 8 [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal last read: \"3,]\" parsing unsuccessful! parsed value: [1,2,3]","title":"User-defined SAX interface"},{"location":"features/parsing/parser_callbacks/","text":"Parser Callbacks \u00b6 Overview \u00b6 With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. The type of the callback function is: template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ; Callback event types \u00b6 We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example When parsing the following JSON text, { \"name\" : \"Berlin\" , \"location\" : [ 52.519444 , 13.406667 ] } these calls are made to the callback function: event depth parsed object_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [ 52.519444 , 13.406667 ] object_end 0 { \"location\" :[ 52.519444 , 13.406667 ], \"name\" : \"Berlin\" } Return value \u00b6 Discarding a value (i.e., returning false ) has different effects depending on the context in which the 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. Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } }","title":"Parser Callbacks"},{"location":"features/parsing/parser_callbacks/#parser-callbacks","text":"","title":"Parser Callbacks"},{"location":"features/parsing/parser_callbacks/#overview","text":"With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. The type of the callback function is: template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ;","title":"Overview"},{"location":"features/parsing/parser_callbacks/#callback-event-types","text":"We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example When parsing the following JSON text, { \"name\" : \"Berlin\" , \"location\" : [ 52.519444 , 13.406667 ] } these calls are made to the callback function: event depth parsed object_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [ 52.519444 , 13.406667 ] object_end 0 { \"location\" :[ 52.519444 , 13.406667 ], \"name\" : \"Berlin\" }","title":"Callback event types"},{"location":"features/parsing/parser_callbacks/#return-value","text":"Discarding a value (i.e., returning false ) has different effects depending on the context in which the 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. Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } }","title":"Return value"},{"location":"features/parsing/sax_interface/","text":"SAX Interface \u00b6 The library uses a SAX-like interface with the following functions: // called when null is parsed bool null (); // called when a boolean is parsed; value is passed bool boolean ( bool val ); // called when a signed or unsigned integer number is parsed; value is passed bool number_integer ( number_integer_t val ); bool number_unsigned ( number_unsigned_t val ); // called when a floating-point number is parsed; value and original string is passed bool number_float ( number_float_t val , const string_t & s ); // called when a string is parsed; value is passed and can be safely moved away bool string ( string_t & val ); // called when a binary value is parsed; value is passed and can be safely moved away bool binary ( binary & val ); // called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known) bool start_object ( std :: size_t elements ); bool end_object (); bool start_array ( std :: size_t elements ); bool end_array (); // called when an object key is parsed; value is passed and can be safely moved away bool key ( string_t & val ); // called when a parse error occurs; byte position, the last token, and an exception is passed bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); 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 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 . See also \u00b6 json_sax - documentation of the SAX interface sax_parse - SAX parser","title":"SAX Interface"},{"location":"features/parsing/sax_interface/#sax-interface","text":"The library uses a SAX-like interface with the following functions: // called when null is parsed bool null (); // called when a boolean is parsed; value is passed bool boolean ( bool val ); // called when a signed or unsigned integer number is parsed; value is passed bool number_integer ( number_integer_t val ); bool number_unsigned ( number_unsigned_t val ); // called when a floating-point number is parsed; value and original string is passed bool number_float ( number_float_t val , const string_t & s ); // called when a string is parsed; value is passed and can be safely moved away bool string ( string_t & val ); // called when a binary value is parsed; value is passed and can be safely moved away bool binary ( binary & val ); // called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known) bool start_object ( std :: size_t elements ); bool end_object (); bool start_array ( std :: size_t elements ); bool end_array (); // called when an object key is parsed; value is passed and can be safely moved away bool key ( string_t & val ); // called when a parse error occurs; byte position, the last token, and an exception is passed bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); 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 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 .","title":"SAX Interface"},{"location":"features/parsing/sax_interface/#see-also","text":"json_sax - documentation of the SAX interface sax_parse - SAX parser","title":"See also"},{"location":"features/types/","text":"Types \u00b6 This page gives an overview how JSON values are stored and how this can be configured. Overview \u00b6 By default, JSON values are stored as follows: JSON type C++ type object std::map array std::vector 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. Storage \u00b6 Template arguments \u00b6 The data types to store a JSON value are derived from the template arguments passed to class basic_json : template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > > class basic_json ; Type json is an alias for basic_json<> and uses the default types. From the template arguments, the following types are derived: using object_comparator_t = std :: less <> ; using object_t = ObjectType < StringType , basic_json , object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; using string_t = StringType ; using boolean_t = BooleanType ; using number_integer_t = NumberIntegerType ; using number_unsigned_t = NumberUnsignedType ; using number_float_t = NumberFloatType ; using binary_t = nlohmann :: byte_container_with_subtype < BinaryType > ; Objects \u00b6 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. Default type \u00b6 With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > Behavior \u00b6 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. Key order \u00b6 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. Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object. Storage \u00b6 Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced. Arrays \u00b6 RFC 8259 describes JSON arrays as follows: An array is an ordered sequence of zero or more values. Default type \u00b6 With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type > Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array. Storage \u00b6 Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced. Strings \u00b6 RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. Unicode values are split by the JSON class into byte-sized characters during deserialization. Default type \u00b6 With the default values for StringType ( std::string ), the default value for string_t is std :: string . Encoding \u00b6 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. String comparison \u00b6 RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit. Storage \u00b6 String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced. Booleans \u00b6 RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false . Default type \u00b6 With the default values for BooleanType ( bool ), the default value for boolean_t is bool . Storage \u00b6 Boolean values are stored directly inside a basic_json type. Numbers \u00b6 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. Default types \u00b6 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 . Default behavior \u00b6 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 . Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 ( INT64_MAX ) and the minimal integer number that can be stored is -9223372036854775808 ( INT64_MIN ). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 ( UINT64_MAX ) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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 . Storage \u00b6 Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.","title":"Types"},{"location":"features/types/#types","text":"This page gives an overview how JSON values are stored and how this can be configured.","title":"Types"},{"location":"features/types/#overview","text":"By default, JSON values are stored as follows: JSON type C++ type object std::map array std::vector 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.","title":"Overview"},{"location":"features/types/#storage","text":"","title":"Storage"},{"location":"features/types/#template-arguments","text":"The data types to store a JSON value are derived from the template arguments passed to class basic_json : template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > > class basic_json ; Type json is an alias for basic_json<> and uses the default types. From the template arguments, the following types are derived: using object_comparator_t = std :: less <> ; using object_t = ObjectType < StringType , basic_json , object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; using string_t = StringType ; using boolean_t = BooleanType ; using number_integer_t = NumberIntegerType ; using number_unsigned_t = NumberUnsignedType ; using number_float_t = NumberFloatType ; using binary_t = nlohmann :: byte_container_with_subtype < BinaryType > ;","title":"Template arguments"},{"location":"features/types/#objects","text":"RFC 8259 describes JSON objects as follows: An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.","title":"Objects"},{"location":"features/types/#default-type","text":"With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type >","title":"Default type"},{"location":"features/types/#behavior","text":"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.","title":"Behavior"},{"location":"features/types/#key-order","text":"The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259 , because any order implements the specified \"unordered\" nature of JSON objects.","title":"Key order"},{"location":"features/types/#limits","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.","title":"Limits"},{"location":"features/types/#storage_1","text":"Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.","title":"Storage"},{"location":"features/types/#arrays","text":"RFC 8259 describes JSON arrays as follows: An array is an ordered sequence of zero or more values.","title":"Arrays"},{"location":"features/types/#default-type_1","text":"With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type >","title":"Default type"},{"location":"features/types/#limits_1","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.","title":"Limits"},{"location":"features/types/#storage_2","text":"Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.","title":"Storage"},{"location":"features/types/#strings","text":"RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. Unicode values are split by the JSON class into byte-sized characters during deserialization.","title":"Strings"},{"location":"features/types/#default-type_2","text":"With the default values for StringType ( std::string ), the default value for string_t is std :: string .","title":"Default type"},{"location":"features/types/#encoding","text":"Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.","title":"Encoding"},{"location":"features/types/#string-comparison","text":"RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit.","title":"String comparison"},{"location":"features/types/#storage_3","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.","title":"Storage"},{"location":"features/types/#booleans","text":"RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false .","title":"Booleans"},{"location":"features/types/#default-type_3","text":"With the default values for BooleanType ( bool ), the default value for boolean_t is bool .","title":"Default type"},{"location":"features/types/#storage_4","text":"Boolean values are stored directly inside a basic_json type.","title":"Storage"},{"location":"features/types/#numbers","text":"See the number handling article for a detailed discussion on how numbers are handled by this library. RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t , and number_float_t are used.","title":"Numbers"},{"location":"features/types/#default-types","text":"With the default values for NumberIntegerType ( std::int64_t ), the default value for number_integer_t is std::int64_t . With the default values for NumberUnsignedType ( std::uint64_t ), the default value for number_unsigned_t is std::uint64_t . With the default values for NumberFloatType ( double ), the default value for number_float_t is double .","title":"Default types"},{"location":"features/types/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"features/types/#limits_2","text":"RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 ( INT64_MAX ) and the minimal integer number that can be stored is -9223372036854775808 ( INT64_MIN ). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 ( UINT64_MAX ) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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 .","title":"Limits"},{"location":"features/types/#storage_5","text":"Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"features/types/number_handling/","text":"Number Handling \u00b6 This document describes how the library is handling numbers. Background \u00b6 This section briefly summarizes how the JSON specification describes how numbers should be handled. JSON number syntax \u00b6 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: Number interoperability \u00b6 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] [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values. Library implementation \u00b6 This section describes how the above number specification is implemented by this library. Number storage \u00b6 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 . Number limits \u00b6 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] [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1] [-2^{53}+1, 2^{53}-1] . All integers outside the range [-2^{63}, 2^{64}-1] [-2^{63}, 2^{64}-1] , as well as floating-point numbers are stored as double . This also concurs with the specification above. Zeros \u00b6 The JSON number grammar allows for different ways to express zero, and this library will store zeros differently: Literal Stored value and type Serialization 0 std :: uint64_t ( 0 ) 0 -0 std :: int64_t ( 0 ) 0 0.0 double ( 0.0 ) 0.0 -0.0 double ( -0.0 ) -0.0 0E0 double ( 0.0 ) 0.0 -0E0 double ( -0.0 ) -0.0 That is, -0 is stored as a signed integer, but the serialization does not reproduce the - . Number serialization \u00b6 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::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: float f = 0.3 ; json j = f ; std :: cout << j << '\\n' ; yields 0.30000001192092896 . All examples here can be reproduced by passing the original double value to std :: printf ( \"%.*g \\n \" , std :: numeric_limits < double >:: max_digits10 , double_value ); NaN handling \u00b6 NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded: RFC 8259 , Section 6 Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment. This library serializes NaN values as null . This corresponds to the behavior of JavaScript's JSON.stringify function. Example The following example shows how a NaN value is stored in a json value. int main () { double val = std :: numeric_limits < double >:: quiet_NaN (); std :: cout << \"val=\" << val << std :: endl ; json j = val ; std :: cout << \"j=\" << j . dump () << std :: endl ; val = j ; std :: cout << \"val=\" << val << std :: endl ; } output: val=nan j=null val=nan Number comparison \u00b6 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 > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-define an operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) { // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } } ... } (see #703 for more information.) Note NaN values never compare equal to themselves or to other NaN values. See #514 . Number conversion \u00b6 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 json jd = d ; // stores double value 42.3 std :: int64_t i = jd . template get < std :: int64_t > (); // now i==42; no warning or error is produced 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 #json-specification ). 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 if ( jd . is_number_integer ()) { // if so, do the conversion and use i std :: int64_t i = jd . template get < std :: int64_t > (); // ... } else { // otherwise, take appropriate action // ... } Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings. (Example taken from #777 .) Determine number types \u00b6 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() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string Template number types \u00b6 The number types can be changed with template parameters. position number type default type possible values 5 signed integers std :: int64_t std :: int32_t , std :: int16_t , etc. 6 unsigned integers std :: uint64_t std :: uint32_t , std :: uint16_t , etc. 7 floating-point double float , long double Constraints on number types 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 , std :: int64_t , std :: uint64_t , long double > ; 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 .","title":"Number Handling"},{"location":"features/types/number_handling/#number-handling","text":"This document describes how the library is handling numbers.","title":"Number Handling"},{"location":"features/types/number_handling/#background","text":"This section briefly summarizes how the JSON specification describes how numbers should be handled.","title":"Background"},{"location":"features/types/number_handling/#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:","title":"JSON number syntax"},{"location":"features/types/number_handling/#number-interoperability","text":"On number interoperability, the following remarks are made: RFC 8259 , Section 6 This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available. Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.","title":"Number interoperability"},{"location":"features/types/number_handling/#library-implementation","text":"This section describes how the above number specification is implemented by this library.","title":"Library implementation"},{"location":"features/types/number_handling/#number-storage","text":"In the default json type, numbers are stored as std :: uint64_t , std :: int64_t , and double , respectively. Thereby, std :: uint64_t and std :: int64_t are used only if they can store the number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as double . Notes 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 .","title":"Number storage"},{"location":"features/types/number_handling/#number-limits","text":"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] [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1] [-2^{53}+1, 2^{53}-1] . All integers outside the range [-2^{63}, 2^{64}-1] [-2^{63}, 2^{64}-1] , as well as floating-point numbers are stored as double . This also concurs with the specification above.","title":"Number limits"},{"location":"features/types/number_handling/#zeros","text":"The JSON number grammar allows for different ways to express zero, and this library will store zeros differently: Literal Stored value and type Serialization 0 std :: uint64_t ( 0 ) 0 -0 std :: int64_t ( 0 ) 0 0.0 double ( 0.0 ) 0.0 -0.0 double ( -0.0 ) -0.0 0E0 double ( 0.0 ) 0.0 -0E0 double ( -0.0 ) -0.0 That is, -0 is stored as a signed integer, but the serialization does not reproduce the - .","title":"Zeros"},{"location":"features/types/number_handling/#number-serialization","text":"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::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: float f = 0.3 ; json j = f ; std :: cout << j << '\\n' ; yields 0.30000001192092896 . All examples here can be reproduced by passing the original double value to std :: printf ( \"%.*g \\n \" , std :: numeric_limits < double >:: max_digits10 , double_value );","title":"Number serialization"},{"location":"features/types/number_handling/#nan-handling","text":"NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded: RFC 8259 , Section 6 Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment. This library serializes NaN values as null . This corresponds to the behavior of JavaScript's JSON.stringify function. Example The following example shows how a NaN value is stored in a json value. int main () { double val = std :: numeric_limits < double >:: quiet_NaN (); std :: cout << \"val=\" << val << std :: endl ; json j = val ; std :: cout << \"j=\" << j . dump () << std :: endl ; val = j ; std :: cout << \"val=\" << val << std :: endl ; } output: val=nan j=null val=nan","title":"NaN handling"},{"location":"features/types/number_handling/#number-comparison","text":"Floating-point inside JSON values numbers are compared with json :: number_float_t :: operator == which is double :: operator == by default. Alternative comparison functions To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance template < typename T , typename = typename std :: enable_if < std :: is_floating_point < T >:: value , T >:: type > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-define an operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) { // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } } ... } (see #703 for more information.) Note NaN values never compare equal to themselves or to other NaN values. See #514 .","title":"Number comparison"},{"location":"features/types/number_handling/#number-conversion","text":"Just like the C++ language itself, the get family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising. Unconditional number conversions double d = 42.3 ; // non-integer double value 42.3 json jd = d ; // stores double value 42.3 std :: int64_t i = jd . template get < std :: int64_t > (); // now i==42; no warning or error is produced 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 #json-specification ). 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 if ( jd . is_number_integer ()) { // if so, do the conversion and use i std :: int64_t i = jd . template get < std :: int64_t > (); // ... } else { // otherwise, take appropriate action // ... } Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings. (Example taken from #777 .)","title":"Number conversion"},{"location":"features/types/number_handling/#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() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string","title":"Determine number types"},{"location":"features/types/number_handling/#template-number-types","text":"The number types can be changed with template parameters. position number type default type possible values 5 signed integers std :: int64_t std :: int32_t , std :: int16_t , etc. 6 unsigned integers std :: uint64_t std :: uint32_t , std :: uint16_t , etc. 7 floating-point double float , long double Constraints on number types 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 , std :: int64_t , std :: uint64_t , long double > ; 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 .","title":"Template number types"},{"location":"home/code_of_conduct/","text":"Contributor Covenant Code of Conduct \u00b6 Our Pledge \u00b6 In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards \u00b6 Examples of behavior that contributes to creating a positive environment include: Using welcoming and inclusive language Being respectful of differing viewpoints and experiences Gracefully accepting constructive criticism Focusing on what is best for the community Showing empathy towards other community members Examples of unacceptable behavior by participants include: The use of sexualized language or imagery and unwelcome sexual attention or advances Trolling, insulting/derogatory comments, and personal or political attacks Public or private harassment Publishing others' private information, such as a physical or electronic address, without explicit permission Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities \u00b6 Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope \u00b6 This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement \u00b6 Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me . The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution \u00b6 This Code of Conduct is adapted from the Contributor Covenant , version 1.4, available at http://contributor-covenant.org/version/1/4","title":"Code of Conduct"},{"location":"home/code_of_conduct/#contributor-covenant-code-of-conduct","text":"","title":"Contributor Covenant Code of Conduct"},{"location":"home/code_of_conduct/#our-pledge","text":"In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.","title":"Our Pledge"},{"location":"home/code_of_conduct/#our-standards","text":"Examples of behavior that contributes to creating a positive environment include: Using welcoming and inclusive language Being respectful of differing viewpoints and experiences Gracefully accepting constructive criticism Focusing on what is best for the community Showing empathy towards other community members Examples of unacceptable behavior by participants include: The use of sexualized language or imagery and unwelcome sexual attention or advances Trolling, insulting/derogatory comments, and personal or political attacks Public or private harassment Publishing others' private information, such as a physical or electronic address, without explicit permission Other conduct which could reasonably be considered inappropriate in a professional setting","title":"Our Standards"},{"location":"home/code_of_conduct/#our-responsibilities","text":"Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.","title":"Our Responsibilities"},{"location":"home/code_of_conduct/#scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.","title":"Scope"},{"location":"home/code_of_conduct/#enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me . The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.","title":"Enforcement"},{"location":"home/code_of_conduct/#attribution","text":"This Code of Conduct is adapted from the Contributor Covenant , version 1.4, available at http://contributor-covenant.org/version/1/4","title":"Attribution"},{"location":"home/design_goals/","text":"Design goals \u00b6 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. Check out the examples below , and you'll know what I mean. 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.","title":"Design goals"},{"location":"home/design_goals/#design-goals","text":"There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals: Intuitive syntax . In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code. Check out the examples below , and you'll know what I mean. 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.","title":"Design goals"},{"location":"home/exceptions/","text":"Exceptions \u00b6 Overview \u00b6 Base type \u00b6 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. Switch off exceptions \u00b6 Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION . In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw ), JSON_TRY_USER (overriding try ), and JSON_CATCH_USER (overriding catch ). Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior. Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 . See documentation of JSON_TRY_USER , JSON_CATCH_USER and JSON_THROW_USER for more information. Extended diagnostic messages \u00b6 Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult. Example #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer . As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp . Example #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type. See documentation of JSON_DIAGNOSTICS for more information. Parse errors \u00b6 This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Exceptions have ids 1xx. Byte index Member byte holds the byte index of the last read character in the input file. For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal exception id: 101 byte position of error: 8 json.exception.parse_error.101 \u00b6 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 No input: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal 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: '\"'\" 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: '\"' 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' \\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\"' 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'\" 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' 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.exception.parse_error.102 \u00b6 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 Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used. json.exception.parse_error.103 \u00b6 Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. Example message parse error: code points above 0x10FFFF are invalid Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used. json.exception.parse_error.104 \u00b6 RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects. Example message [json.exception.parse_error.104] parse error: JSON patch must be an array of objects json.exception.parse_error.105 \u00b6 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' [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from' [json.exception.parse_error.105] parse error: operation value 'foo' is invalid json.exception.parse_error.106 \u00b6 An array index in a JSON Pointer ( RFC 6901 ) may be 0 or any number without a leading 0 . Example message [json.exception.parse_error.106] parse error: array index '01' must not begin with '0' json.exception.parse_error.107 \u00b6 A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character. Example message [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo' json.exception.parse_error.108 \u00b6 In a JSON Pointer, only ~0 and ~1 are valid escape sequences. Example message [json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1' json.exception.parse_error.109 \u00b6 A JSON Pointer array index must be a number. Example messages [json.exception.parse_error.109] parse error: array index 'one' is not a number [json.exception.parse_error.109] parse error: array index '+1' is not a number json.exception.parse_error.110 \u00b6 When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. Example message [json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A json.exception.parse_error.112 \u00b6 An unexpected byte was read in a binary format or length information is invalid ( BSON ). Example messages [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648 [json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1 json.exception.parse_error.113 \u00b6 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 [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 [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 json.exception.parse_error.114 \u00b6 The parsing of the corresponding BSON record type is not implemented (yet). Example message [json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF json.exception.parse_error.115 \u00b6 A UBJSON high-precision number could not be parsed. Example message [json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A Iterator errors \u00b6 This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. Example The following code shows how an invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators exception id: 207 json.exception.invalid_iterator.201 \u00b6 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 json.exception.invalid_iterator.202 \u00b6 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 [json.exception.invalid_iterator.202] iterators first and last must point to objects json.exception.invalid_iterator.203 \u00b6 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 json.exception.invalid_iterator.204 \u00b6 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 json.exception.invalid_iterator.205 \u00b6 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 json.exception.invalid_iterator.206 \u00b6 The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. Example message [json.exception.invalid_iterator.206] cannot construct with iterators from null json.exception.invalid_iterator.207 \u00b6 The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. Example message [json.exception.invalid_iterator.207] cannot use key() for non-object iterators json.exception.invalid_iterator.208 \u00b6 The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.208] cannot use operator[] for object iterators json.exception.invalid_iterator.209 \u00b6 The offset operators ( + , - , += , -= ) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.209] cannot use offsets with object iterators json.exception.invalid_iterator.210 \u00b6 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 json.exception.invalid_iterator.211 \u00b6 The iterator range passed to the insert function must not be a subrange of the container to insert to. Example message [json.exception.invalid_iterator.211] passed iterators may not belong to container json.exception.invalid_iterator.212 \u00b6 When two iterators are compared, they must belong to the same container. Example message [json.exception.invalid_iterator.212] cannot compare iterators of different containers json.exception.invalid_iterator.213 \u00b6 The order of object iterators cannot be compared, because JSON objects are unordered. Example message [json.exception.invalid_iterator.213] cannot compare order of object iterators json.exception.invalid_iterator.214 \u00b6 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 Type errors \u00b6 This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.type_error.308] cannot use push_back() with string exception id: 308 json.exception.type_error.301 \u00b6 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 json.exception.type_error.302 \u00b6 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 [json.exception.type_error.302] type must be string, but is object json.exception.type_error.303 \u00b6 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 [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\" json.exception.type_error.304 \u00b6 The at() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.304] cannot use at() with string [json.exception.type_error.304] cannot use at() with number json.exception.type_error.305 \u00b6 The operator[] member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.305] cannot use operator[] with a string argument with array [json.exception.type_error.305] cannot use operator[] with a numeric argument with object json.exception.type_error.306 \u00b6 The value() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.306] cannot use value() with number json.exception.type_error.307 \u00b6 The erase() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.307] cannot use erase() with string json.exception.type_error.308 \u00b6 The push_back() and operator+= member functions can only be executed for certain JSON types. Example message [json.exception.type_error.308] cannot use push_back() with string json.exception.type_error.309 \u00b6 The insert() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.309] cannot use insert() with array [json.exception.type_error.309] cannot use insert() with number json.exception.type_error.310 \u00b6 The swap() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.310] cannot use swap() with number json.exception.type_error.311 \u00b6 The emplace() and emplace_back() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.311] cannot use emplace() with number [json.exception.type_error.311] cannot use emplace_back() with number json.exception.type_error.312 \u00b6 The update() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.312] cannot use update() with array json.exception.type_error.313 \u00b6 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 json.exception.type_error.314 \u00b6 The unflatten function only works for an object whose keys are JSON Pointers. Example message Calling unflatten() on an array [ 1 , 2 , 3 ] : [json.exception.type_error.314] only objects can be unflattened json.exception.type_error.315 \u00b6 The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive. Example message Calling unflatten() on an object { \"/1\" , [ 1 , 2 , 3 ]} : [json.exception.type_error.315] values in object must be primitive json.exception.type_error.316 \u00b6 The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded. Example message Calling dump() on a JSON value containing an ISO 8859-1 encoded string: [json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F Tip Store the source file with UTF-8 encoding. Pass an error handler as last parameter to the dump() function to avoid this exception: json::error_handler_t::replace will replace invalid bytes sequences with U+FFFD json::error_handler_t::ignore will silently ignore invalid byte sequences json.exception.type_error.317 \u00b6 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 Serializing [ 1 , 2 , 3 ] to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array Tip Encapsulate the JSON value in an object. That is, instead of serializing true , serialize { \"value\" : true } Out of range \u00b6 This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. Example The following code shows how an out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.out_of_range.401] array index 4 is out of range exception id: 401 json.exception.out_of_range.401 \u00b6 The provided array index i is larger than size-1 . Example message array index 3 is out of range json.exception.out_of_range.402 \u00b6 The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. Example message array index '-' (3) is out of range json.exception.out_of_range.403 \u00b6 The provided key was not found in the JSON object. Example message key 'foo' not found json.exception.out_of_range.404 \u00b6 A reference token in a JSON Pointer could not be resolved. Example message unresolved reference token 'foo' json.exception.out_of_range.405 \u00b6 The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. Example message JSON pointer has no parent json.exception.out_of_range.406 \u00b6 A parsed number could not be stored as without changing it to NaN or INF. Example message number overflow parsing '10E1000' json.exception.out_of_range.407 \u00b6 UBJSON and BSON only support integer numbers up to 9223372036854775807. Example message number overflow serializing '9223372036854775808' Note Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur. json.exception.out_of_range.408 \u00b6 The size (following # ) of an UBJSON array or object exceeds the maximal capacity. Example message excessive array size: 8658170730974374167 json.exception.out_of_range.409 \u00b6 Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string. Example message BSON key cannot contain code point U+0000 (at byte 2) Further exceptions \u00b6 This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. Example The following code shows how an other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"} exception id: 501 json.exception.other_error.501 \u00b6 A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. Example message Executing { \"op\" : \"test\" , \"path\" : \"/baz\" , \"value\" : \"bar\" } on { \"baz\" : \"qux\" } : [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}","title":"Exceptions"},{"location":"home/exceptions/#exceptions","text":"","title":"Exceptions"},{"location":"home/exceptions/#overview","text":"","title":"Overview"},{"location":"home/exceptions/#base-type","text":"All exceptions inherit from class json::exception (which in turn inherits from std::exception ). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions.","title":"Base type"},{"location":"home/exceptions/#switch-off-exceptions","text":"Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION . In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw ), JSON_TRY_USER (overriding try ), and JSON_CATCH_USER (overriding catch ). Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior. Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 . See documentation of JSON_TRY_USER , JSON_CATCH_USER and JSON_THROW_USER for more information.","title":"Switch off exceptions"},{"location":"home/exceptions/#extended-diagnostic-messages","text":"Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult. Example #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer . As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp . Example #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type. See documentation of JSON_DIAGNOSTICS for more information.","title":"Extended diagnostic messages"},{"location":"home/exceptions/#parse-errors","text":"This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Exceptions have ids 1xx. Byte index Member byte holds the byte index of the last read character in the input file. For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal exception id: 101 byte position of error: 8","title":"Parse errors"},{"location":"home/exceptions/#jsonexceptionparse_error101","text":"This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte indicates the error position. Example message Input ended prematurely: [json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal No input: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal 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: '\"'\" 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: '\"' 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' \\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\"' 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'\" 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' 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 .","title":"json.exception.parse_error.101"},{"location":"home/exceptions/#jsonexceptionparse_error102","text":"JSON uses the \\uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \\uxxxx entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. Example message parse error at 14: missing or wrong low surrogate Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.","title":"json.exception.parse_error.102"},{"location":"home/exceptions/#jsonexceptionparse_error103","text":"Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. Example message parse error: code points above 0x10FFFF are invalid Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.","title":"json.exception.parse_error.103"},{"location":"home/exceptions/#jsonexceptionparse_error104","text":"RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects. Example message [json.exception.parse_error.104] parse error: JSON patch must be an array of objects","title":"json.exception.parse_error.104"},{"location":"home/exceptions/#jsonexceptionparse_error105","text":"An operation of a JSON Patch document must contain exactly one \"op\" member, whose value indicates the operation to perform. Its value must be one of \"add\", \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are errors. Example message [json.exception.parse_error.105] parse error: operation 'add' must have member 'value' [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from' [json.exception.parse_error.105] parse error: operation value 'foo' is invalid","title":"json.exception.parse_error.105"},{"location":"home/exceptions/#jsonexceptionparse_error106","text":"An array index in a JSON Pointer ( RFC 6901 ) may be 0 or any number without a leading 0 . Example message [json.exception.parse_error.106] parse error: array index '01' must not begin with '0'","title":"json.exception.parse_error.106"},{"location":"home/exceptions/#jsonexceptionparse_error107","text":"A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character. Example message [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'","title":"json.exception.parse_error.107"},{"location":"home/exceptions/#jsonexceptionparse_error108","text":"In a JSON Pointer, only ~0 and ~1 are valid escape sequences. Example message [json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'","title":"json.exception.parse_error.108"},{"location":"home/exceptions/#jsonexceptionparse_error109","text":"A JSON Pointer array index must be a number. Example messages [json.exception.parse_error.109] parse error: array index 'one' is not a number [json.exception.parse_error.109] parse error: array index '+1' is not a number","title":"json.exception.parse_error.109"},{"location":"home/exceptions/#jsonexceptionparse_error110","text":"When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. Example message [json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A","title":"json.exception.parse_error.110"},{"location":"home/exceptions/#jsonexceptionparse_error112","text":"An unexpected byte was read in a binary format or length information is invalid ( BSON ). Example messages [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648 [json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1","title":"json.exception.parse_error.112"},{"location":"home/exceptions/#jsonexceptionparse_error113","text":"While parsing a map key, a value that is not a string has been read. Example messages [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF [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 [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","title":"json.exception.parse_error.113"},{"location":"home/exceptions/#jsonexceptionparse_error114","text":"The parsing of the corresponding BSON record type is not implemented (yet). Example message [json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF","title":"json.exception.parse_error.114"},{"location":"home/exceptions/#jsonexceptionparse_error115","text":"A UBJSON high-precision number could not be parsed. Example message [json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A","title":"json.exception.parse_error.115"},{"location":"home/exceptions/#iterator-errors","text":"This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. Example The following code shows how an invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators exception id: 207","title":"Iterator errors"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range ( first , last ) is invalid. Example message [json.exception.invalid_iterator.201] iterators are not compatible","title":"json.exception.invalid_iterator.201"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","text":"In the erase or insert function, the passed iterator pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. Example messages [json.exception.invalid_iterator.202] iterator does not fit current value [json.exception.invalid_iterator.202] iterators first and last must point to objects","title":"json.exception.invalid_iterator.202"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","text":"Either iterator passed to function erase(IteratorType first, IteratorType last ) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. Example message [json.exception.invalid_iterator.203] iterators do not fit current value","title":"json.exception.invalid_iterator.203"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","text":"When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly ( begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid. Example message [json.exception.invalid_iterator.204] iterators out of range","title":"json.exception.invalid_iterator.204"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","text":"When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. Example message [json.exception.invalid_iterator.205] iterator out of range","title":"json.exception.invalid_iterator.205"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. Example message [json.exception.invalid_iterator.206] cannot construct with iterators from null","title":"json.exception.invalid_iterator.206"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","text":"The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. Example message [json.exception.invalid_iterator.207] cannot use key() for non-object iterators","title":"json.exception.invalid_iterator.207"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","text":"The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.208] cannot use operator[] for object iterators","title":"json.exception.invalid_iterator.208"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","text":"The offset operators ( + , - , += , -= ) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.209] cannot use offsets with object iterators","title":"json.exception.invalid_iterator.209"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","text":"The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range ( first , last ) is invalid. Example message [json.exception.invalid_iterator.210] iterators do not fit","title":"json.exception.invalid_iterator.210"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","text":"The iterator range passed to the insert function must not be a subrange of the container to insert to. Example message [json.exception.invalid_iterator.211] passed iterators may not belong to container","title":"json.exception.invalid_iterator.211"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","text":"When two iterators are compared, they must belong to the same container. Example message [json.exception.invalid_iterator.212] cannot compare iterators of different containers","title":"json.exception.invalid_iterator.212"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","text":"The order of object iterators cannot be compared, because JSON objects are unordered. Example message [json.exception.invalid_iterator.213] cannot compare order of object iterators","title":"json.exception.invalid_iterator.213"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","text":"Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin() . Example message [json.exception.invalid_iterator.214] cannot get value","title":"json.exception.invalid_iterator.214"},{"location":"home/exceptions/#type-errors","text":"This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.type_error.308] cannot use push_back() with string exception id: 308","title":"Type errors"},{"location":"home/exceptions/#jsonexceptiontype_error301","text":"To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. Example message [json.exception.type_error.301] cannot create object from initializer list","title":"json.exception.type_error.301"},{"location":"home/exceptions/#jsonexceptiontype_error302","text":"During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. Example messages [json.exception.type_error.302] type must be object, but is null [json.exception.type_error.302] type must be string, but is object","title":"json.exception.type_error.302"},{"location":"home/exceptions/#jsonexceptiontype_error303","text":"To retrieve a reference to a value stored in a basic_json object with get_ref , the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t & . Example messages [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"","title":"json.exception.type_error.303"},{"location":"home/exceptions/#jsonexceptiontype_error304","text":"The at() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.304] cannot use at() with string [json.exception.type_error.304] cannot use at() with number","title":"json.exception.type_error.304"},{"location":"home/exceptions/#jsonexceptiontype_error305","text":"The operator[] member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.305] cannot use operator[] with a string argument with array [json.exception.type_error.305] cannot use operator[] with a numeric argument with object","title":"json.exception.type_error.305"},{"location":"home/exceptions/#jsonexceptiontype_error306","text":"The value() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.306] cannot use value() with number","title":"json.exception.type_error.306"},{"location":"home/exceptions/#jsonexceptiontype_error307","text":"The erase() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.307] cannot use erase() with string","title":"json.exception.type_error.307"},{"location":"home/exceptions/#jsonexceptiontype_error308","text":"The push_back() and operator+= member functions can only be executed for certain JSON types. Example message [json.exception.type_error.308] cannot use push_back() with string","title":"json.exception.type_error.308"},{"location":"home/exceptions/#jsonexceptiontype_error309","text":"The insert() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.309] cannot use insert() with array [json.exception.type_error.309] cannot use insert() with number","title":"json.exception.type_error.309"},{"location":"home/exceptions/#jsonexceptiontype_error310","text":"The swap() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.310] cannot use swap() with number","title":"json.exception.type_error.310"},{"location":"home/exceptions/#jsonexceptiontype_error311","text":"The emplace() and emplace_back() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.311] cannot use emplace() with number [json.exception.type_error.311] cannot use emplace_back() with number","title":"json.exception.type_error.311"},{"location":"home/exceptions/#jsonexceptiontype_error312","text":"The update() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.312] cannot use update() with array","title":"json.exception.type_error.312"},{"location":"home/exceptions/#jsonexceptiontype_error313","text":"The unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined. Example message [json.exception.type_error.313] invalid value to unflatten","title":"json.exception.type_error.313"},{"location":"home/exceptions/#jsonexceptiontype_error314","text":"The unflatten function only works for an object whose keys are JSON Pointers. Example message Calling unflatten() on an array [ 1 , 2 , 3 ] : [json.exception.type_error.314] only objects can be unflattened","title":"json.exception.type_error.314"},{"location":"home/exceptions/#jsonexceptiontype_error315","text":"The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive. Example message Calling unflatten() on an object { \"/1\" , [ 1 , 2 , 3 ]} : [json.exception.type_error.315] values in object must be primitive","title":"json.exception.type_error.315"},{"location":"home/exceptions/#jsonexceptiontype_error316","text":"The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded. Example message Calling dump() on a JSON value containing an ISO 8859-1 encoded string: [json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F Tip Store the source file with UTF-8 encoding. Pass an error handler as last parameter to the dump() function to avoid this exception: json::error_handler_t::replace will replace invalid bytes sequences with U+FFFD json::error_handler_t::ignore will silently ignore invalid byte sequences","title":"json.exception.type_error.316"},{"location":"home/exceptions/#jsonexceptiontype_error317","text":"The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON) Example messages Serializing null to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null Serializing [ 1 , 2 , 3 ] to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array Tip Encapsulate the JSON value in an object. That is, instead of serializing true , serialize { \"value\" : true }","title":"json.exception.type_error.317"},{"location":"home/exceptions/#out-of-range","text":"This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. Example The following code shows how an out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.out_of_range.401] array index 4 is out of range exception id: 401","title":"Out of range"},{"location":"home/exceptions/#jsonexceptionout_of_range401","text":"The provided array index i is larger than size-1 . Example message array index 3 is out of range","title":"json.exception.out_of_range.401"},{"location":"home/exceptions/#jsonexceptionout_of_range402","text":"The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. Example message array index '-' (3) is out of range","title":"json.exception.out_of_range.402"},{"location":"home/exceptions/#jsonexceptionout_of_range403","text":"The provided key was not found in the JSON object. Example message key 'foo' not found","title":"json.exception.out_of_range.403"},{"location":"home/exceptions/#jsonexceptionout_of_range404","text":"A reference token in a JSON Pointer could not be resolved. Example message unresolved reference token 'foo'","title":"json.exception.out_of_range.404"},{"location":"home/exceptions/#jsonexceptionout_of_range405","text":"The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. Example message JSON pointer has no parent","title":"json.exception.out_of_range.405"},{"location":"home/exceptions/#jsonexceptionout_of_range406","text":"A parsed number could not be stored as without changing it to NaN or INF. Example message number overflow parsing '10E1000'","title":"json.exception.out_of_range.406"},{"location":"home/exceptions/#jsonexceptionout_of_range407","text":"UBJSON and BSON only support integer numbers up to 9223372036854775807. Example message number overflow serializing '9223372036854775808' Note Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.","title":"json.exception.out_of_range.407"},{"location":"home/exceptions/#jsonexceptionout_of_range408","text":"The size (following # ) of an UBJSON array or object exceeds the maximal capacity. Example message excessive array size: 8658170730974374167","title":"json.exception.out_of_range.408"},{"location":"home/exceptions/#jsonexceptionout_of_range409","text":"Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string. Example message BSON key cannot contain code point U+0000 (at byte 2)","title":"json.exception.out_of_range.409"},{"location":"home/exceptions/#further-exceptions","text":"This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. Example The following code shows how an other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"} exception id: 501","title":"Further exceptions"},{"location":"home/exceptions/#jsonexceptionother_error501","text":"A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. Example message Executing { \"op\" : \"test\" , \"path\" : \"/baz\" , \"value\" : \"bar\" } on { \"baz\" : \"qux\" } : [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}","title":"json.exception.other_error.501"},{"location":"home/faq/","text":"Frequently Asked Questions (FAQ) \u00b6 Known bugs \u00b6 Brace initialization yields arrays \u00b6 Question Why does json j { true }; and json j ( true ); yield different results ( [ true ] vs. true )? This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like json array = { 1 , 2 , 3 , 4 }; for arrays and json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; 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. Limitations \u00b6 Relaxed parsing \u00b6 Question Can you add an option to ignore trailing commas? This library does not support any feature which would jeopardize interoperability. Parse errors reading non-ASCII characters \u00b6 Questions 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. Wide string handling \u00b6 Question Why are wide strings (e.g., std::wstring ) dumped as arrays of numbers? As described above , the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding. Example #include // codecvt_utf8 #include // wstring_convert // encoding function std :: string to_utf8 ( std :: wstring & wide_string ) { static std :: wstring_convert < std :: codecvt_utf8 < wchar_t >> utf8_conv ; return utf8_conv . to_bytes ( wide_string ); } json j ; std :: wstring ws = L \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" ; j [ \"original\" ] = ws ; j [ \"encoded\" ] = to_utf8 ( ws ); std :: cout << j << std :: endl ; The result is: { \"encoded\" : \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" , \"original\" : [ 36554 , 66 , 49 , 50 , 51 , 52 , 32 , 12371 , 12435 , 12395 , 12385 , 12399 ] } Exceptions \u00b6 Parsing without exceptions \u00b6 Question Is it possible to indicate a parse error without throwing an exception? Yes, see Parsing and exceptions . Key name in exceptions \u00b6 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 . Serialization issues \u00b6 Number precision \u00b6 Question 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::digits10 (15 for IEEE double s) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip. cppreference.com The value of std::numeric_limits::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. Compilation issues \u00b6 Android SDK \u00b6 Question Why does the code not compile with Android SDK? Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk . This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default. APP_STL : = c++_shared NDK_TOOLCHAIN_VERSION : = clang3.6 APP_CPPFLAGS + = -frtti -fexceptions The code compiles successfully with Android NDK , Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10. Missing STL function \u00b6 Questions 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 .","title":"FAQ"},{"location":"home/faq/#frequently-asked-questions-faq","text":"","title":"Frequently Asked Questions (FAQ)"},{"location":"home/faq/#known-bugs","text":"","title":"Known bugs"},{"location":"home/faq/#brace-initialization-yields-arrays","text":"Question Why does json j { true }; and json j ( true ); yield different results ( [ true ] vs. true )? This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like json array = { 1 , 2 , 3 , 4 }; for arrays and json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; 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.","title":"Brace initialization yields arrays"},{"location":"home/faq/#limitations","text":"","title":"Limitations"},{"location":"home/faq/#relaxed-parsing","text":"Question Can you add an option to ignore trailing commas? This library does not support any feature which would jeopardize interoperability.","title":"Relaxed parsing"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","text":"Questions 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.","title":"Parse errors reading non-ASCII characters"},{"location":"home/faq/#wide-string-handling","text":"Question Why are wide strings (e.g., std::wstring ) dumped as arrays of numbers? As described above , the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding. Example #include // codecvt_utf8 #include // wstring_convert // encoding function std :: string to_utf8 ( std :: wstring & wide_string ) { static std :: wstring_convert < std :: codecvt_utf8 < wchar_t >> utf8_conv ; return utf8_conv . to_bytes ( wide_string ); } json j ; std :: wstring ws = L \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" ; j [ \"original\" ] = ws ; j [ \"encoded\" ] = to_utf8 ( ws ); std :: cout << j << std :: endl ; The result is: { \"encoded\" : \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" , \"original\" : [ 36554 , 66 , 49 , 50 , 51 , 52 , 32 , 12371 , 12435 , 12395 , 12385 , 12399 ] }","title":"Wide string handling"},{"location":"home/faq/#exceptions","text":"","title":"Exceptions"},{"location":"home/faq/#parsing-without-exceptions","text":"Question Is it possible to indicate a parse error without throwing an exception? Yes, see Parsing and exceptions .","title":"Parsing without exceptions"},{"location":"home/faq/#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 .","title":"Key name in exceptions"},{"location":"home/faq/#serialization-issues","text":"","title":"Serialization issues"},{"location":"home/faq/#number-precision","text":"Question 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::digits10 (15 for IEEE double s) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip. cppreference.com The value of std::numeric_limits::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.","title":"Number precision"},{"location":"home/faq/#compilation-issues","text":"","title":"Compilation issues"},{"location":"home/faq/#android-sdk","text":"Question Why does the code not compile with Android SDK? Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk . This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default. APP_STL : = c++_shared NDK_TOOLCHAIN_VERSION : = clang3.6 APP_CPPFLAGS + = -frtti -fexceptions The code compiles successfully with Android NDK , Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.","title":"Android SDK"},{"location":"home/faq/#missing-stl-function","text":"Questions 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 .","title":"Missing STL function"},{"location":"home/license/","text":"License \u00b6 The class is licensed under the MIT License : Copyright \u00a9 2013-2022 Niels Lohmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0 .","title":"License"},{"location":"home/license/#license","text":"The class is licensed under the MIT License : Copyright \u00a9 2013-2022 Niels Lohmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0 .","title":"License"},{"location":"home/releases/","text":"Releases \u00b6 v3.7.3 \u00b6 Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip) Summary \u00b6 This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible. Bug Fixes \u00b6 Removed reserve() calls from the destructor which could lead to quadratic complexity. #1837 #1838 Deprecated functions \u00b6 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. v3.7.2 \u00b6 Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip) Summary \u00b6 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. Bug Fixes \u00b6 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 Further Changes \u00b6 Added WhiteStone Bolt. #1830 Deprecated functions \u00b6 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. v3.7.1 \u00b6 Files include.zip (273 KB) include.zip.asc (1 KB) json.hpp (789 KB) json.hpp.asc (1 KB) Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip) Summary \u00b6 This release fixes several small bugs in the library. All changes are backward-compatible. Bug Fixes \u00b6 Fixed a segmentation fault when serializing std::int64_t minimum value. #1708 #1722 Fixed the contains() function for JSON Pointers. #1727 #1741 Fixed too lax SFINAE guard for conversion from std::pair and std::tuple to json . #1805 #1806 #1825 #1826 Fixed some regressions detected by UBSAN. Updated CI to use Clang-Tidy 7.1.0. #1716 #1728 Fixed integer truncation in iteration_proxy . #1797 Updated Hedley to v11 to fix a E2512 error in MSVC. #1799 Fixed a compile error in enum deserialization of non non-default-constructible types. #1647 #1821 Fixed the conversion from json to std::valarray . Improvements \u00b6 The items() function can now be used with a custom string type. #1765 Made json_pointer::back const . #1764 #1769 Meson is part of the release archive. #1672 #1694 Improved documentation on the Meson and Spack package manager. #1694 #1720 Further Changes \u00b6 Added GitHub Workflow with ubuntu-latest /GCC 7.4.0 as CI step. Added GCC 9 to Travis CI to compile with C++20 support. #1724 Added MSVC 2019 to the AppVeyor CI. #1780 Added badge to fuzzing status . Fixed some cppcheck warnings. #1760 Fixed several typos in the documentation. #1720 #1767 #1803 Added documentation on the JSON_THROW_USER , JSON_TRY_USER , and JSON_CATCH_USER macros to control user-defined exception handling. Used GitHub's CODEOWNERS and SECURITY feature. Removed GLOB from CMake files. #1779 Updated to Doctest 2.3.5. Deprecated functions \u00b6 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. v3.7.0 \u00b6 Files include.zip (143 KB) include.zip.asc (1 KB) json.hpp (782 KB) json.hpp.asc (1 KB) Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip) Summary \u00b6 This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible. New Features \u00b6 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 Bug Fixes \u00b6 Fix an issue where typedefs with certain names yielded a compilation error. #1642 #1643 Fix a conversion to std::string_view in the unit tests. #1634 #1639 Fix MSVC Debug build. #1536 #1570 #1608 Fix get_to method to clear existing content before writing. #1511 #1555 Fix a -Wc++17-extensions warning. nodiscard attributes are now only used with Clang when -std=c++17 is used. #1535 #1551 Improvements \u00b6 Switch from Catch to doctest for the unit tests which speeds up compilation and runtime of the 112,112,308 tests. Add an explicit section to the README about the frequently addressed topics character encoding , comments in JSON , and the order of object keys . Further Changes \u00b6 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. Deprecated functions \u00b6 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. v3.6.1 \u00b6 Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip) Summary \u00b6 This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible. Bug Fixes \u00b6 Fixed regression of #590 which could lead to compilation errors with GCC 7 and GCC 8. #1530 Fixed a compilation error when was included. #1531 Further Changes \u00b6 Fixed a warning for missing field initializers. #1527 Deprecated functions \u00b6 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. v3.6.0 \u00b6 Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip) \u2139\ufe0f This release introduced a regression. Please update to version 3.6.1 ! Summary \u00b6 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. New Features \u00b6 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 Bug Fixes \u00b6 Fixed a compilation issues with libc 2.12. #1483 #1514 Fixed endian conversion on PPC64. #1489 Fixed library to compile with GCC 9. #1472 #1492 Fixed a compilation issue with GCC 7 on CentOS. #1496 Fixed an integer overflow. #1447 Fixed buffer flushing in serializer. #1445 #1446 Improvements \u00b6 The performance of dumping integers has been greatly improved. #1411 Added CMake parameter JSON_Install to control whether the library should be installed (default: on). #1330 Fixed a lot of compiler and linter warnings. #1400 #1435 #1502 Reduced required CMake version from 3.8 to 3.1. #1409 #1428 #1441 #1498 Added nodiscard attribute to meta() , array() , object() , from_cbor , from_msgpack , from_ubjson , from_bson , and parse . #1433 Further Changes \u00b6 Added missing headers. #1500 Fixed typos and broken links in README. #1417 #1423 #1425 #1451 #1455 #1491 Fixed documentation of parse function. #1473 Suppressed warning that cannot be fixed inside the library. #1401 #1468 Imroved package manager suppert: Updated Buckaroo instructions. #1495 Improved Meson support. #1463 Added Conda package manager documentation. #1430 Added NuGet package manager documentation. #1132 Continuous Integration Removed unstable or deprecated Travis builders (Xcode 6.4 - 8.2) and added Xcode 10.1 builder. Added Clang 7 to Travis CI. Fixed AppVeyor x64 builds. #1374 #1414 Updated thirdparty libraries: Catch 1.12.0 -> 1.12.2 Google Benchmark 1.3.0 -> 1.4.1 Doxygen 1.8.15 -> 1.8.16 Deprecated functions \u00b6 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. v3.5.0 \u00b6 Files include.zip (133 KB) include.zip.asc (1 KB) json.hpp (693 KB) json.hpp.asc (1 KB) Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip) Summary \u00b6 This release introduces the support for structured bindings and reading from FILE* . Besides, a few bugs have been fixed. All changes are backward-compatible. New Features \u00b6 Structured bindings are now supported for JSON objects and arrays via the items() member function, so finally this code is possible: for ( auto & [ key , val ] : j . items ()) { std :: cout << key << ':' << val << '\\n' ; } #1388 #1391 Added support for reading from FILE* to support situations in which streams are nit available or would require too much RAM. #1370 #1392 Bug Fixes \u00b6 The eofbit was not set for input streams when the end of a stream was reached while parsing. #1340 #1343 Fixed a bug in the SAX parser for BSON arrays. Improvements \u00b6 Added support for Clang 5.0.1 (PS4 version). #1341 #1342 Further Changes \u00b6 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 Added code to allow installation via Meson. #1345 Deprecated functions \u00b6 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. v3.4.0 \u00b6 Files include.zip (132 KB) include.zip.asc (1 KB) json.hpp (689 KB) json.hpp.asc (1 KB) Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip) Summary \u00b6 This release introduces three new features: 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. New Features \u00b6 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 Bug Fixes \u00b6 fixed truncation #1286 #1315 fixed an issue with std::pair #1299 #1301 fixed an issue with std::variant #1292 #1294 fixed a bug in the JSON Pointer parser Improvements \u00b6 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: '' 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: '' . #1280 #1288 #1303 Further Changes \u00b6 improved Meson documentation #1305 fixed some more linter warnings #1280 fixed Clang detection for third-party Google Benchmark library #1277 Deprecated functions \u00b6 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. v3.3.0 \u00b6 Files include.zip (123 KB) include.zip.asc (1 KB) json.hpp (635 KB) json.hpp.asc (1 KB) Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip) Summary \u00b6 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. New Features \u00b6 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 Bug Fixes \u00b6 Fixed a bug in the CMake file that made target_link_libraries to not properly include nlohmann_json . #1243 #1245 #1260 Fixed a warning in MSVC 2017 complaining about a constexpr if. #1204 #1268 #1272 Fixed a bug that prevented compilation with ICPC. #755 #1222 Improved the SFINAE correctness to fix a bug in the conversion operator. #1237 #1238 Fixed a -Wctor-dtor-privacy warning. #1224 Fixed a warning on a lambda in unevaluated context. #1225 #1230 Fixed a bug introduced in version 3.2.0 where defining JSON_CATCH_USER led to duplicate macro definition of JSON_INTERNAL_CATCH . #1213 #1214 Fixed a bug that prevented compilation with Clang 3.4.2 in RHEL 7. #1179 #1249 Improvements \u00b6 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 Further Changes \u00b6 GCC 4.8 and Xcode 10 were added to the continuous integration suite at Travis. Added lgtm checks to pull requests. Added tests for CMake integration. #1260 Deprecated functions \u00b6 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. v3.2.0 \u00b6 Files include.zip (124 KB) include.zip.asc (1 KB) json.hpp (636 KB) json.hpp.asc (1 KB) Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip) Summary \u00b6 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 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. New Features \u00b6 added a parser with a SAX interface (#971, #1153) 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) Bug Fixes \u00b6 allow to create nullptr_t from JSON allowing to properly roundtrip null values (#1169) allow compare user-defined string types (#1130) better support for algorithms using iterators from items() (#1045, #1134) added parameter to avoid compilation error with MSVC 2015 debug builds (#1114) re-added accidentally skipped unit tests (#1176) fixed MSVC issue with std::swap (#1168) Improvements \u00b6 key() function for iterators returns a const reference rather than a string copy (#1098) binary formats CBOR, MessagePack, and UBJSON now supports float as type for floating-point numbers (#1021) Further Changes \u00b6 changed issue templates 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 updated to Catch 1.12.0 Deprecated functions \u00b6 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. v3.1.2 \u00b6 Files include.zip (115 KB) include.zip.asc (1 KB) json.hpp (582 KB) json.hpp.asc (1 KB) Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip) Summary \u00b6 This release fixes several bugs in the library. All changes are backward-compatible. Bug Fixes \u00b6 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). Improvements \u00b6 The parser and the serialization now support user-defined string types (#1006, #1009). Further Changes \u00b6 Clang Analyzer is now used as additional static analyzer; see make clang_analyze . Overworked README by adding links to the documentation (#981). Deprecated functions \u00b6 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. v3.1.1 \u00b6 Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip) Summary \u00b6 This release fixes several bugs in the library. All changes are backward-compatible. Bug Fixes \u00b6 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() . Further Changes \u00b6 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 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). Deprecated functions \u00b6 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. v3.1.0 \u00b6 Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip) Summary \u00b6 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. New features \u00b6 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. Improvements \u00b6 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. Reorganization \u00b6 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). Further changes \u00b6 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. Deprecated functions \u00b6 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): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead. v3.0.1 \u00b6 Files json.hpp (502 KB) json.hpp.asc (1 KB) Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c Summary \u00b6 This release fixes small issues in the implementation of JSON Pointer and JSON Patch . All changes are backward-compatible. Changes \u00b6 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) Fixed some compiler warnings (see #858, #882). Deprecated functions \u00b6 To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead. v3.0.0 \u00b6 Files json.hpp (501 KB) json.hpp.asc (1 KB) Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462 Summary \u00b6 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. Breaking changes \u00b6 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 (#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 , , and 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). Deprecated functions \u00b6 To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead. New features \u00b6 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 (#494). Fixed support for std::valarray (#702), std::array (#553), and std::map (#600, #607). Further changes \u00b6 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. Moving from 2.x.x to 3.0.0 \u00b6 User-defined Exceptions \u00b6 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: new exception previous exception parse_error.101 invalid_argument parse_error.102 invalid_argument parse_error.103 invalid_argument parse_error.104 invalid_argument parse_error.105 invalid_argument parse_error.106 domain_error parse_error.107 domain_error parse_error.108 domain_error parse_error.109 invalid_argument parse_error.110 out_of_range parse_error.111 invalid_argument parse_error.112 invalid_argument invalid_iterator.201 domain_error invalid_iterator.202 domain_error invalid_iterator.203 domain_error invalid_iterator.204 out_of_range invalid_iterator.205 out_of_range invalid_iterator.206 domain_error invalid_iterator.207 domain_error invalid_iterator.208 domain_error invalid_iterator.209 domain_error invalid_iterator.210 domain_error invalid_iterator.211 domain_error invalid_iterator.212 domain_error invalid_iterator.213 domain_error invalid_iterator.214 out_of_range type_error.301 domain_error type_error.302 domain_error type_error.303 domain_error type_error.304 domain_error type_error.305 domain_error type_error.306 domain_error type_error.307 domain_error type_error.308 domain_error type_error.309 domain_error type_error.310 domain_error type_error.311 domain_error type_error.313 domain_error type_error.314 domain_error type_error.315 domain_error out_of_range.401 out_of_range out_of_range.402 out_of_range out_of_range.403 out_of_range out_of_range.404 out_of_range out_of_range.405 domain_error other_error.501 domain_error Handling of NaN and INF \u00b6 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 . Removal of deprecated functions \u00b6 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 ); New code: json j = json :: parse ( ss , cb ); If no callback function is used, also the following code works: json j ; j << ss ; or json j ; ss >> j ; v2.1.1 \u00b6 Files json.hpp (437 KB) json.hpp.asc (1 KB) Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57 Summary \u00b6 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. Changes \u00b6 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 . Removed Doozer. Added Codacity. Upgraded Catch to version 1.7.2. v2.1.0 \u00b6 Files json.hpp (426 KB) json.hpp.asc (1 KB) Release date: 2017-01-28 SHA-256: a571dee92515b685784fd527e38405cf3f5e13e96edbfe3f03d6df2e363a767b Summary \u00b6 This release introduces a means to convert from/to user-defined types. The release is backwards compatible. Changes \u00b6 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. Updated to Catch v1.6.0 . Some typos in the documentation have been fixed. v2.0.10 \u00b6 Files json.hpp (409 KB) json.hpp.asc (1 KB) Release date: 2017-01-02 SHA-256: ec27d4e74e9ce0f78066389a70724afd07f10761009322dc020656704ad5296d Summary \u00b6 This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible. Changes \u00b6 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. v2.0.9 \u00b6 Files json.hpp (406 KB) json.hpp.asc (1 KB) Release date: 2016-12-16 SHA-256: fbf3396f13e187d6c214c297bddc742d918ea9b55e10bfb3d9f458b9bfdc22e5 Summary \u00b6 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. Changes \u00b6 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 test suite now contains 11201886 tests v2.0.8 \u00b6 Files json.hpp (360 KB) json.hpp.asc (1 KB) Release date: 2016-12-02 SHA-256: b70db0ad34f8e0e61dc3f0cbab88099336c9674c193d8a3439d93d6aca2d7120 Summary \u00b6 This release combines a lot of small fixes and improvements. The fixes are backwards compatible. Changes \u00b6 fixed a bug that froze the parser if a passed file was not found (now, std::invalid_argument is thrown) fixed a bug that lead to an error of a file at EOF was parsed again (now, std::invalid_argument is thrown) the well known functions emplace and emplace_back have been added to JSON values and work as expected improved the performance of the serialization ( dump function) improved the performance of the deserialization (parser) some continuous integration images at Travis were added and retired; see here for the current continuous integration setup the Coverity scan works again the benchmarking code has been improved to produce more stable results the README file has been extended and includes more frequently asked examples the test suite now contains 8905518 tests updated Catch to version 1.5.8 v2.0.7 \u00b6 Files json.hpp (355 KB) json.hpp.asc (1 KB) Release date: 2016-11-02 SHA-256: 5545c323670f8165bae90b9dc6078825e86ec310d96cc4e5b47233ea43715bbf Summary \u00b6 This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible. Changes \u00b6 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. v2.0.6 \u00b6 Files json.hpp (349 KB) json.hpp.asc (1 KB) Release date: 2016-10-15 SHA256: 459cc93d5e2f503e50c6d5876eb86bfea7daf405f5a567c5a2c9abc2383756ae Summary \u00b6 This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible. Changes \u00b6 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 restored test coverage to 100%. v2.0.5 \u00b6 Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-14 SHA-256: 8b7565263a44e2b7d3b89808bc73d2d639037ff0c1f379e3d56dbd77e00b98d9 Summary \u00b6 This release fixes a regression bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible. Changes \u00b6 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. v2.0.4 \u00b6 Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-11 SHA-256: 632ceec4c25c4e2153f71470d3a2b992c8355f6d8b4d627d05dd16095cd3aeda Summary \u00b6 This release fixes a bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible. Changes \u00b6 Bug fix : The end of a file stream was not detected properly which led to parse errors. Fixed a compiler warning about an unused variable. v2.0.3 \u00b6 Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-08-31 SHA-256: 535b73efe5546fde9e763c14aeadfc7b58183c0b3cd43c29741025aba6cf6bd3 Summary \u00b6 This release combines a lot of small fixes and improvements. The release is backwards compatible. Changes \u00b6 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. v2.0.2 \u00b6 Files json.hpp (338 KB) json.hpp.asc (1 KB) Release date: 2016-07-31 SHA-256: 8e97b7965b4594b00998d6704465412360e1a0ed927badb51ded8b82291a8f3d Summary \u00b6 This release combines a lot of small fixes and improvements. The release is backwards compatible. Changes \u00b6 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. Avoided output to std::cout in the test cases. v2.0.1 \u00b6 Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-28 SHA-256: ef550fcd7df572555bf068e9ec4e9d3b9e4cdd441cecb0dcea9ea7fd313f72dd Summary \u00b6 This release fixes a performance regression in the JSON serialization (function dump() ). This fix is backwards compatible. Changes \u00b6 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. v2.0.0 \u00b6 Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-24 SHA-256: ac9e1fb25c2ac9ca5fc501fcd2fe3281fe04f07018a1b48820e7b1b11491bb6c Summary \u00b6 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. Changes \u00b6 \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 ). Added noexcept specifier to basic_json(boolean_t) , basic_json(const number_integer_t) , basic_json(const int) , basic_json(const number_float_t) , iterator functions ( begin() , end() , etc.) When parsing numbers, the sign of 0.0 (vs. -0.0 ) is preserved. Improved MSVC 2015, Android, and MinGW support. See README for more information. Improved test coverage (added 2,225,386 tests). Removed some misuses of std::move . Fixed several compiler warnings. Improved error messages from JSON parser. Updated to re2c to version 0.16 to use a minimal DFAs for the lexer. Updated test suite to use Catch version 1.5.6. Made type getters ( is_number , etc.) and const value access constexpr . Functions push_back and operator+= now work with key/value pairs passed as initializer list, e.g. j_object += {\"key\", 1} . Overworked CMakeLists.txt to make it easier to integrate the library into other projects. Notes \u00b6 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. v1.1.0 \u00b6 Files json.hpp (257 KB) json.hpp.asc (1 KB) Release date: 2016-01-24 SHA-256: c0cf0e3017798ca6bb18e757ebc570d21a3bdac877845e2b9e9573d183ed2f05 Summary \u00b6 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: Changes \u00b6 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] Notes \u00b6 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. v1.0.0 \u00b6 Files json.hpp (243 KB) json.hpp.asc (1 KB) Release date: 2015-12-28 SHA-256: 767dc2fab1819d7b9e19b6e456d61e38d21ef7182606ecf01516e3f5230446de Summary \u00b6 This is the first official release. Compared to the prerelease version 1.0.0-rc1 , only a few minor improvements have been made: Changes \u00b6 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.","title":"Releases"},{"location":"home/releases/#releases","text":"","title":"Releases"},{"location":"home/releases/#v373","text":"Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)","title":"v3.7.3"},{"location":"home/releases/#summary","text":"This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes","text":"Removed reserve() calls from the destructor which could lead to quadratic complexity. #1837 #1838","title":"Bug Fixes"},{"location":"home/releases/#deprecated-functions","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v372","text":"Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)","title":"v3.7.2"},{"location":"home/releases/#summary_1","text":"Project bad_json_parsers tested how JSON parser libraries react on deeply nested inputs . It turns out that this library segfaulted at a certain nesting depth. This bug was fixed with this release. Now the parsing is only bounded by the available memory. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_1","text":"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","title":"Bug Fixes"},{"location":"home/releases/#further-changes","text":"Added WhiteStone Bolt. #1830","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_1","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v371","text":"Files include.zip (273 KB) include.zip.asc (1 KB) json.hpp (789 KB) json.hpp.asc (1 KB) Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)","title":"v3.7.1"},{"location":"home/releases/#summary_2","text":"This release fixes several small bugs in the library. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_2","text":"Fixed a segmentation fault when serializing std::int64_t minimum value. #1708 #1722 Fixed the contains() function for JSON Pointers. #1727 #1741 Fixed too lax SFINAE guard for conversion from std::pair and std::tuple to json . #1805 #1806 #1825 #1826 Fixed some regressions detected by UBSAN. Updated CI to use Clang-Tidy 7.1.0. #1716 #1728 Fixed integer truncation in iteration_proxy . #1797 Updated Hedley to v11 to fix a E2512 error in MSVC. #1799 Fixed a compile error in enum deserialization of non non-default-constructible types. #1647 #1821 Fixed the conversion from json to std::valarray .","title":"Bug Fixes"},{"location":"home/releases/#improvements","text":"The items() function can now be used with a custom string type. #1765 Made json_pointer::back const . #1764 #1769 Meson is part of the release archive. #1672 #1694 Improved documentation on the Meson and Spack package manager. #1694 #1720","title":"Improvements"},{"location":"home/releases/#further-changes_1","text":"Added GitHub Workflow with ubuntu-latest /GCC 7.4.0 as CI step. Added GCC 9 to Travis CI to compile with C++20 support. #1724 Added MSVC 2019 to the AppVeyor CI. #1780 Added badge to fuzzing status . Fixed some cppcheck warnings. #1760 Fixed several typos in the documentation. #1720 #1767 #1803 Added documentation on the JSON_THROW_USER , JSON_TRY_USER , and JSON_CATCH_USER macros to control user-defined exception handling. Used GitHub's CODEOWNERS and SECURITY feature. Removed GLOB from CMake files. #1779 Updated to Doctest 2.3.5.","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_2","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v370","text":"Files include.zip (143 KB) include.zip.asc (1 KB) json.hpp (782 KB) json.hpp.asc (1 KB) Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)","title":"v3.7.0"},{"location":"home/releases/#summary_3","text":"This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_3","text":"Fix an issue where typedefs with certain names yielded a compilation error. #1642 #1643 Fix a conversion to std::string_view in the unit tests. #1634 #1639 Fix MSVC Debug build. #1536 #1570 #1608 Fix get_to method to clear existing content before writing. #1511 #1555 Fix a -Wc++17-extensions warning. nodiscard attributes are now only used with Clang when -std=c++17 is used. #1535 #1551","title":"Bug Fixes"},{"location":"home/releases/#improvements_1","text":"Switch from Catch to doctest for the unit tests which speeds up compilation and runtime of the 112,112,308 tests. Add an explicit section to the README about the frequently addressed topics character encoding , comments in JSON , and the order of object keys .","title":"Improvements"},{"location":"home/releases/#further-changes_2","text":"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.","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_3","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v361","text":"Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)","title":"v3.6.1"},{"location":"home/releases/#summary_4","text":"This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_4","text":"Fixed regression of #590 which could lead to compilation errors with GCC 7 and GCC 8. #1530 Fixed a compilation error when was included. #1531","title":"Bug Fixes"},{"location":"home/releases/#further-changes_3","text":"Fixed a warning for missing field initializers. #1527","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_4","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v360","text":"Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip) \u2139\ufe0f This release introduced a regression. Please update to version 3.6.1 !","title":"v3.6.0"},{"location":"home/releases/#summary_5","text":"This release adds some convenience functions for JSON Pointers , introduces a contains function to check if a key is present in an object, and improves the performance of integer serialization . Furthermore, a lot of small bug fixes and improvements have been made. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_1","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_5","text":"Fixed a compilation issues with libc 2.12. #1483 #1514 Fixed endian conversion on PPC64. #1489 Fixed library to compile with GCC 9. #1472 #1492 Fixed a compilation issue with GCC 7 on CentOS. #1496 Fixed an integer overflow. #1447 Fixed buffer flushing in serializer. #1445 #1446","title":"Bug Fixes"},{"location":"home/releases/#improvements_2","text":"The performance of dumping integers has been greatly improved. #1411 Added CMake parameter JSON_Install to control whether the library should be installed (default: on). #1330 Fixed a lot of compiler and linter warnings. #1400 #1435 #1502 Reduced required CMake version from 3.8 to 3.1. #1409 #1428 #1441 #1498 Added nodiscard attribute to meta() , array() , object() , from_cbor , from_msgpack , from_ubjson , from_bson , and parse . #1433","title":"Improvements"},{"location":"home/releases/#further-changes_4","text":"Added missing headers. #1500 Fixed typos and broken links in README. #1417 #1423 #1425 #1451 #1455 #1491 Fixed documentation of parse function. #1473 Suppressed warning that cannot be fixed inside the library. #1401 #1468 Imroved package manager suppert: Updated Buckaroo instructions. #1495 Improved Meson support. #1463 Added Conda package manager documentation. #1430 Added NuGet package manager documentation. #1132 Continuous Integration Removed unstable or deprecated Travis builders (Xcode 6.4 - 8.2) and added Xcode 10.1 builder. Added Clang 7 to Travis CI. Fixed AppVeyor x64 builds. #1374 #1414 Updated thirdparty libraries: Catch 1.12.0 -> 1.12.2 Google Benchmark 1.3.0 -> 1.4.1 Doxygen 1.8.15 -> 1.8.16","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_5","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v350","text":"Files include.zip (133 KB) include.zip.asc (1 KB) json.hpp (693 KB) json.hpp.asc (1 KB) Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)","title":"v3.5.0"},{"location":"home/releases/#summary_6","text":"This release introduces the support for structured bindings and reading from FILE* . Besides, a few bugs have been fixed. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_2","text":"Structured bindings are now supported for JSON objects and arrays via the items() member function, so finally this code is possible: for ( auto & [ key , val ] : j . items ()) { std :: cout << key << ':' << val << '\\n' ; } #1388 #1391 Added support for reading from FILE* to support situations in which streams are nit available or would require too much RAM. #1370 #1392","title":"New Features"},{"location":"home/releases/#bug-fixes_6","text":"The eofbit was not set for input streams when the end of a stream was reached while parsing. #1340 #1343 Fixed a bug in the SAX parser for BSON arrays.","title":"Bug Fixes"},{"location":"home/releases/#improvements_3","text":"Added support for Clang 5.0.1 (PS4 version). #1341 #1342","title":"Improvements"},{"location":"home/releases/#further-changes_5","text":"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 Added code to allow installation via Meson. #1345","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_6","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v340","text":"Files include.zip (132 KB) include.zip.asc (1 KB) json.hpp (689 KB) json.hpp.asc (1 KB) Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)","title":"v3.4.0"},{"location":"home/releases/#summary_7","text":"This release introduces three new features: 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.","title":"Summary"},{"location":"home/releases/#new-features_3","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_7","text":"fixed truncation #1286 #1315 fixed an issue with std::pair #1299 #1301 fixed an issue with std::variant #1292 #1294 fixed a bug in the JSON Pointer parser","title":"Bug Fixes"},{"location":"home/releases/#improvements_4","text":"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: '' 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: '' . #1280 #1288 #1303","title":"Improvements"},{"location":"home/releases/#further-changes_6","text":"improved Meson documentation #1305 fixed some more linter warnings #1280 fixed Clang detection for third-party Google Benchmark library #1277","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_7","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v330","text":"Files include.zip (123 KB) include.zip.asc (1 KB) json.hpp (635 KB) json.hpp.asc (1 KB) Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)","title":"v3.3.0"},{"location":"home/releases/#summary_8","text":"This release adds support for GCC 4.8 . Furthermore, it adds a function get_to to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented. Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_4","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_8","text":"Fixed a bug in the CMake file that made target_link_libraries to not properly include nlohmann_json . #1243 #1245 #1260 Fixed a warning in MSVC 2017 complaining about a constexpr if. #1204 #1268 #1272 Fixed a bug that prevented compilation with ICPC. #755 #1222 Improved the SFINAE correctness to fix a bug in the conversion operator. #1237 #1238 Fixed a -Wctor-dtor-privacy warning. #1224 Fixed a warning on a lambda in unevaluated context. #1225 #1230 Fixed a bug introduced in version 3.2.0 where defining JSON_CATCH_USER led to duplicate macro definition of JSON_INTERNAL_CATCH . #1213 #1214 Fixed a bug that prevented compilation with Clang 3.4.2 in RHEL 7. #1179 #1249","title":"Bug Fixes"},{"location":"home/releases/#improvements_5","text":"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","title":"Improvements"},{"location":"home/releases/#further-changes_7","text":"GCC 4.8 and Xcode 10 were added to the continuous integration suite at Travis. Added lgtm checks to pull requests. Added tests for CMake integration. #1260","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_8","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v320","text":"Files include.zip (124 KB) include.zip.asc (1 KB) json.hpp (636 KB) json.hpp.asc (1 KB) Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)","title":"v3.2.0"},{"location":"home/releases/#summary_9","text":"This release introduces a SAX interface to the library. While this may be a very special feature used by only few people, it allowed to unify all functions that consumed input and created some kind of JSON value. Internally, now all existing functions like parse , accept , from_cbor , from_msgpack , and from_ubjson use the SAX interface with different event processors. This allowed to separate the input processing from the value generation. Furthermore, throwing an exception in case of a parse error is now optional and up to the event processor. Finally, the JSON parser is now non-recursive (meaning it does not use the call stack, but std::vector 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.","title":"Summary"},{"location":"home/releases/#new-features_5","text":"added a parser with a SAX interface (#971, #1153) 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)","title":"New Features"},{"location":"home/releases/#bug-fixes_9","text":"allow to create nullptr_t from JSON allowing to properly roundtrip null values (#1169) allow compare user-defined string types (#1130) better support for algorithms using iterators from items() (#1045, #1134) added parameter to avoid compilation error with MSVC 2015 debug builds (#1114) re-added accidentally skipped unit tests (#1176) fixed MSVC issue with std::swap (#1168)","title":"Bug Fixes"},{"location":"home/releases/#improvements_6","text":"key() function for iterators returns a const reference rather than a string copy (#1098) binary formats CBOR, MessagePack, and UBJSON now supports float as type for floating-point numbers (#1021)","title":"Improvements"},{"location":"home/releases/#further-changes_8","text":"changed issue templates 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 updated to Catch 1.12.0","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_9","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v312","text":"Files include.zip (115 KB) include.zip.asc (1 KB) json.hpp (582 KB) json.hpp.asc (1 KB) Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)","title":"v3.1.2"},{"location":"home/releases/#summary_10","text":"This release fixes several bugs in the library. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_10","text":"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).","title":"Bug Fixes"},{"location":"home/releases/#improvements_7","text":"The parser and the serialization now support user-defined string types (#1006, #1009).","title":"Improvements"},{"location":"home/releases/#further-changes_9","text":"Clang Analyzer is now used as additional static analyzer; see make clang_analyze . Overworked README by adding links to the documentation (#981).","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_10","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v311","text":"Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)","title":"v3.1.1"},{"location":"home/releases/#summary_11","text":"This release fixes several bugs in the library. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_11","text":"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() .","title":"Bug Fixes"},{"location":"home/releases/#further-changes_10","text":"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 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).","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_11","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v310","text":"Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)","title":"v3.1.0"},{"location":"home/releases/#summary_12","text":"This release adds support for the UBJSON format and JSON Merge Patch . It also contains some minor changes and bug fixes. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_6","text":"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.","title":"New features"},{"location":"home/releases/#improvements_8","text":"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.","title":"Improvements"},{"location":"home/releases/#reorganization","text":"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).","title":"Reorganization"},{"location":"home/releases/#further-changes_11","text":"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.","title":"Further changes"},{"location":"home/releases/#deprecated-functions_12","text":"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): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.","title":"Deprecated functions"},{"location":"home/releases/#v301","text":"Files json.hpp (502 KB) json.hpp.asc (1 KB) Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c","title":"v3.0.1"},{"location":"home/releases/#summary_13","text":"This release fixes small issues in the implementation of JSON Pointer and JSON Patch . All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#changes","text":"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) Fixed some compiler warnings (see #858, #882).","title":"Changes"},{"location":"home/releases/#deprecated-functions_13","text":"To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.","title":"Deprecated functions"},{"location":"home/releases/#v300","text":"Files json.hpp (501 KB) json.hpp.asc (1 KB) Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462","title":"v3.0.0"},{"location":"home/releases/#summary_14","text":"After almost a year, here is finally a new release of JSON for Modern C++, and it is a major one! As we adhere to semantic versioning , this means the release includes some breaking changes, so please read the next section carefully before you update. But don't worry, we also added a few new features and put a lot of effort into fixing a lot of bugs and straighten out a few inconsistencies.","title":"Summary"},{"location":"home/releases/#breaking-changes","text":"This section describes changes that change the public API of the library and may require changes in code using a previous version of the library. In section \"Moving from 2.x.x to 3.0.0\" at the end of the release notes, we describe in detail how existing code needs to be changed. The library now uses user-defined exceptions instead of re-using those defined in (#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 , , and 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).","title":"Breaking changes"},{"location":"home/releases/#deprecated-functions_14","text":"To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.","title":"Deprecated functions"},{"location":"home/releases/#new-features_7","text":"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 (#494). Fixed support for std::valarray (#702), std::array (#553), and std::map (#600, #607).","title":"New features"},{"location":"home/releases/#further-changes_12","text":"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.","title":"Further changes"},{"location":"home/releases/#moving-from-2xx-to-300","text":"","title":"Moving from 2.x.x to 3.0.0"},{"location":"home/releases/#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: new exception previous exception parse_error.101 invalid_argument parse_error.102 invalid_argument parse_error.103 invalid_argument parse_error.104 invalid_argument parse_error.105 invalid_argument parse_error.106 domain_error parse_error.107 domain_error parse_error.108 domain_error parse_error.109 invalid_argument parse_error.110 out_of_range parse_error.111 invalid_argument parse_error.112 invalid_argument invalid_iterator.201 domain_error invalid_iterator.202 domain_error invalid_iterator.203 domain_error invalid_iterator.204 out_of_range invalid_iterator.205 out_of_range invalid_iterator.206 domain_error invalid_iterator.207 domain_error invalid_iterator.208 domain_error invalid_iterator.209 domain_error invalid_iterator.210 domain_error invalid_iterator.211 domain_error invalid_iterator.212 domain_error invalid_iterator.213 domain_error invalid_iterator.214 out_of_range type_error.301 domain_error type_error.302 domain_error type_error.303 domain_error type_error.304 domain_error type_error.305 domain_error type_error.306 domain_error type_error.307 domain_error type_error.308 domain_error type_error.309 domain_error type_error.310 domain_error type_error.311 domain_error type_error.313 domain_error type_error.314 domain_error type_error.315 domain_error out_of_range.401 out_of_range out_of_range.402 out_of_range out_of_range.403 out_of_range out_of_range.404 out_of_range out_of_range.405 domain_error other_error.501 domain_error","title":"User-defined Exceptions"},{"location":"home/releases/#handling-of-nan-and-inf","text":"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 .","title":"Handling of NaN and INF"},{"location":"home/releases/#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 ); New code: json j = json :: parse ( ss , cb ); If no callback function is used, also the following code works: json j ; j << ss ; or json j ; ss >> j ;","title":"Removal of deprecated functions"},{"location":"home/releases/#v211","text":"Files json.hpp (437 KB) json.hpp.asc (1 KB) Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57","title":"v2.1.1"},{"location":"home/releases/#summary_15","text":"This release fixes a locale-related bug in the parser . To do so, the whole number handling (lexer, parser, and also the serialization) have been overworked. Furthermore, a lot of small changes added up that were added to this release. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#changes_1","text":"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 . Removed Doozer. Added Codacity. Upgraded Catch to version 1.7.2.","title":"Changes"},{"location":"home/releases/#v210","text":"Files json.hpp (426 KB) json.hpp.asc (1 KB) Release date: 2017-01-28 SHA-256: a571dee92515b685784fd527e38405cf3f5e13e96edbfe3f03d6df2e363a767b","title":"v2.1.0"},{"location":"home/releases/#summary_16","text":"This release introduces a means to convert from/to user-defined types. The release is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_2","text":"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. Updated to Catch v1.6.0 . Some typos in the documentation have been fixed.","title":"Changes"},{"location":"home/releases/#v2010","text":"Files json.hpp (409 KB) json.hpp.asc (1 KB) Release date: 2017-01-02 SHA-256: ec27d4e74e9ce0f78066389a70724afd07f10761009322dc020656704ad5296d","title":"v2.0.10"},{"location":"home/releases/#summary_17","text":"This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_3","text":"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.","title":"Changes"},{"location":"home/releases/#v209","text":"Files json.hpp (406 KB) json.hpp.asc (1 KB) Release date: 2016-12-16 SHA-256: fbf3396f13e187d6c214c297bddc742d918ea9b55e10bfb3d9f458b9bfdc22e5","title":"v2.0.9"},{"location":"home/releases/#summary_18","text":"This release implements with CBOR and MessagePack two binary serialization/deserialization formats . It further contains some small fixes and improvements. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_4","text":"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 test suite now contains 11201886 tests","title":"Changes"},{"location":"home/releases/#v208","text":"Files json.hpp (360 KB) json.hpp.asc (1 KB) Release date: 2016-12-02 SHA-256: b70db0ad34f8e0e61dc3f0cbab88099336c9674c193d8a3439d93d6aca2d7120","title":"v2.0.8"},{"location":"home/releases/#summary_19","text":"This release combines a lot of small fixes and improvements. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_5","text":"fixed a bug that froze the parser if a passed file was not found (now, std::invalid_argument is thrown) fixed a bug that lead to an error of a file at EOF was parsed again (now, std::invalid_argument is thrown) the well known functions emplace and emplace_back have been added to JSON values and work as expected improved the performance of the serialization ( dump function) improved the performance of the deserialization (parser) some continuous integration images at Travis were added and retired; see here for the current continuous integration setup the Coverity scan works again the benchmarking code has been improved to produce more stable results the README file has been extended and includes more frequently asked examples the test suite now contains 8905518 tests updated Catch to version 1.5.8","title":"Changes"},{"location":"home/releases/#v207","text":"Files json.hpp (355 KB) json.hpp.asc (1 KB) Release date: 2016-11-02 SHA-256: 5545c323670f8165bae90b9dc6078825e86ec310d96cc4e5b47233ea43715bbf","title":"v2.0.7"},{"location":"home/releases/#summary_20","text":"This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_6","text":"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.","title":"Changes"},{"location":"home/releases/#v206","text":"Files json.hpp (349 KB) json.hpp.asc (1 KB) Release date: 2016-10-15 SHA256: 459cc93d5e2f503e50c6d5876eb86bfea7daf405f5a567c5a2c9abc2383756ae","title":"v2.0.6"},{"location":"home/releases/#summary_21","text":"This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_7","text":"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 restored test coverage to 100%.","title":"Changes"},{"location":"home/releases/#v205","text":"Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-14 SHA-256: 8b7565263a44e2b7d3b89808bc73d2d639037ff0c1f379e3d56dbd77e00b98d9","title":"v2.0.5"},{"location":"home/releases/#summary_22","text":"This release fixes a regression bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_8","text":"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.","title":"Changes"},{"location":"home/releases/#v204","text":"Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-11 SHA-256: 632ceec4c25c4e2153f71470d3a2b992c8355f6d8b4d627d05dd16095cd3aeda","title":"v2.0.4"},{"location":"home/releases/#summary_23","text":"This release fixes a bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_9","text":"Bug fix : The end of a file stream was not detected properly which led to parse errors. Fixed a compiler warning about an unused variable.","title":"Changes"},{"location":"home/releases/#v203","text":"Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-08-31 SHA-256: 535b73efe5546fde9e763c14aeadfc7b58183c0b3cd43c29741025aba6cf6bd3","title":"v2.0.3"},{"location":"home/releases/#summary_24","text":"This release combines a lot of small fixes and improvements. The release is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_10","text":"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.","title":"Changes"},{"location":"home/releases/#v202","text":"Files json.hpp (338 KB) json.hpp.asc (1 KB) Release date: 2016-07-31 SHA-256: 8e97b7965b4594b00998d6704465412360e1a0ed927badb51ded8b82291a8f3d","title":"v2.0.2"},{"location":"home/releases/#summary_25","text":"This release combines a lot of small fixes and improvements. The release is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_11","text":"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. Avoided output to std::cout in the test cases.","title":"Changes"},{"location":"home/releases/#v201","text":"Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-28 SHA-256: ef550fcd7df572555bf068e9ec4e9d3b9e4cdd441cecb0dcea9ea7fd313f72dd","title":"v2.0.1"},{"location":"home/releases/#summary_26","text":"This release fixes a performance regression in the JSON serialization (function dump() ). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_12","text":"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.","title":"Changes"},{"location":"home/releases/#v200","text":"Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-24 SHA-256: ac9e1fb25c2ac9ca5fc501fcd2fe3281fe04f07018a1b48820e7b1b11491bb6c","title":"v2.0.0"},{"location":"home/releases/#summary_27","text":"This release adds several features such as JSON Pointers, JSON Patch, or support for 64 bit unsigned integers. Furthermore, several (subtle) bugs have been fixed. As noexcept and constexpr specifier have been added to several functions, the public API has effectively been changed in a (potential) non-backwards compatible manner. As we adhere to Semantic Versioning , this calls for a new major version, so say hello to 2\ufe0f\u20e3.0\ufe0f\u20e3.0\ufe0f\u20e3.","title":"Summary"},{"location":"home/releases/#changes_13","text":"\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 ). Added noexcept specifier to basic_json(boolean_t) , basic_json(const number_integer_t) , basic_json(const int) , basic_json(const number_float_t) , iterator functions ( begin() , end() , etc.) When parsing numbers, the sign of 0.0 (vs. -0.0 ) is preserved. Improved MSVC 2015, Android, and MinGW support. See README for more information. Improved test coverage (added 2,225,386 tests). Removed some misuses of std::move . Fixed several compiler warnings. Improved error messages from JSON parser. Updated to re2c to version 0.16 to use a minimal DFAs for the lexer. Updated test suite to use Catch version 1.5.6. Made type getters ( is_number , etc.) and const value access constexpr . Functions push_back and operator+= now work with key/value pairs passed as initializer list, e.g. j_object += {\"key\", 1} . Overworked CMakeLists.txt to make it easier to integrate the library into other projects.","title":"Changes"},{"location":"home/releases/#notes","text":"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.","title":"Notes"},{"location":"home/releases/#v110","text":"Files json.hpp (257 KB) json.hpp.asc (1 KB) Release date: 2016-01-24 SHA-256: c0cf0e3017798ca6bb18e757ebc570d21a3bdac877845e2b9e9573d183ed2f05","title":"v1.1.0"},{"location":"home/releases/#summary_28","text":"This release fixes several small bugs and adds functionality in a backwards-compatible manner. Compared to the last version (1.0.0) , the following changes have been made:","title":"Summary"},{"location":"home/releases/#changes_14","text":"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]","title":"Changes"},{"location":"home/releases/#notes_1","text":"There are still known open issues (#178, #187) which will be fixed in version 2.0.0. However, these fixes will require a small API change and will not be entirely backwards-compatible.","title":"Notes"},{"location":"home/releases/#v100","text":"Files json.hpp (243 KB) json.hpp.asc (1 KB) Release date: 2015-12-28 SHA-256: 767dc2fab1819d7b9e19b6e456d61e38d21ef7182606ecf01516e3f5230446de","title":"v1.0.0"},{"location":"home/releases/#summary_29","text":"This is the first official release. Compared to the prerelease version 1.0.0-rc1 , only a few minor improvements have been made:","title":"Summary"},{"location":"home/releases/#changes_15","text":"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.","title":"Changes"},{"location":"home/sponsors/","text":"Sponsors \u00b6 You can sponsor this library at GitHub Sponsors . Named Sponsors \u00b6 Michael Hartmann Stefan Hagen Steve Sperandeo Robert Jefe Lindst\u00e4dt Steve Wagner Thanks everyone!","title":"Sponsors"},{"location":"home/sponsors/#sponsors","text":"You can sponsor this library at GitHub Sponsors .","title":"Sponsors"},{"location":"home/sponsors/#named-sponsors","text":"Michael Hartmann Stefan Hagen Steve Sperandeo Robert Jefe Lindst\u00e4dt Steve Wagner Thanks everyone!","title":"Named Sponsors"},{"location":"integration/","text":"Header only \u00b6 json.hpp is the single required file in single_include/nlohmann or released here . You need to add #include // for convenience using json = nlohmann :: json ; to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang). You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.","title":"Header only"},{"location":"integration/#header-only","text":"json.hpp is the single required file in single_include/nlohmann or released here . You need to add #include // for convenience using json = nlohmann :: json ; to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang). You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.","title":"Header only"},{"location":"integration/cmake/","text":"CMake \u00b6 Integration \u00b6 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. External \u00b6 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 ) project ( ExampleProject LANGUAGES CXX ) find_package ( nlohmann_json 3.11.2 REQUIRED ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) The package configuration file, nlohmann_jsonConfig.cmake , can be used either from an install tree or directly out of the build tree. Embedded \u00b6 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 ) project ( ExampleProject LANGUAGES CXX ) # If you only include this third party in PRIVATE source files, you do not need to install it # when your main project gets installed. set ( JSON_Install OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) 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. Supporting Both \u00b6 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 ) option ( EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF ) add_subdirectory ( thirdparty ) add_executable ( example example.cpp ) # Note that the namespaced target will always be available regardless of the import method target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) thirdparty/CMakeLists.txt if ( EXAMPLE_USE_EXTERNAL_JSON ) find_package ( nlohmann_json 3.11.2 REQUIRED ) else () set ( JSON_BuildTests OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) endif () thirdparty/nlohmann_json is then a complete copy of this source tree. FetchContent \u00b6 Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type. Example CMakeLists.txt cmake_minimum_required ( VERSION 3.11 ) project ( ExampleProject LANGUAGES CXX ) include ( FetchContent ) FetchContent_Declare ( json URL https://github.com/nlohmann/json/releases/download/v3.11.2/json.tar.xz ) FetchContent_MakeAvailable ( json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) Note It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like FetchContent_Declare ( json GIT_REPOSITORY https://github.com/nlohmann/json GIT_TAG v3.11.2 ) However, the repository https://github.com/nlohmann/json download size is quite large. You might want to depend on a smaller repository. For instance, you might want to replace the URL in the example by https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent . CMake Options \u00b6 JSON_BuildTests \u00b6 Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option. JSON_CI \u00b6 Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default. JSON_Diagnostics \u00b6 Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS . This option is OFF by default. JSON_DisableEnumSerialization \u00b6 Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION . This option is OFF by default. JSON_FastTests \u00b6 Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests . JSON_GlobalUDLs \u00b6 Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS . This option is OFF by default. JSON_ImplicitConversions \u00b6 Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS . This option is ON by default. JSON_Install \u00b6 Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project. JSON_MultipleHeaders \u00b6 Use non-amalgamated version of the library. This option is OFF by default. JSON_SystemInclude \u00b6 Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default. JSON_Valgrind \u00b6 Execute test suite with Valgrind . This option is OFF by default. Depends on JSON_BuildTests .","title":"CMake"},{"location":"integration/cmake/#cmake","text":"","title":"CMake"},{"location":"integration/cmake/#integration","text":"You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags.","title":"Integration"},{"location":"integration/cmake/#external","text":"To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration: Example CMakeLists.txt cmake_minimum_required ( VERSION 3.1 ) project ( ExampleProject LANGUAGES CXX ) find_package ( nlohmann_json 3.11.2 REQUIRED ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) The package configuration file, nlohmann_jsonConfig.cmake , can be used either from an install tree or directly out of the build tree.","title":"External"},{"location":"integration/cmake/#embedded","text":"To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file. Example CMakeLists.txt cmake_minimum_required ( VERSION 3.1 ) project ( ExampleProject LANGUAGES CXX ) # If you only include this third party in PRIVATE source files, you do not need to install it # when your main project gets installed. set ( JSON_Install OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) 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.","title":"Embedded"},{"location":"integration/cmake/#supporting-both","text":"To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following. Example CMakeLists.txt project ( ExampleProject LANGUAGES CXX ) option ( EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF ) add_subdirectory ( thirdparty ) add_executable ( example example.cpp ) # Note that the namespaced target will always be available regardless of the import method target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) thirdparty/CMakeLists.txt if ( EXAMPLE_USE_EXTERNAL_JSON ) find_package ( nlohmann_json 3.11.2 REQUIRED ) else () set ( JSON_BuildTests OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) endif () thirdparty/nlohmann_json is then a complete copy of this source tree.","title":"Supporting Both"},{"location":"integration/cmake/#fetchcontent","text":"Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type. Example CMakeLists.txt cmake_minimum_required ( VERSION 3.11 ) project ( ExampleProject LANGUAGES CXX ) include ( FetchContent ) FetchContent_Declare ( json URL https://github.com/nlohmann/json/releases/download/v3.11.2/json.tar.xz ) FetchContent_MakeAvailable ( json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) Note It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like FetchContent_Declare ( json GIT_REPOSITORY https://github.com/nlohmann/json GIT_TAG v3.11.2 ) However, the repository https://github.com/nlohmann/json download size is quite large. You might want to depend on a smaller repository. For instance, you might want to replace the URL in the example by https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent .","title":"FetchContent"},{"location":"integration/cmake/#cmake-options","text":"","title":"CMake Options"},{"location":"integration/cmake/#json_buildtests","text":"Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option.","title":"JSON_BuildTests"},{"location":"integration/cmake/#json_ci","text":"Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.","title":"JSON_CI"},{"location":"integration/cmake/#json_diagnostics","text":"Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS . This option is OFF by default.","title":"JSON_Diagnostics"},{"location":"integration/cmake/#json_disableenumserialization","text":"Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION . This option is OFF by default.","title":"JSON_DisableEnumSerialization"},{"location":"integration/cmake/#json_fasttests","text":"Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests .","title":"JSON_FastTests"},{"location":"integration/cmake/#json_globaludls","text":"Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS . This option is OFF by default.","title":"JSON_GlobalUDLs"},{"location":"integration/cmake/#json_implicitconversions","text":"Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS . This option is ON by default.","title":"JSON_ImplicitConversions"},{"location":"integration/cmake/#json_install","text":"Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project.","title":"JSON_Install"},{"location":"integration/cmake/#json_multipleheaders","text":"Use non-amalgamated version of the library. This option is OFF by default.","title":"JSON_MultipleHeaders"},{"location":"integration/cmake/#json_systeminclude","text":"Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default.","title":"JSON_SystemInclude"},{"location":"integration/cmake/#json_valgrind","text":"Execute test suite with Valgrind . This option is OFF by default. Depends on JSON_BuildTests .","title":"JSON_Valgrind"},{"location":"integration/migration_guide/","text":"Migration Guide \u00b6 This page collects some guidelines on how to future-proof your code for future versions of this library. Replace deprecated functions \u00b6 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. Parsing \u00b6 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. Deprecated Future-proof nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); j << ss ; nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); ss >> j ; 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}) . Deprecated Future-proof const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ({ s , s + std :: strlen ( s )}); const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ( s , s + std :: strlen ( s )); JSON Pointers \u00b6 Comparing JSON Pointers with strings via operator== and operator!= is deprecated since 3.11.2. To compare a json_pointer p with a string s , convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!= . Deprecated Future-proof nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == \"/foo/bar/1\" ); nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == nlohmann :: json :: json_pointer ( \"/foo/bar/1\" )); 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. Deprecated Future-proof nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr ; nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr . to_string (); 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. Deprecated Future-proof using my_json = nlohmann :: basic_json < std :: map , std :: vector , my_string_type > ; nlohmann :: json_pointer < my_json > ptr ( \"/foo/bar/1\" ); nlohmann :: json_pointer < my_string_type > ptr ( \"/foo/bar/1\" ); Thereby, nlohmann::my_json::json_pointer is an alias for nlohmann::json_pointer and is always an alias to the json_pointer with the appropriate string type for all specializations of basic_json . Miscellaneous functions \u00b6 The function iterator_wrapper is deprecated since 3.1.0. Please use the member function items instead. Deprecated Future-proof for ( auto & x : nlohmann :: json :: iterator_wrapper ( j )) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } for ( auto & x : j . items ()) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } 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. Deprecated Future-proof j >> std :: cout ; std :: cout << j ; 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 . Deprecated Future-proof #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include #include Replace implicit conversions \u00b6 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 . Deprecated Future-proof Future-proof (alternative) nlohmann :: json j = \"Hello, world!\" ; std :: string s = j ; nlohmann :: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > (); nlohmann :: json j = \"Hello, world!\" ; std :: string s ; j . get_to ( s ); You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get . Import namespace literals for UDLs \u00b6 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. Deprecated Future-proof nlohmann :: json j = \"[1,2,3]\" _json ; using namespace nlohmann :: literals ; nlohmann :: json j = \"[1,2,3]\" _json ; To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Do not hard-code the complete library namespace \u00b6 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. Dangerous Future-proof Future-proof (alternative) void to_json ( nlohmann :: json_abi_v3_11_2 :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( nlohmann :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( NLOHMANN_JSON_NAMESPACE :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } Do not use the details namespace \u00b6 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.","title":"Migration Guide"},{"location":"integration/migration_guide/#migration-guide","text":"This page collects some guidelines on how to future-proof your code for future versions of this library.","title":"Migration Guide"},{"location":"integration/migration_guide/#replace-deprecated-functions","text":"The following functions have been deprecated and will be removed in the next major version (i.e., 4.0.0). All deprecations are annotated with HEDLEY_DEPRECATED_FOR to report which function to use instead.","title":"Replace deprecated functions"},{"location":"integration/migration_guide/#parsing","text":"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. Deprecated Future-proof nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); j << ss ; nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); ss >> j ; 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}) . Deprecated Future-proof const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ({ s , s + std :: strlen ( s )}); const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ( s , s + std :: strlen ( s ));","title":"Parsing"},{"location":"integration/migration_guide/#json-pointers","text":"Comparing JSON Pointers with strings via operator== and operator!= is deprecated since 3.11.2. To compare a json_pointer p with a string s , convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!= . Deprecated Future-proof nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == \"/foo/bar/1\" ); nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == nlohmann :: json :: json_pointer ( \"/foo/bar/1\" )); 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. Deprecated Future-proof nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr ; nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr . to_string (); 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. Deprecated Future-proof using my_json = nlohmann :: basic_json < std :: map , std :: vector , my_string_type > ; nlohmann :: json_pointer < my_json > ptr ( \"/foo/bar/1\" ); nlohmann :: json_pointer < my_string_type > ptr ( \"/foo/bar/1\" ); Thereby, nlohmann::my_json::json_pointer is an alias for nlohmann::json_pointer and is always an alias to the json_pointer with the appropriate string type for all specializations of basic_json .","title":"JSON Pointers"},{"location":"integration/migration_guide/#miscellaneous-functions","text":"The function iterator_wrapper is deprecated since 3.1.0. Please use the member function items instead. Deprecated Future-proof for ( auto & x : nlohmann :: json :: iterator_wrapper ( j )) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } for ( auto & x : j . items ()) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } 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. Deprecated Future-proof j >> std :: cout ; std :: cout << j ; 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 . Deprecated Future-proof #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include #include ","title":"Miscellaneous functions"},{"location":"integration/migration_guide/#replace-implicit-conversions","text":"Implicit conversions via operator ValueType will be switched off by default in the next major release of the library. You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get , get_to , get_ref , or get_ptr . Deprecated Future-proof Future-proof (alternative) nlohmann :: json j = \"Hello, world!\" ; std :: string s = j ; nlohmann :: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > (); nlohmann :: json j = \"Hello, world!\" ; std :: string s ; j . get_to ( s ); You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get .","title":"Replace implicit conversions"},{"location":"integration/migration_guide/#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. Deprecated Future-proof nlohmann :: json j = \"[1,2,3]\" _json ; using namespace nlohmann :: literals ; nlohmann :: json j = \"[1,2,3]\" _json ; To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.","title":"Import namespace literals for UDLs"},{"location":"integration/migration_guide/#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. Dangerous Future-proof Future-proof (alternative) void to_json ( nlohmann :: json_abi_v3_11_2 :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( nlohmann :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( NLOHMANN_JSON_NAMESPACE :: json & j , const person & p ) { j [ \"age\" ] = p . age ; }","title":"Do not hard-code the complete library namespace"},{"location":"integration/migration_guide/#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.","title":"Do not use the details namespace"},{"location":"integration/package_managers/","text":"Package Managers \u00b6 Throughout this page, we will describe how to compile the example file example.cpp below. #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } When executed, this program should create output similar to { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } } Homebrew \u00b6 If you are using OS X and Homebrew , just type brew install nlohmann-json and you're set. If you want the bleeding edge rather than the latest release, use brew install nlohmann-json --HEAD instead. See nlohmann-json for more information. Example Create the following file: example.cpp #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } Install the package brew install nlohmann-json Determine the include path, which defaults to /usr/local/Cellar/nlohmann-json/$version/include , where $version is the version of the library, e.g. 3.7.3 . The path of the library can be determined with brew list nlohmann-json Compile the code. For instance, the code can be compiled using Clang with clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std = c++11 -o example The formula is updated automatically. Meson \u00b6 If you are using the Meson Build System , add this source tree as a meson subproject . You may also use the include.zip published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB , or simply use meson wrap install nlohmann_json . Please see the meson project for any issues regarding the packaging. The provided meson.build can also be used as an alternative to cmake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly. Bazel \u00b6 This repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive , git_repository , or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g. via deps attribute). Conan \u00b6 If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile 's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages. Example Create the following files: Conanfile.txt [requires] nlohmann_json/3.7.3 [generators] cmake CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) add_definitions ( \"-std=c++11\" ) include ( ${ CMAKE_BINARY_DIR } /conanbuildinfo.cmake ) conan_basic_setup () add_executable ( json_example example.cpp ) target_link_libraries ( json_example ${ CONAN_LIBS } ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Build: mkdir build cd build conan install .. cmake .. cmake --build . The package is updated automatically. Spack \u00b6 If you are using Spack to manage your dependencies, you can use the nlohmann-json package . Please see the spack project for any issues regarding the packaging. Hunter \u00b6 If you are using hunter on your project for external dependencies, then you can use the nlohmann_json package . Please see the hunter project for any issues regarding the packaging. Buckaroo \u00b6 If you are using Buckaroo , you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json . Please file issues here . There is a demo repo here . vcpkg \u00b6 If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with vcpkg install nlohmann-json and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging. Example Create the following files: CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) find_package ( nlohmann_json CONFIG REQUIRED ) add_executable ( json_example example.cpp ) target_link_libraries ( json_example PRIVATE nlohmann_json::nlohmann_json ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Install package: vcpkg install nlohmann-json Build: mkdir build cd build cmake .. -DCMAKE_TOOLCHAIN_FILE = /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake cmake --build . Note you need to adjust /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake to your system. cget \u00b6 If you are using cget , you can install the latest development version with cget install nlohmann/json . A specific version can be installed with cget install nlohmann/json@v3.1.0 . Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON ). cget reads directly from the GitHub repository and is always up-to-date. CocoaPods \u00b6 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 . NuGet \u00b6 If you are using NuGet , you can use the package nlohmann.json . Please check this extensive description on how to use the package. Please file issues here . Conda \u00b6 If you are using conda , you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json . Please file issues here . MSYS2 \u00b6 If you are using MSYS2 , you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages. The package is updated automatically. MacPorts \u00b6 If you are using MacPorts , execute sudo port install nlohmann-json to install the nlohmann-json package. The package is updated automatically. build2 \u00b6 If you are using build2 , you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository . In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints ). If you are not familiar with using dependencies in build2 , please read this introduction . Please file issues here if you experience problems with the packages. The package is updated automatically. wsjcpp \u00b6 If you are using wsjcpp , you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch. wsjcpp reads directly from the GitHub repository and is always up-to-date. CPM.cmake \u00b6 If you are using CPM.cmake , you can check this example . After adding CPM script to your project, implement the following snippet to your CMake: CPMAddPackage ( NAME nlohmann_json GITHUB_REPOSITORY nlohmann/json VERSION 3.9.1 )","title":"Package Managers"},{"location":"integration/package_managers/#package-managers","text":"Throughout this page, we will describe how to compile the example file example.cpp below. #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } When executed, this program should create output similar to { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } }","title":"Package Managers"},{"location":"integration/package_managers/#homebrew","text":"If you are using OS X and Homebrew , just type brew install nlohmann-json and you're set. If you want the bleeding edge rather than the latest release, use brew install nlohmann-json --HEAD instead. See nlohmann-json for more information. Example Create the following file: example.cpp #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } Install the package brew install nlohmann-json Determine the include path, which defaults to /usr/local/Cellar/nlohmann-json/$version/include , where $version is the version of the library, e.g. 3.7.3 . The path of the library can be determined with brew list nlohmann-json Compile the code. For instance, the code can be compiled using Clang with clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std = c++11 -o example The formula is updated automatically.","title":"Homebrew"},{"location":"integration/package_managers/#meson","text":"If you are using the Meson Build System , add this source tree as a meson subproject . You may also use the include.zip published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB , or simply use meson wrap install nlohmann_json . Please see the meson project for any issues regarding the packaging. The provided meson.build can also be used as an alternative to cmake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly.","title":"Meson"},{"location":"integration/package_managers/#bazel","text":"This repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive , git_repository , or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g. via deps attribute).","title":"Bazel"},{"location":"integration/package_managers/#conan","text":"If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile 's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages. Example Create the following files: Conanfile.txt [requires] nlohmann_json/3.7.3 [generators] cmake CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) add_definitions ( \"-std=c++11\" ) include ( ${ CMAKE_BINARY_DIR } /conanbuildinfo.cmake ) conan_basic_setup () add_executable ( json_example example.cpp ) target_link_libraries ( json_example ${ CONAN_LIBS } ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Build: mkdir build cd build conan install .. cmake .. cmake --build . The package is updated automatically.","title":"Conan"},{"location":"integration/package_managers/#spack","text":"If you are using Spack to manage your dependencies, you can use the nlohmann-json package . Please see the spack project for any issues regarding the packaging.","title":"Spack"},{"location":"integration/package_managers/#hunter","text":"If you are using hunter on your project for external dependencies, then you can use the nlohmann_json package . Please see the hunter project for any issues regarding the packaging.","title":"Hunter"},{"location":"integration/package_managers/#buckaroo","text":"If you are using Buckaroo , you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json . Please file issues here . There is a demo repo here .","title":"Buckaroo"},{"location":"integration/package_managers/#vcpkg","text":"If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with vcpkg install nlohmann-json and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging. Example Create the following files: CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) find_package ( nlohmann_json CONFIG REQUIRED ) add_executable ( json_example example.cpp ) target_link_libraries ( json_example PRIVATE nlohmann_json::nlohmann_json ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Install package: vcpkg install nlohmann-json Build: mkdir build cd build cmake .. -DCMAKE_TOOLCHAIN_FILE = /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake cmake --build . Note you need to adjust /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake to your system.","title":"vcpkg"},{"location":"integration/package_managers/#cget","text":"If you are using cget , you can install the latest development version with cget install nlohmann/json . A specific version can be installed with cget install nlohmann/json@v3.1.0 . Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON ). cget reads directly from the GitHub repository and is always up-to-date.","title":"cget"},{"location":"integration/package_managers/#cocoapods","text":"If you are using CocoaPods , you can use the library by adding pod \"nlohmann_json\", '~>3.1.2' to your podfile (see an example ). Please file issues here .","title":"CocoaPods"},{"location":"integration/package_managers/#nuget","text":"If you are using NuGet , you can use the package nlohmann.json . Please check this extensive description on how to use the package. Please file issues here .","title":"NuGet"},{"location":"integration/package_managers/#conda","text":"If you are using conda , you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json . Please file issues here .","title":"Conda"},{"location":"integration/package_managers/#msys2","text":"If you are using MSYS2 , you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages. The package is updated automatically.","title":"MSYS2"},{"location":"integration/package_managers/#macports","text":"If you are using MacPorts , execute sudo port install nlohmann-json to install the nlohmann-json package. The package is updated automatically.","title":"MacPorts"},{"location":"integration/package_managers/#build2","text":"If you are using build2 , you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository . In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints ). If you are not familiar with using dependencies in build2 , please read this introduction . Please file issues here if you experience problems with the packages. The package is updated automatically.","title":"build2"},{"location":"integration/package_managers/#wsjcpp","text":"If you are using wsjcpp , you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch. wsjcpp reads directly from the GitHub repository and is always up-to-date.","title":"wsjcpp"},{"location":"integration/package_managers/#cpmcmake","text":"If you are using CPM.cmake , you can check this example . After adding CPM script to your project, implement the following snippet to your CMake: CPMAddPackage ( NAME nlohmann_json GITHUB_REPOSITORY nlohmann/json VERSION 3.9.1 )","title":"CPM.cmake"},{"location":"integration/pkg-config/","text":"Pkg-config \u00b6 If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed: pkg-config nlohmann_json --cflags Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config : json = dependency ( 'nlohmann_json' , required : true )","title":"Pkg-config"},{"location":"integration/pkg-config/#pkg-config","text":"If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed: pkg-config nlohmann_json --cflags Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config : json = dependency ( 'nlohmann_json' , required : true )","title":"Pkg-config"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-\\.]"},"docs":[{"location":"","text":"JSON for Modern C++ \u00b6","title":"JSON for Modern C++"},{"location":"#json-for-modern-c","text":"","title":"JSON for Modern C++"},{"location":"api/json/","text":"nlohmann:: json \u00b6 using json = basic_json <> ; This type is the default specialization of the basic_json class which uses the standard template types. Examples \u00b6 Example The example below demonstrates how to use the type nlohmann::json . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 } Version history \u00b6 Since version 1.0.0.","title":"json"},{"location":"api/json/#nlohmannjson","text":"using json = basic_json <> ; This type is the default specialization of the basic_json class which uses the standard template types.","title":"nlohmann::json"},{"location":"api/json/#examples","text":"Example The example below demonstrates how to use the type nlohmann::json . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 }","title":"Examples"},{"location":"api/json/#version-history","text":"Since version 1.0.0.","title":"Version history"},{"location":"api/operator_gtgt/","text":"nlohmann:: operator>>(basic_json) \u00b6 std :: istream & operator >> ( std :: istream & i , basic_json & j ); Deserializes an input stream to a JSON value. Parameters \u00b6 i (in, out) input stream to read a serialized JSON value from j (in, out) JSON value to write the deserialized input to Return value \u00b6 the stream i Exceptions \u00b6 Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails. Complexity \u00b6 Linear in the length of the input. The parser is a predictive LL(1) parser. Notes \u00b6 A UTF-8 byte order mark is silently ignored. Deprecation This function replaces function std :: istream & operator << ( basic_json & j , std :: istream & i ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i ; with i >> j ; . Examples \u00b6 Example The example below shows how a JSON value is constructed by reading a serialization from a stream. #include #include #include #include using json = nlohmann :: json ; int main () { // create stream with serialized JSON std :: stringstream ss ; ss << R \" ( { \"number\": 23, \"string\": \"Hello, world!\", \"array\": [1, 2, 3, 4, 5], \"boolean\": false, \"null\": null } ) \" ; // create JSON value and read the serialization from the stream json j ; ss >> j ; // serialize JSON std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"array\" : [ 1 , 2 , 3 , 4 , 5 ], \"boolean\" : false , \"null\" : null , \"number\" : 23 , \"string\" : \"Hello, world!\" } See also \u00b6 accept - check if the input is valid JSON parse - deserialize from a compatible input Version history \u00b6 Added in version 1.0.0. Deprecated in version 3.0.0.","title":"operator>>(basic_json)"},{"location":"api/operator_gtgt/#nlohmannoperatorbasic_json","text":"std :: istream & operator >> ( std :: istream & i , basic_json & j ); Deserializes an input stream to a JSON value.","title":"nlohmann::operator>>(basic_json)"},{"location":"api/operator_gtgt/#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","title":"Parameters"},{"location":"api/operator_gtgt/#return-value","text":"the stream i","title":"Return value"},{"location":"api/operator_gtgt/#exceptions","text":"Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails.","title":"Exceptions"},{"location":"api/operator_gtgt/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser.","title":"Complexity"},{"location":"api/operator_gtgt/#notes","text":"A UTF-8 byte order mark is silently ignored. Deprecation This function replaces function std :: istream & operator << ( basic_json & j , std :: istream & i ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j << i ; with i >> j ; .","title":"Notes"},{"location":"api/operator_gtgt/#examples","text":"Example The example below shows how a JSON value is constructed by reading a serialization from a stream. #include #include #include #include using json = nlohmann :: json ; int main () { // create stream with serialized JSON std :: stringstream ss ; ss << R \" ( { \"number\": 23, \"string\": \"Hello, world!\", \"array\": [1, 2, 3, 4, 5], \"boolean\": false, \"null\": null } ) \" ; // create JSON value and read the serialization from the stream json j ; ss >> j ; // serialize JSON std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"array\" : [ 1 , 2 , 3 , 4 , 5 ], \"boolean\" : false , \"null\" : null , \"number\" : 23 , \"string\" : \"Hello, world!\" }","title":"Examples"},{"location":"api/operator_gtgt/#see-also","text":"accept - check if the input is valid JSON parse - deserialize from a compatible input","title":"See also"},{"location":"api/operator_gtgt/#version-history","text":"Added in version 1.0.0. Deprecated in version 3.0.0.","title":"Version history"},{"location":"api/operator_literal_json/","text":"nlohmann:: operator\"\"_json \u00b6 json operator \"\" _json ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details. Parameters \u00b6 s (in) a string representation of a JSON object n (in) length of string s Return value \u00b6 json value parsed from s Exceptions \u00b6 The function can throw anything that parse(s, s+n) would throw. Complexity \u00b6 Linear. Examples \u00b6 Example The following code shows how to create JSON values from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"answer\" : 42 , \"hello\" : \"world\" } Version history \u00b6 Added in version 1.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"operator\"\"_json"},{"location":"api/operator_literal_json/#nlohmannoperator_json","text":"json operator \"\" _json ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON objects. It can be used by adding _json to a string literal and returns a json object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.","title":"nlohmann::operator\"\"_json"},{"location":"api/operator_literal_json/#parameters","text":"s (in) a string representation of a JSON object n (in) length of string s","title":"Parameters"},{"location":"api/operator_literal_json/#return-value","text":"json value parsed from s","title":"Return value"},{"location":"api/operator_literal_json/#exceptions","text":"The function can throw anything that parse(s, s+n) would throw.","title":"Exceptions"},{"location":"api/operator_literal_json/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/operator_literal_json/#examples","text":"Example The following code shows how to create JSON values from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; std :: cout << std :: setw ( 2 ) << j << '\\n' ; } Output: { \"answer\" : 42 , \"hello\" : \"world\" }","title":"Examples"},{"location":"api/operator_literal_json/#version-history","text":"Added in version 1.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"Version history"},{"location":"api/operator_literal_json_pointer/","text":"nlohmann:: operator\"\"_json_pointer \u00b6 json_pointer operator \"\" _json_pointer ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json_pointer ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details. Parameters \u00b6 s (in) a string representation of a JSON Pointer n (in) length of string s Return value \u00b6 json_pointer value parsed from s Exceptions \u00b6 The function can throw anything that json_pointer::json_pointer would throw. Complexity \u00b6 Linear. Examples \u00b6 Example The following code shows how to create JSON Pointers from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; auto val = j [ \"/hello\" _json_pointer ]; std :: cout << std :: setw ( 2 ) << val << '\\n' ; } Output: \"world\" See also \u00b6 json_pointer - type to represent JSON Pointers Version history \u00b6 Added in version 2.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"operator\"\"_json_pointer"},{"location":"api/operator_literal_json_pointer/#nlohmannoperator_json_pointer","text":"json_pointer operator \"\" _json_pointer ( const char * s , std :: size_t n ); This operator implements a user-defined string literal for JSON Pointers. It can be used by adding _json_pointer to a string literal and returns a json_pointer object if no parse error occurred. It is recommended to bring the operator into scope using any of the following lines: using nlohmann :: literals :: operator \"\" _json_pointer ; using namespace nlohmann :: literals ; using namespace nlohmann :: json_literals ; using namespace nlohmann :: literals :: json_literals ; using namespace nlohmann ; This is suggested to ease migration to the next major version release of the library. See 'JSON_USE_GLOBAL_UDLS` for details.","title":"nlohmann::operator\"\"_json_pointer"},{"location":"api/operator_literal_json_pointer/#parameters","text":"s (in) a string representation of a JSON Pointer n (in) length of string s","title":"Parameters"},{"location":"api/operator_literal_json_pointer/#return-value","text":"json_pointer value parsed from s","title":"Return value"},{"location":"api/operator_literal_json_pointer/#exceptions","text":"The function can throw anything that json_pointer::json_pointer would throw.","title":"Exceptions"},{"location":"api/operator_literal_json_pointer/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/operator_literal_json_pointer/#examples","text":"Example The following code shows how to create JSON Pointers from string literals. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { json j = R \" ( {\"hello\": \"world\", \"answer\": 42} ) \" _json ; auto val = j [ \"/hello\" _json_pointer ]; std :: cout << std :: setw ( 2 ) << val << '\\n' ; } Output: \"world\"","title":"Examples"},{"location":"api/operator_literal_json_pointer/#see-also","text":"json_pointer - type to represent JSON Pointers","title":"See also"},{"location":"api/operator_literal_json_pointer/#version-history","text":"Added in version 2.0.0. Moved to namespace nlohmann::literals::json_literals in 3.11.0.","title":"Version history"},{"location":"api/operator_ltlt/","text":"nlohmann:: operator<<(basic_json), nlohmann:: operator<<(json_pointer) \u00b6 std :: ostream & operator << ( std :: ostream & o , const basic_json & j ); // (1) std :: ostream & operator << ( std :: ostream & o , const json_pointer & ptr ); // (2) 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. Parameters \u00b6 o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write Return value \u00b6 the stream o Exceptions \u00b6 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. None. Complexity \u00b6 Linear. Notes \u00b6 Deprecation Function std :: ostream & operator << ( std :: ostream & o , const basic_json & j ) replaces function std :: ostream & operator >> ( const basic_json & j , std :: ostream & o ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o ; with o << j ; . Examples \u00b6 Example: (1) serialize JSON value to stream The example below shows the serialization with different parameters to width to adjust the indentation level. #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // serialize without indentation std :: cout << j_object << \" \\n\\n \" ; std :: cout << j_array << \" \\n\\n \" ; // serialize with indentation std :: cout << std :: setw ( 4 ) << j_object << \" \\n\\n \" ; std :: cout << std :: setw ( 2 ) << j_array << \" \\n\\n \" ; std :: cout << std :: setw ( 1 ) << std :: setfill ( '\\t' ) << j_object << \" \\n\\n \" ; } Output: { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } Example: (2) write JSON pointer to stream The example below shows how to write a JSON pointer to a stream. #include #include using json = nlohmann :: json ; int main () { // create JSON poiner json :: json_pointer ptr ( \"/foo/bar/baz\" ); // write string representation to stream std :: cout << ptr << std :: endl ; } Output: / f oo/bar/baz Version history \u00b6 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. Added in version 3.11.0.","title":"operator<<(json_pointer)"},{"location":"api/operator_ltlt/#nlohmannoperatorbasic_json-nlohmannoperatorjson_pointer","text":"std :: ostream & operator << ( std :: ostream & o , const basic_json & j ); // (1) std :: ostream & operator << ( std :: ostream & o , const json_pointer & ptr ); // (2) 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.","title":"nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)"},{"location":"api/operator_ltlt/#parameters","text":"o (in, out) stream to write to j (in) JSON value to serialize ptr (in) JSON pointer to write","title":"Parameters"},{"location":"api/operator_ltlt/#return-value","text":"the stream o","title":"Return value"},{"location":"api/operator_ltlt/#exceptions","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. None.","title":"Exceptions"},{"location":"api/operator_ltlt/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/operator_ltlt/#notes","text":"Deprecation Function std :: ostream & operator << ( std :: ostream & o , const basic_json & j ) replaces function std :: ostream & operator >> ( const basic_json & j , std :: ostream & o ) which has been deprecated in version 3.0.0. It will be removed in version 4.0.0. Please replace calls like j >> o ; with o << j ; .","title":"Notes"},{"location":"api/operator_ltlt/#examples","text":"Example: (1) serialize JSON value to stream The example below shows the serialization with different parameters to width to adjust the indentation level. #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // serialize without indentation std :: cout << j_object << \" \\n\\n \" ; std :: cout << j_array << \" \\n\\n \" ; // serialize with indentation std :: cout << std :: setw ( 4 ) << j_object << \" \\n\\n \" ; std :: cout << std :: setw ( 2 ) << j_array << \" \\n\\n \" ; std :: cout << std :: setw ( 1 ) << std :: setfill ( '\\t' ) << j_object << \" \\n\\n \" ; } Output: { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 4 , 8 , 16 ] { \"one\" : 1 , \"two\" : 2 } Example: (2) write JSON pointer to stream The example below shows how to write a JSON pointer to a stream. #include #include using json = nlohmann :: json ; int main () { // create JSON poiner json :: json_pointer ptr ( \"/foo/bar/baz\" ); // write string representation to stream std :: cout << ptr << std :: endl ; } Output: / f oo/bar/baz","title":"Examples"},{"location":"api/operator_ltlt/#version-history","text":"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. Added in version 3.11.0.","title":"Version history"},{"location":"api/ordered_json/","text":"nlohmann:: ordered_json \u00b6 using ordered_json = basic_json < ordered_map > ; This type preserves the insertion order of object keys. Examples \u00b6 Example The example below demonstrates how ordered_json preserves the insertion order of object keys. #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } See also \u00b6 ordered_map Object Order Version history \u00b6 Since version 3.9.0.","title":"ordered_json"},{"location":"api/ordered_json/#nlohmannordered_json","text":"using ordered_json = basic_json < ordered_map > ; This type preserves the insertion order of object keys.","title":"nlohmann::ordered_json"},{"location":"api/ordered_json/#examples","text":"Example The example below demonstrates how ordered_json preserves the insertion order of object keys. #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 }","title":"Examples"},{"location":"api/ordered_json/#see-also","text":"ordered_map Object Order","title":"See also"},{"location":"api/ordered_json/#version-history","text":"Since version 3.9.0.","title":"Version history"},{"location":"api/ordered_map/","text":"nlohmann:: ordered_map \u00b6 template < class Key , class T , class IgnoredLess = std :: less < Key > , class Allocator = std :: allocator < std :: pair < const Key , T >>> struct ordered_map : std :: vector < std :: pair < const Key , T > , Allocator > ; A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json ( nlohmann::basic_json ). Template parameters \u00b6 Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std :: map ) Allocator allocator type Member types \u00b6 key_type - key type ( Key ) mapped_type - mapped type ( T ) Container - base container type ( std :: vector < std :: pair < const Key , T > , Allocator > ) iterator const_iterator size_type value_type key_compare - key comparison function std :: equal_to < Key > // until C++14 std :: equal_to <> // since C++14 Member functions \u00b6 (constructor) (destructor) emplace operator[] at erase count find insert Examples \u00b6 Example The example shows the different behavior of std::map and nlohmann::ordered_map . #include #include // simple output function template < typename Map > void output ( const char * prefix , const Map & m ) { std :: cout << prefix << \" = { \" ; for ( auto & element : m ) { std :: cout << element . first << \":\" << element . second << ' ' ; } std :: cout << \"}\" << std :: endl ; } int main () { // create and fill two maps nlohmann :: ordered_map < std :: string , std :: string > m_ordered ; m_ordered [ \"one\" ] = \"eins\" ; m_ordered [ \"two\" ] = \"zwei\" ; m_ordered [ \"three\" ] = \"drei\" ; std :: map < std :: string , std :: string > m_std ; m_std [ \"one\" ] = \"eins\" ; m_std [ \"two\" ] = \"zwei\" ; m_std [ \"three\" ] = \"drei\" ; // output: m_ordered is ordered by insertion order, m_std is ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); // erase and re-add \"one\" key m_ordered . erase ( \"one\" ); m_ordered [ \"one\" ] = \"eins\" ; m_std . erase ( \"one\" ); m_std [ \"one\" ] = \"eins\" ; // output: m_ordered shows newly added key at the end; m_std is again ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); } Output: m_ordered = { o ne : ei ns t wo : zwei t hree : drei } m_s t d = { o ne : ei ns t hree : drei t wo : zwei } m_ordered = { t wo : zwei t hree : drei o ne : ei ns } m_s t d = { o ne : ei ns t hree : drei t wo : zwei } See also \u00b6 ordered_json Version history \u00b6 Added in version 3.9.0 to implement nlohmann::ordered_json . Added key_compare member in version 3.11.0.","title":"ordered_map"},{"location":"api/ordered_map/#nlohmannordered_map","text":"template < class Key , class T , class IgnoredLess = std :: less < Key > , class Allocator = std :: allocator < std :: pair < const Key , T >>> struct ordered_map : std :: vector < std :: pair < const Key , T > , Allocator > ; A minimal map-like container that preserves insertion order for use within nlohmann::ordered_json ( nlohmann::basic_json ).","title":"nlohmann::ordered_map"},{"location":"api/ordered_map/#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","title":"Template parameters"},{"location":"api/ordered_map/#member-types","text":"key_type - key type ( Key ) mapped_type - mapped type ( T ) Container - base container type ( std :: vector < std :: pair < const Key , T > , Allocator > ) iterator const_iterator size_type value_type key_compare - key comparison function std :: equal_to < Key > // until C++14 std :: equal_to <> // since C++14","title":"Member types"},{"location":"api/ordered_map/#member-functions","text":"(constructor) (destructor) emplace operator[] at erase count find insert","title":"Member functions"},{"location":"api/ordered_map/#examples","text":"Example The example shows the different behavior of std::map and nlohmann::ordered_map . #include #include // simple output function template < typename Map > void output ( const char * prefix , const Map & m ) { std :: cout << prefix << \" = { \" ; for ( auto & element : m ) { std :: cout << element . first << \":\" << element . second << ' ' ; } std :: cout << \"}\" << std :: endl ; } int main () { // create and fill two maps nlohmann :: ordered_map < std :: string , std :: string > m_ordered ; m_ordered [ \"one\" ] = \"eins\" ; m_ordered [ \"two\" ] = \"zwei\" ; m_ordered [ \"three\" ] = \"drei\" ; std :: map < std :: string , std :: string > m_std ; m_std [ \"one\" ] = \"eins\" ; m_std [ \"two\" ] = \"zwei\" ; m_std [ \"three\" ] = \"drei\" ; // output: m_ordered is ordered by insertion order, m_std is ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); // erase and re-add \"one\" key m_ordered . erase ( \"one\" ); m_ordered [ \"one\" ] = \"eins\" ; m_std . erase ( \"one\" ); m_std [ \"one\" ] = \"eins\" ; // output: m_ordered shows newly added key at the end; m_std is again ordered by key output ( \"m_ordered\" , m_ordered ); output ( \"m_std\" , m_std ); } Output: m_ordered = { o ne : ei ns t wo : zwei t hree : drei } m_s t d = { o ne : ei ns t hree : drei t wo : zwei } m_ordered = { t wo : zwei t hree : drei o ne : ei ns } m_s t d = { o ne : ei ns t hree : drei t wo : zwei }","title":"Examples"},{"location":"api/ordered_map/#see-also","text":"ordered_json","title":"See also"},{"location":"api/ordered_map/#version-history","text":"Added in version 3.9.0 to implement nlohmann::ordered_json . Added key_compare member in version 3.11.0.","title":"Version history"},{"location":"api/adl_serializer/","text":"nlohmann:: adl_serializer \u00b6 template < typename , typename > struct adl_serializer ; Serializer that uses ADL ( Argument-Dependent Lookup ) to choose to_json / from_json functions from the types' namespaces. It is implemented similar to template < typename ValueType > struct adl_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // calls the \"to_json\" method in T's namespace } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing, but with the \"from_json\" method } }; Member functions \u00b6 from_json - convert a JSON value to any value type to_json - convert any value type to a JSON value Version history \u00b6 Added in version 2.1.0.","title":"Overview"},{"location":"api/adl_serializer/#nlohmannadl_serializer","text":"template < typename , typename > struct adl_serializer ; Serializer that uses ADL ( Argument-Dependent Lookup ) to choose to_json / from_json functions from the types' namespaces. It is implemented similar to template < typename ValueType > struct adl_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // calls the \"to_json\" method in T's namespace } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing, but with the \"from_json\" method } };","title":"nlohmann::adl_serializer"},{"location":"api/adl_serializer/#member-functions","text":"from_json - convert a JSON value to any value type to_json - convert any value type to a JSON value","title":"Member functions"},{"location":"api/adl_serializer/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/adl_serializer/from_json/","text":"nlohmann::adl_serializer:: from_json \u00b6 // (1) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j , TargetType & val ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ), void ()) // (2) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {}))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {})) 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. Parameters \u00b6 j (in) JSON value to read from val (out) value to write to Return value \u00b6 Copy of the JSON value, converted to ValueType Examples \u00b6 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() is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace 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 #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace See also \u00b6 to_json Version history \u00b6 Added in version 2.1.0.","title":"from_json"},{"location":"api/adl_serializer/from_json/#nlohmannadl_serializerfrom_json","text":"// (1) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j , TargetType & val ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), val ), void ()) // (2) template < typename BasicJsonType , typename TargetType = ValueType > static auto from_json ( BasicJsonType && j ) noexcept ( noexcept ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {}))) -> decltype ( :: nlohmann :: from_json ( std :: forward < BasicJsonType > ( j ), detail :: identity_tag < TargetType > {})) 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.","title":"nlohmann::adl_serializer::from_json"},{"location":"api/adl_serializer/from_json/#parameters","text":"j (in) JSON value to read from val (out) value to write to","title":"Parameters"},{"location":"api/adl_serializer/from_json/#return-value","text":"Copy of the JSON value, converted to ValueType","title":"Return value"},{"location":"api/adl_serializer/from_json/#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() is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace 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 #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace","title":"Examples"},{"location":"api/adl_serializer/from_json/#see-also","text":"to_json","title":"See also"},{"location":"api/adl_serializer/from_json/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/adl_serializer/to_json/","text":"nlohmann::adl_serializer:: to_json \u00b6 template < typename BasicJsonType , typename TargetType = ValueType > static auto to_json ( BasicJsonType & j , TargetType && val ) noexcept ( noexcept ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )))) -> decltype ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )), void ()) This function is usually called by the constructors of the basic_json class. Parameters \u00b6 j (out) JSON value to write to val (in) value to read from Examples \u00b6 Example The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; json j = p ; std :: cout << j << std :: endl ; } Output: { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } See also \u00b6 from_json Version history \u00b6 Added in version 2.1.0.","title":"to_json"},{"location":"api/adl_serializer/to_json/#nlohmannadl_serializerto_json","text":"template < typename BasicJsonType , typename TargetType = ValueType > static auto to_json ( BasicJsonType & j , TargetType && val ) noexcept ( noexcept ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )))) -> decltype ( :: nlohmann :: to_json ( j , std :: forward < TargetType > ( val )), void ()) This function is usually called by the constructors of the basic_json class.","title":"nlohmann::adl_serializer::to_json"},{"location":"api/adl_serializer/to_json/#parameters","text":"j (out) JSON value to write to val (in) value to read from","title":"Parameters"},{"location":"api/adl_serializer/to_json/#examples","text":"Example The example below shows how a to_json function can be implemented for a user-defined type. This function is called by the adl_serializer when the constructor basic_json(ns::person) is called. #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; json j = p ; std :: cout << j << std :: endl ; } Output: { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" }","title":"Examples"},{"location":"api/adl_serializer/to_json/#see-also","text":"from_json","title":"See also"},{"location":"api/adl_serializer/to_json/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/basic_json/","text":"nlohmann:: basic_json \u00b6 Defined in header template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > , class CustomBaseClass = void > class basic_json ; Template parameters \u00b6 Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t Specializations \u00b6 json - default specialization ordered_json - specialization that maintains the insertion order of object keys Iterator invalidation \u00b6 Todo Requirements \u00b6 The class satisfies the following concept requirements: Basic \u00b6 DefaultConstructible : JSON values can be default constructed. The result will be a JSON null value. MoveConstructible : A JSON value can be constructed from an rvalue argument. CopyConstructible : A JSON value can be copy-constructed from an lvalue expression. MoveAssignable : A JSON value can be assigned from an rvalue argument. CopyAssignable : A JSON value can be copy-assigned from an lvalue expression. Destructible : JSON values can be destructed. Layout \u00b6 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. Library-wide \u00b6 EqualityComparable : JSON values can be compared with == , see operator== . LessThanComparable : JSON values can be compared with < , see operator< . Swappable : Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function swap . NullablePointer : JSON values can be compared against std::nullptr_t objects which are used to model the null value. Container \u00b6 Container : JSON values can be used like STL containers and provide iterator access. ReversibleContainer : JSON values can be used like STL containers and provide reverse iterator access. Member types \u00b6 adl_serializer - the default serializer value_t - the JSON type enumeration json_pointer - JSON Pointer implementation json_serializer - type of the serializer to for conversions from/to JSON error_handler_t - type to choose behavior on decoding errors cbor_tag_handler_t - type to choose how to handle CBOR tags initializer_list_t - type for initializer lists of basic_json values input_format_t - type to choose the format to parse json_sax_t - type for SAX events Exceptions \u00b6 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 Container types \u00b6 Type Definition value_type basic_json reference value_type & const_reference const value_type & difference_type std :: ptrdiff_t size_type std :: size_t allocator_type AllocatorType < basic_json > pointer std :: allocator_traits < allocator_type >:: pointer const_pointer std :: allocator_traits < allocator_type >:: const_pointer iterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iterator const_reverse_iterator reverse iterator, derived from const_iterator iteration_proxy helper type for items function JSON value data types \u00b6 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) number_integer_t - type for numbers (integer) number_unsigned_t - type for numbers (unsigned) object_comparator_t - comparator for objects object_t - type for objects string_t - type for strings Parser callback \u00b6 parse_event_t - parser event types parser_callback_t - per-element parser callback type Member functions \u00b6 (constructor) (destructor) operator= - copy assignment array ( static ) - explicitly create an array binary ( static ) - explicitly create a binary array object ( static ) - explicitly create an object Object inspection \u00b6 Functions to inspect the type of a JSON value. type - return the type of the JSON value operator value_t - return the type of the JSON value type_name - return the type as string is_primitive - return whether type is primitive is_structured - return whether type is structured is_null - return whether value is null is_boolean - return whether value is a boolean is_number - return whether value is a number is_number_integer - return whether value is an integer number is_number_unsigned - return whether value is an unsigned integer number is_number_float - return whether value is a floating-point number is_object - return whether value is an object is_array - return whether value is an array is_string - return whether value is a string is_binary - return whether value is a binary array is_discarded - return whether value is discarded Value access \u00b6 Direct access to the stored value of a JSON value. get - get a value get_to - get a value and write it to a destination get_ptr - get a pointer value get_ref - get a reference value operator ValueType - get a value get_binary - get a binary value Element access \u00b6 Access to the JSON value at - access specified element with bounds checking operator[] - access specified element value - access specified object element with default value front - access the first element back - access the last element Lookup \u00b6 find - find an element in a JSON object count - returns the number of occurrences of a key in a JSON object contains - check the existence of an element in a JSON object Iterators \u00b6 begin - returns an iterator to the first element cbegin - returns a const iterator to the first element end - returns an iterator to one past the last element cend - returns a const iterator to one past the last element rbegin - returns an iterator to the reverse-beginning rend - returns an iterator to the reverse-end crbegin - returns a const iterator to the reverse-beginning crend - returns a const iterator to the reverse-end items - wrapper to access iterator member functions in range-based for Capacity \u00b6 empty - checks whether the container is empty size - returns the number of elements max_size - returns the maximum possible number of elements Modifiers \u00b6 clear - clears the contents push_back - add a value to an array/object operator+= - add a value to an array/object emplace_back - add a value to an array emplace - add a value to an object if key does not exist erase - remove elements insert - inserts elements update - updates a JSON object from another object, overwriting existing keys swap - exchanges the values Lexicographical comparison operators \u00b6 operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator> - comparison: greater than operator<= - comparison: less than or equal operator>= - comparison: greater than or equal operator<=> - comparison: 3-way Serialization / Dumping \u00b6 dump - serialization Deserialization / Parsing \u00b6 parse ( static ) - deserialize from a compatible input accept ( static ) - check if the input is valid JSON sax_parse ( static ) - generate SAX events JSON Pointer functions \u00b6 flatten - return flattened JSON value unflatten - unflatten a previously flattened JSON value JSON Patch functions \u00b6 patch - applies a JSON patch patch_inplace - applies a JSON patch in place diff ( static ) - creates a diff as a JSON patch JSON Merge Patch functions \u00b6 merge_patch - applies a JSON Merge Patch Static functions \u00b6 meta - returns version information on the library get_allocator - returns the allocator associated with the container Binary formats \u00b6 from_bjdata ( static ) - create a JSON value from an input in BJData format from_bson ( static ) - create a JSON value from an input in BSON format from_cbor ( static ) - create a JSON value from an input in CBOR format from_msgpack ( static ) - create a JSON value from an input in MessagePack format from_ubjson ( static ) - create a JSON value from an input in UBJSON format to_bjdata ( static ) - create a BJData serialization of a given JSON value to_bson ( static ) - create a BSON serialization of a given JSON value to_cbor ( static ) - create a CBOR serialization of a given JSON value to_msgpack ( static ) - create a MessagePack serialization of a given JSON value to_ubjson ( static ) - create a UBJSON serialization of a given JSON value Non-member functions \u00b6 operator<<(std::ostream&) - serialize to stream operator>>(std::istream&) - deserialize from stream to_string - user-defined to_string function for JSON values Literals \u00b6 operator\"\"_json - user-defined string literal for JSON values Helper classes \u00b6 std::hash - return a hash value for a JSON object std::swap - exchanges the values of two JSON objects Examples \u00b6 Example The example shows how the library is used. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 } See also \u00b6 RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format Version history \u00b6 Added in version 1.0.0.","title":"Overview"},{"location":"api/basic_json/#nlohmannbasic_json","text":"Defined in header template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > , class CustomBaseClass = void > class basic_json ;","title":"nlohmann::basic_json"},{"location":"api/basic_json/#template-parameters","text":"Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t","title":"Template parameters"},{"location":"api/basic_json/#specializations","text":"json - default specialization ordered_json - specialization that maintains the insertion order of object keys","title":"Specializations"},{"location":"api/basic_json/#iterator-invalidation","text":"Todo","title":"Iterator invalidation"},{"location":"api/basic_json/#requirements","text":"The class satisfies the following concept requirements:","title":"Requirements"},{"location":"api/basic_json/#basic","text":"DefaultConstructible : JSON values can be default constructed. The result will be a JSON null value. MoveConstructible : A JSON value can be constructed from an rvalue argument. CopyConstructible : A JSON value can be copy-constructed from an lvalue expression. MoveAssignable : A JSON value can be assigned from an rvalue argument. CopyAssignable : A JSON value can be copy-assigned from an lvalue expression. Destructible : JSON values can be destructed.","title":"Basic"},{"location":"api/basic_json/#layout","text":"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.","title":"Layout"},{"location":"api/basic_json/#library-wide","text":"EqualityComparable : JSON values can be compared with == , see operator== . LessThanComparable : JSON values can be compared with < , see operator< . Swappable : Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function swap . NullablePointer : JSON values can be compared against std::nullptr_t objects which are used to model the null value.","title":"Library-wide"},{"location":"api/basic_json/#container","text":"Container : JSON values can be used like STL containers and provide iterator access. ReversibleContainer : JSON values can be used like STL containers and provide reverse iterator access.","title":"Container"},{"location":"api/basic_json/#member-types","text":"adl_serializer - the default serializer value_t - the JSON type enumeration json_pointer - JSON Pointer implementation json_serializer - type of the serializer to for conversions from/to JSON error_handler_t - type to choose behavior on decoding errors cbor_tag_handler_t - type to choose how to handle CBOR tags initializer_list_t - type for initializer lists of basic_json values input_format_t - type to choose the format to parse json_sax_t - type for SAX events","title":"Member types"},{"location":"api/basic_json/#exceptions","text":"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","title":"Exceptions"},{"location":"api/basic_json/#container-types","text":"Type Definition value_type basic_json reference value_type & const_reference const value_type & difference_type std :: ptrdiff_t size_type std :: size_t allocator_type AllocatorType < basic_json > pointer std :: allocator_traits < allocator_type >:: pointer const_pointer std :: allocator_traits < allocator_type >:: const_pointer iterator LegacyBidirectionalIterator const_iterator constant LegacyBidirectionalIterator reverse_iterator reverse iterator, derived from iterator const_reverse_iterator reverse iterator, derived from const_iterator iteration_proxy helper type for items function","title":"Container types"},{"location":"api/basic_json/#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) number_integer_t - type for numbers (integer) number_unsigned_t - type for numbers (unsigned) object_comparator_t - comparator for objects object_t - type for objects string_t - type for strings","title":"JSON value data types"},{"location":"api/basic_json/#parser-callback","text":"parse_event_t - parser event types parser_callback_t - per-element parser callback type","title":"Parser callback"},{"location":"api/basic_json/#member-functions","text":"(constructor) (destructor) operator= - copy assignment array ( static ) - explicitly create an array binary ( static ) - explicitly create a binary array object ( static ) - explicitly create an object","title":"Member functions"},{"location":"api/basic_json/#object-inspection","text":"Functions to inspect the type of a JSON value. type - return the type of the JSON value operator value_t - return the type of the JSON value type_name - return the type as string is_primitive - return whether type is primitive is_structured - return whether type is structured is_null - return whether value is null is_boolean - return whether value is a boolean is_number - return whether value is a number is_number_integer - return whether value is an integer number is_number_unsigned - return whether value is an unsigned integer number is_number_float - return whether value is a floating-point number is_object - return whether value is an object is_array - return whether value is an array is_string - return whether value is a string is_binary - return whether value is a binary array is_discarded - return whether value is discarded","title":"Object inspection"},{"location":"api/basic_json/#value-access","text":"Direct access to the stored value of a JSON value. get - get a value get_to - get a value and write it to a destination get_ptr - get a pointer value get_ref - get a reference value operator ValueType - get a value get_binary - get a binary value","title":"Value access"},{"location":"api/basic_json/#element-access","text":"Access to the JSON value at - access specified element with bounds checking operator[] - access specified element value - access specified object element with default value front - access the first element back - access the last element","title":"Element access"},{"location":"api/basic_json/#lookup","text":"find - find an element in a JSON object count - returns the number of occurrences of a key in a JSON object contains - check the existence of an element in a JSON object","title":"Lookup"},{"location":"api/basic_json/#iterators","text":"begin - returns an iterator to the first element cbegin - returns a const iterator to the first element end - returns an iterator to one past the last element cend - returns a const iterator to one past the last element rbegin - returns an iterator to the reverse-beginning rend - returns an iterator to the reverse-end crbegin - returns a const iterator to the reverse-beginning crend - returns a const iterator to the reverse-end items - wrapper to access iterator member functions in range-based for","title":"Iterators"},{"location":"api/basic_json/#capacity","text":"empty - checks whether the container is empty size - returns the number of elements max_size - returns the maximum possible number of elements","title":"Capacity"},{"location":"api/basic_json/#modifiers","text":"clear - clears the contents push_back - add a value to an array/object operator+= - add a value to an array/object emplace_back - add a value to an array emplace - add a value to an object if key does not exist erase - remove elements insert - inserts elements update - updates a JSON object from another object, overwriting existing keys swap - exchanges the values","title":"Modifiers"},{"location":"api/basic_json/#lexicographical-comparison-operators","text":"operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator> - comparison: greater than operator<= - comparison: less than or equal operator>= - comparison: greater than or equal operator<=> - comparison: 3-way","title":"Lexicographical comparison operators"},{"location":"api/basic_json/#serialization-dumping","text":"dump - serialization","title":"Serialization / Dumping"},{"location":"api/basic_json/#deserialization-parsing","text":"parse ( static ) - deserialize from a compatible input accept ( static ) - check if the input is valid JSON sax_parse ( static ) - generate SAX events","title":"Deserialization / Parsing"},{"location":"api/basic_json/#json-pointer-functions","text":"flatten - return flattened JSON value unflatten - unflatten a previously flattened JSON value","title":"JSON Pointer functions"},{"location":"api/basic_json/#json-patch-functions","text":"patch - applies a JSON patch patch_inplace - applies a JSON patch in place diff ( static ) - creates a diff as a JSON patch","title":"JSON Patch functions"},{"location":"api/basic_json/#json-merge-patch-functions","text":"merge_patch - applies a JSON Merge Patch","title":"JSON Merge Patch functions"},{"location":"api/basic_json/#static-functions","text":"meta - returns version information on the library get_allocator - returns the allocator associated with the container","title":"Static functions"},{"location":"api/basic_json/#binary-formats","text":"from_bjdata ( static ) - create a JSON value from an input in BJData format from_bson ( static ) - create a JSON value from an input in BSON format from_cbor ( static ) - create a JSON value from an input in CBOR format from_msgpack ( static ) - create a JSON value from an input in MessagePack format from_ubjson ( static ) - create a JSON value from an input in UBJSON format to_bjdata ( static ) - create a BJData serialization of a given JSON value to_bson ( static ) - create a BSON serialization of a given JSON value to_cbor ( static ) - create a CBOR serialization of a given JSON value to_msgpack ( static ) - create a MessagePack serialization of a given JSON value to_ubjson ( static ) - create a UBJSON serialization of a given JSON value","title":"Binary formats"},{"location":"api/basic_json/#non-member-functions","text":"operator<<(std::ostream&) - serialize to stream operator>>(std::istream&) - deserialize from stream to_string - user-defined to_string function for JSON values","title":"Non-member functions"},{"location":"api/basic_json/#literals","text":"operator\"\"_json - user-defined string literal for JSON values","title":"Literals"},{"location":"api/basic_json/#helper-classes","text":"std::hash - return a hash value for a JSON object std::swap - exchanges the values of two JSON objects","title":"Helper classes"},{"location":"api/basic_json/#examples","text":"Example The example shows how the library is used. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // add new values j [ \"new\" ][ \"key\" ][ \"value\" ] = { \"another\" , \"list\" }; // count elements auto s = j . size (); j [ \"size\" ] = s ; // pretty print with indent of 4 spaces std :: cout << std :: setw ( 4 ) << j << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"new\" : { \"key\" : { \"value\" : [ \"another\" , \"list\" ] } }, \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 , \"size\" : 8 }","title":"Examples"},{"location":"api/basic_json/#see-also","text":"RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format","title":"See also"},{"location":"api/basic_json/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/accept/","text":"nlohmann::basic_json:: accept \u00b6 // (1) template < typename InputType > static bool accept ( InputType && i , const bool ignore_comments = false ); // (2) template < typename IteratorType > static bool accept ( IteratorType first , IteratorType last , const bool ignore_comments = false ); Checks whether the input is valid JSON. Reads from a compatible input. Reads from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information. Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len Parameters \u00b6 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 Return value \u00b6 Whether the input is valid JSON. Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the length of the input. The parser is a predictive LL(1) parser. Notes \u00b6 (1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion . Examples \u00b6 Example The example below demonstrates the accept() function reading from a string. #include #include #include using json = nlohmann :: json ; int main () { // a valid JSON text auto valid_text = R \" ( { \"numbers\": [1, 2, 3] } ) \" ; // an invalid JSON text auto invalid_text = R \" ( { \"strings\": [\"extra\", \"comma\", ] } ) \" ; std :: cout << std :: boolalpha << json :: accept ( valid_text ) << ' ' << json :: accept ( invalid_text ) << '\\n' ; } Output: true false See also \u00b6 parse - deserialize from a compatible input operator>> - deserialize from stream Version history \u00b6 Added in version 3.0.0. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"accept"},{"location":"api/basic_json/accept/#nlohmannbasic_jsonaccept","text":"// (1) template < typename InputType > static bool accept ( InputType && i , const bool ignore_comments = false ); // (2) template < typename IteratorType > static bool accept ( IteratorType first , IteratorType last , const bool ignore_comments = false ); Checks whether the input is valid JSON. Reads from a compatible input. Reads from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. Unlike the parse function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.","title":"nlohmann::basic_json::accept"},{"location":"api/basic_json/accept/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len","title":"Template parameters"},{"location":"api/basic_json/accept/#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","title":"Parameters"},{"location":"api/basic_json/accept/#return-value","text":"Whether the input is valid JSON.","title":"Return value"},{"location":"api/basic_json/accept/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/accept/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser.","title":"Complexity"},{"location":"api/basic_json/accept/#notes","text":"(1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion .","title":"Notes"},{"location":"api/basic_json/accept/#examples","text":"Example The example below demonstrates the accept() function reading from a string. #include #include #include using json = nlohmann :: json ; int main () { // a valid JSON text auto valid_text = R \" ( { \"numbers\": [1, 2, 3] } ) \" ; // an invalid JSON text auto invalid_text = R \" ( { \"strings\": [\"extra\", \"comma\", ] } ) \" ; std :: cout << std :: boolalpha << json :: accept ( valid_text ) << ' ' << json :: accept ( invalid_text ) << '\\n' ; } Output: true false","title":"Examples"},{"location":"api/basic_json/accept/#see-also","text":"parse - deserialize from a compatible input operator>> - deserialize from stream","title":"See also"},{"location":"api/basic_json/accept/#version-history","text":"Added in version 3.0.0. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"Version history"},{"location":"api/basic_json/array/","text":"nlohmann::basic_json:: array \u00b6 static basic_json array ( initializer_list_t init = {}); 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. Parameters \u00b6 init (in) initializer list with JSON values to create an array from (optional) Return value \u00b6 JSON array value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of init . Notes \u00b6 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 Examples \u00b6 Example The following code shows an example for the array function. #include #include using json = nlohmann :: json ; int main () { // create JSON arrays json j_no_init_list = json :: array (); json j_empty_init_list = json :: array ({}); json j_nonempty_init_list = json :: array ({ 1 , 2 , 3 , 4 }); json j_list_of_pairs = json :: array ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON arrays std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_nonempty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; } Output: [] [] [ 1 , 2 , 3 , 4 ] [[ \"one\" , 1 ],[ \"two\" , 2 ]] See also \u00b6 basic_json(initializer_list_t) - create a JSON value from an initializer list object - create a JSON object value from an initializer list Version history \u00b6 Added in version 1.0.0.","title":"array"},{"location":"api/basic_json/array/#nlohmannbasic_jsonarray","text":"static basic_json array ( initializer_list_t init = {}); 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.","title":"nlohmann::basic_json::array"},{"location":"api/basic_json/array/#parameters","text":"init (in) initializer list with JSON values to create an array from (optional)","title":"Parameters"},{"location":"api/basic_json/array/#return-value","text":"JSON array value","title":"Return value"},{"location":"api/basic_json/array/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/array/#complexity","text":"Linear in the size of init .","title":"Complexity"},{"location":"api/basic_json/array/#notes","text":"This function is only needed to express two edge cases that cannot be realized with the initializer list constructor ( basic_json(initializer_list_t, bool, value_t) ). These cases are: 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","title":"Notes"},{"location":"api/basic_json/array/#examples","text":"Example The following code shows an example for the array function. #include #include using json = nlohmann :: json ; int main () { // create JSON arrays json j_no_init_list = json :: array (); json j_empty_init_list = json :: array ({}); json j_nonempty_init_list = json :: array ({ 1 , 2 , 3 , 4 }); json j_list_of_pairs = json :: array ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON arrays std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_nonempty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; } Output: [] [] [ 1 , 2 , 3 , 4 ] [[ \"one\" , 1 ],[ \"two\" , 2 ]]","title":"Examples"},{"location":"api/basic_json/array/#see-also","text":"basic_json(initializer_list_t) - create a JSON value from an initializer list object - create a JSON object value from an initializer list","title":"See also"},{"location":"api/basic_json/array/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/array_t/","text":"nlohmann::basic_json:: array_t \u00b6 using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; 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. Template parameters \u00b6 ArrayType container type to store arrays (e.g., std::vector or std::list ) AllocatorType the allocator to use for objects (e.g., std::allocator ) Notes \u00b6 Default type \u00b6 With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type > Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array. Storage \u00b6 Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t * must be dereferenced. Examples \u00b6 Example The following code shows that array_t is by default, a typedef to std :: vector < nlohmann :: json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: vector < json > , json :: array_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"array_t"},{"location":"api/basic_json/array_t/#nlohmannbasic_jsonarray_t","text":"using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; 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.","title":"nlohmann::basic_json::array_t"},{"location":"api/basic_json/array_t/#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 )","title":"Template parameters"},{"location":"api/basic_json/array_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/array_t/#default-type","text":"With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type >","title":"Default type"},{"location":"api/basic_json/array_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.","title":"Limits"},{"location":"api/basic_json/array_t/#storage","text":"Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t * must be dereferenced.","title":"Storage"},{"location":"api/basic_json/array_t/#examples","text":"Example The following code shows that array_t is by default, a typedef to std :: vector < nlohmann :: json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: vector < json > , json :: array_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/array_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/at/","text":"nlohmann::basic_json:: at \u00b6 // (1) reference at ( size_type idx ); const_reference at ( size_type idx ) const ; // (2) reference at ( const typename object_t :: key_type & key ); const_reference at ( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference at ( KeyType && key ); template < typename KeyType > const_reference at ( KeyType && key ) const ; // (4) reference at ( const json_pointer & ptr ); const_reference at ( const json_pointer & ptr ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 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 Return value \u00b6 reference to the element at index idx reference to the element at key key reference to the element at key key reference to the element pointed to by ptr Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below. Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size() . See example below. 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. Complexity \u00b6 Constant. Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container. Examples \u00b6 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 #include using json = nlohmann :: json ; int main () { // create JSON array json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // change element at index 1 (second element) to \"second\" array . at ( 1 ) = \"second\" ; // output changed array std :: cout << array << '\\n' ; // exception type_error.304 try { // use at() on a non-array type json str = \"I am a string\" ; str . at ( 0 ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write beyond the array limit array . at ( 5 ) = \"sixth\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ \"first\" , \"second\" , \"third\" , \"fourth\" ] [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge 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 #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // exception type_error.304 try { // use at() on a non-array type const json str = \"I am a string\" ; std :: cout << str . at ( 0 ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read beyond the array limit std :: cout << array . at ( 5 ) << '\\n' ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge Example: (2) access specified object element with bounds checking The example below shows how object elements can be read and written using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // change element with key \"the bad\" object . at ( \"the bad\" ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key object . at ( \"the fast\" ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d Example: (2) access specified object element with bounds checking The example below shows how object elements can be read using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // exception type_error.304 try { // use at() on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key std :: cout << object . at ( \"the fast\" ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // change element with key \"the bad\" using string_view object . at ( \"the bad\" sv ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" sv ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key using string_view object . at ( \"the fast\" sv ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" sv ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key using string_view std :: cout << object . at ( \"the fast\" sv ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // writing access // change the string j . at ( \"/string\" _json_pointer ) = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // change an array element j . at ( \"/array/1\" _json_pointer ) = 21 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // out_of_range.106 try { // try to use an array index with leading '0' json :: reference ref = j . at ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.109 try { // try to use an array index that is not a number json :: reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" [ 1 , 21 ] [ jso n .excep t io n .parse_error. 106 ] parse error : array i n dex ' 01 ' mus t n o t begi n wi t h ' 0 ' [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo' 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // out_of_range.109 try { // try to use an array index that is not a number json :: const_reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: const_reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: const_reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: const_reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo' See also \u00b6 documentation on checked access see operator[] for unchecked access by reference see value for access with default value Version history \u00b6 Added in version 1.0.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 2.0.0.","title":"at"},{"location":"api/basic_json/at/#nlohmannbasic_jsonat","text":"// (1) reference at ( size_type idx ); const_reference at ( size_type idx ) const ; // (2) reference at ( const typename object_t :: key_type & key ); const_reference at ( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference at ( KeyType && key ); template < typename KeyType > const_reference at ( KeyType && key ) const ; // (4) reference at ( const json_pointer & ptr ); const_reference at ( const json_pointer & ptr ) const ; 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.","title":"nlohmann::basic_json::at"},{"location":"api/basic_json/at/#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).","title":"Template parameters"},{"location":"api/basic_json/at/#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","title":"Parameters"},{"location":"api/basic_json/at/#return-value","text":"reference to the element at index idx reference to the element at key key reference to the element at key key reference to the element pointed to by ptr","title":"Return value"},{"location":"api/basic_json/at/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/at/#exceptions","text":"The function can throw the following exceptions: Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below. Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size() . See example below. 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.","title":"Exceptions"},{"location":"api/basic_json/at/#complexity","text":"Constant. Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container.","title":"Complexity"},{"location":"api/basic_json/at/#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 #include using json = nlohmann :: json ; int main () { // create JSON array json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // change element at index 1 (second element) to \"second\" array . at ( 1 ) = \"second\" ; // output changed array std :: cout << array << '\\n' ; // exception type_error.304 try { // use at() on a non-array type json str = \"I am a string\" ; str . at ( 0 ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write beyond the array limit array . at ( 5 ) = \"sixth\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ \"first\" , \"second\" , \"third\" , \"fourth\" ] [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge 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 #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; // exception type_error.304 try { // use at() on a non-array type const json str = \"I am a string\" ; std :: cout << str . at ( 0 ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read beyond the array limit std :: cout << array . at ( 5 ) << '\\n' ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"third\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 5 is ou t o f ra n ge Example: (2) access specified object element with bounds checking The example below shows how object elements can be read and written using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // change element with key \"the bad\" object . at ( \"the bad\" ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key object . at ( \"the fast\" ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d Example: (2) access specified object element with bounds checking The example below shows how object elements can be read using at() . It also demonstrates the different exceptions that can be thrown. #include #include using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" std :: cout << object . at ( \"the ugly\" ) << '\\n' ; // exception type_error.304 try { // use at() on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key std :: cout << object . at ( \"the fast\" ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // change element with key \"the bad\" using string_view object . at ( \"the bad\" sv ) = \"il cattivo\" ; // output changed array std :: cout << object << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type json str = \"I am a string\" ; str . at ( \"the good\" sv ) = \"Another string\" ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to write at a nonexisting key using string_view object . at ( \"the fast\" sv ) = \"il rapido\" ; } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: \"il brutto\" { \"the bad\" : \"il cattivo\" , \"the good\" : \"il buono\" , \"the ugly\" : \"il brutto\" } [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' t he fast ' n o t f ou n d 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 #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create JSON object const json object = { { \"the good\" , \"il buono\" }, { \"the bad\" , \"il cattivo\" }, { \"the ugly\" , \"il brutto\" } }; // output element with key \"the ugly\" using string_view std :: cout << object . at ( \"the ugly\" sv ) << '\\n' ; // exception type_error.304 try { // use at() with string_view on a non-object type const json str = \"I am a string\" ; std :: cout << str . at ( \"the good\" sv ) << '\\n' ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } // exception out_of_range.401 try { // try to read from a nonexisting key using string_view std :: cout << object . at ( \"the fast\" sv ) << '\\n' ; } catch ( const json :: out_of_range ) { std :: cout << \"out of range\" << '\\n' ; } } Output: \"il brutto\" [ jso n .excep t io n . t ype_error. 304 ] ca nn o t use a t () wi t h s tr i n g ou t o f ra n ge 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // writing access // change the string j . at ( \"/string\" _json_pointer ) = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // change an array element j . at ( \"/array/1\" _json_pointer ) = 21 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // out_of_range.106 try { // try to use an array index with leading '0' json :: reference ref = j . at ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.109 try { // try to use an array index that is not a number json :: reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" [ 1 , 21 ] [ jso n .excep t io n .parse_error. 106 ] parse error : array i n dex ' 01 ' mus t n o t begi n wi t h ' 0 ' [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo' 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 #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j . at ( \"/number\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j . at ( \"/string\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j . at ( \"/array\" _json_pointer ) << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j . at ( \"/array/1\" _json_pointer ) << '\\n' ; // out_of_range.109 try { // try to use an array index that is not a number json :: const_reference ref = j . at ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.401 try { // try to use an invalid array index json :: const_reference ref = j . at ( \"/array/4\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.402 try { // try to use the array index '-' json :: const_reference ref = j . at ( \"/array/-\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json :: const_reference ref = j . at ( \"/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json :: const_reference ref = j . at ( \"/number/foo\" _json_pointer ); } catch ( const json :: out_of_range & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 \"foo\" [ 1 , 2 ] 2 [ jso n .excep t io n .parse_error. 109 ] parse error : array i n dex 'o ne ' is n o t a nu mber [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 402 ] array i n dex ' - ' ( 2 ) is ou t o f ra n ge [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' f oo' n o t f ou n d [ jso n .excep t io n .ou t _o f _ra n ge. 404 ] u nres olved re feren ce t oke n ' f oo'","title":"Examples"},{"location":"api/basic_json/at/#see-also","text":"documentation on checked access see operator[] for unchecked access by reference see value for access with default value","title":"See also"},{"location":"api/basic_json/at/#version-history","text":"Added in version 1.0.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/back/","text":"nlohmann::basic_json:: back \u00b6 reference back (); const_reference back () const ; Returns a reference to the last element in the container. For a JSON container c , the expression c.back() is equivalent to auto tmp = c . end (); -- tmp ; return * tmp ; Return value \u00b6 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. Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 If the JSON value is null , exception invalid_iterator.214 is thrown. Complexity \u00b6 Constant. Notes \u00b6 Precondition The array or object must not be empty. Calling back on an empty array or object yields undefined behavior. Examples \u00b6 Example The following code shows an example for back() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call back() std :: cout << j_boolean . back () << '\\n' ; std :: cout << j_number_integer . back () << '\\n' ; std :: cout << j_number_float . back () << '\\n' ; std :: cout << j_object . back () << '\\n' ; //std::cout << j_object_empty.back() << '\\n'; // undefined behavior std :: cout << j_array . back () << '\\n' ; //std::cout << j_array_empty.back() << '\\n'; // undefined behavior std :: cout << j_string . back () << '\\n' ; // back() called on a null value try { json j_null ; j_null . back (); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: true 17 23.42 2 16 \"Hello, world\" [ jso n .excep t io n .i n valid_i terat or. 214 ] ca nn o t ge t value See also \u00b6 front to access the first element Version history \u00b6 Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"back"},{"location":"api/basic_json/back/#nlohmannbasic_jsonback","text":"reference back (); const_reference back () const ; Returns a reference to the last element in the container. For a JSON container c , the expression c.back() is equivalent to auto tmp = c . end (); -- tmp ; return * tmp ;","title":"nlohmann::basic_json::back"},{"location":"api/basic_json/back/#return-value","text":"In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.","title":"Return value"},{"location":"api/basic_json/back/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/back/#exceptions","text":"If the JSON value is null , exception invalid_iterator.214 is thrown.","title":"Exceptions"},{"location":"api/basic_json/back/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/back/#notes","text":"Precondition The array or object must not be empty. Calling back on an empty array or object yields undefined behavior.","title":"Notes"},{"location":"api/basic_json/back/#examples","text":"Example The following code shows an example for back() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call back() std :: cout << j_boolean . back () << '\\n' ; std :: cout << j_number_integer . back () << '\\n' ; std :: cout << j_number_float . back () << '\\n' ; std :: cout << j_object . back () << '\\n' ; //std::cout << j_object_empty.back() << '\\n'; // undefined behavior std :: cout << j_array . back () << '\\n' ; //std::cout << j_array_empty.back() << '\\n'; // undefined behavior std :: cout << j_string . back () << '\\n' ; // back() called on a null value try { json j_null ; j_null . back (); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: true 17 23.42 2 16 \"Hello, world\" [ jso n .excep t io n .i n valid_i terat or. 214 ] ca nn o t ge t value","title":"Examples"},{"location":"api/basic_json/back/#see-also","text":"front to access the first element","title":"See also"},{"location":"api/basic_json/back/#version-history","text":"Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/basic_json/","text":"nlohmann::basic_json:: basic_json \u00b6 // (1) basic_json ( const value_t v ); // (2) basic_json ( std :: nullptr_t = nullptr ) noexcept ; // (3) template < typename CompatibleType > basic_json ( CompatibleType && val ) noexcept ( noexcept ( JSONSerializer < U >:: to_json ( std :: declval < basic_json_t &> (), std :: forward < CompatibleType > ( val )))); // (4) template < typename BasicJsonType > basic_json ( const BasicJsonType & val ); // (5) basic_json ( initializer_list_t init , bool type_deduction = true , value_t manual_type = value_t :: array ); // (6) basic_json ( size_type cnt , const basic_json & val ); // (7) basic_json ( iterator first , iterator last ); basic_json ( const_iterator first , const_iterator last ); // (8) basic_json ( const basic_json & other ); // (9) basic_json ( basic_json && other ) noexcept ; 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::to_json method with U = uncvref_t , 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 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. Template parameters \u00b6 CompatibleType a type such that: CompatibleType is not derived from std::istream , CompatibleType is not basic_json (to avoid hijacking copy/move constructors), CompatibleType is not a different basic_json type (i.e. with different template arguments) CompatibleType is not a basic_json nested type (e.g., json_pointer , iterator , etc.) json_serializer (with U = uncvref_t ) 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 Parameters \u00b6 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 Exception safety \u00b6 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. Exceptions \u00b6 (none) The function does not throw exceptions. (none) (none) The function can throw the following exceptions: Throws type_error.301 if type_deduction is false , manual_type is value_t::object , but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true , an array would have been created. See object(initializer_list_t) for an example. (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. (none) The function does not throw exceptions. Complexity \u00b6 Constant. Constant. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Linear in the size of the initializer list init . Linear in cnt . Linear in distance between first and last . Linear in the size of other . Constant. Notes \u00b6 Overload 5: Empty initializer list When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value. Overload 7: Preconditions 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 Examples \u00b6 Example: (1) create an empty value with a given type The following code shows the constructor for different value_t values. #include #include using json = nlohmann :: json ; int main () { // create the different JSON values with default values json j_null ( json :: value_t :: null ); json j_boolean ( json :: value_t :: boolean ); json j_number_integer ( json :: value_t :: number_integer ); json j_number_float ( json :: value_t :: number_float ); json j_object ( json :: value_t :: object ); json j_array ( json :: value_t :: array ); json j_string ( json :: value_t :: string ); // serialize the JSON values std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\" Example: (2) create a null object The following code shows the constructor with and without a null pointer parameter. #include #include using json = nlohmann :: json ; int main () { // implicitly create a JSON null value json j1 ; // explicitly create a JSON null value json j2 ( nullptr ); // serialize the JSON null value std :: cout << j1 << '\\n' << j2 << '\\n' ; } Output: null null Example: (3) create a JSON value from compatible types The following code shows the constructor with several compatible types. #include #include #include #include #include #include #include #include #include using json = nlohmann :: json ; int main () { // ============ // object types // ============ // create an object from an object_t value json :: object_t object_value = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_object_t ( object_value ); // create an object from std::map std :: map < std :: string , int > c_map { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 3 } }; json j_map ( c_map ); // create an object from std::unordered_map std :: unordered_map < const char * , double > c_umap { { \"one\" , 1.2 }, { \"two\" , 2.3 }, { \"three\" , 3.4 } }; json j_umap ( c_umap ); // create an object from std::multimap std :: multimap < std :: string , bool > c_mmap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_mmap ( c_mmap ); // only one entry for key \"three\" is used // create an object from std::unordered_multimap std :: unordered_multimap < std :: string , bool > c_ummap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_ummap ( c_ummap ); // only one entry for key \"three\" is used // serialize the JSON objects std :: cout << j_object_t << '\\n' ; std :: cout << j_map << '\\n' ; std :: cout << j_umap << '\\n' ; std :: cout << j_mmap << '\\n' ; std :: cout << j_ummap << \" \\n\\n \" ; // =========== // array types // =========== // create an array from an array_t value json :: array_t array_value = { \"one\" , \"two\" , 3 , 4.5 , false }; json j_array_t ( array_value ); // create an array from std::vector std :: vector < int > c_vector { 1 , 2 , 3 , 4 }; json j_vec ( c_vector ); // create an array from std::valarray std :: valarray < short > c_valarray { 10 , 9 , 8 , 7 }; json j_valarray ( c_valarray ); // create an array from std::deque std :: deque < double > c_deque { 1.2 , 2.3 , 3.4 , 5.6 }; json j_deque ( c_deque ); // create an array from std::list std :: list < bool > c_list { true , true , false , true }; json j_list ( c_list ); // create an array from std::forward_list std :: forward_list < std :: int64_t > c_flist { 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 }; json j_flist ( c_flist ); // create an array from std::array std :: array < unsigned long , 4 > c_array {{ 1 , 2 , 3 , 4 }}; json j_array ( c_array ); // create an array from std::set std :: set < std :: string > c_set { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_set ( c_set ); // only one entry for \"one\" is used // create an array from std::unordered_set std :: unordered_set < std :: string > c_uset { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_uset ( c_uset ); // only one entry for \"one\" is used // create an array from std::multiset std :: multiset < std :: string > c_mset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_mset ( c_mset ); // both entries for \"one\" are used // create an array from std::unordered_multiset std :: unordered_multiset < std :: string > c_umset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_umset ( c_umset ); // both entries for \"one\" are used // serialize the JSON arrays std :: cout << j_array_t << '\\n' ; std :: cout << j_vec << '\\n' ; std :: cout << j_valarray << '\\n' ; std :: cout << j_deque << '\\n' ; std :: cout << j_list << '\\n' ; std :: cout << j_flist << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_set << '\\n' ; std :: cout << j_uset << '\\n' ; std :: cout << j_mset << '\\n' ; std :: cout << j_umset << \" \\n\\n \" ; // ============ // string types // ============ // create string from a string_t value json :: string_t string_value = \"The quick brown fox jumps over the lazy dog.\" ; json j_string_t ( string_value ); // create a JSON string directly from a string literal json j_string_literal ( \"The quick brown fox jumps over the lazy dog.\" ); // create string from std::string std :: string s_stdstring = \"The quick brown fox jumps over the lazy dog.\" ; json j_stdstring ( s_stdstring ); // serialize the JSON strings std :: cout << j_string_t << '\\n' ; std :: cout << j_string_literal << '\\n' ; std :: cout << j_stdstring << \" \\n\\n \" ; // ============ // number types // ============ // create a JSON number from number_integer_t json :: number_integer_t value_integer_t = -42 ; json j_integer_t ( value_integer_t ); // create a JSON number from number_unsigned_t json :: number_integer_t value_unsigned_t = 17 ; json j_unsigned_t ( value_unsigned_t ); // create a JSON number from an anonymous enum enum { enum_value = 17 }; json j_enum ( enum_value ); // create values of different integer types short n_short = 42 ; int n_int = -23 ; long n_long = 1024 ; int_least32_t n_int_least32_t = -17 ; uint8_t n_uint8_t = 8 ; // create (integer) JSON numbers json j_short ( n_short ); json j_int ( n_int ); json j_long ( n_long ); json j_int_least32_t ( n_int_least32_t ); json j_uint8_t ( n_uint8_t ); // create values of different floating-point types json :: number_float_t v_ok = 3.141592653589793 ; json :: number_float_t v_nan = NAN ; json :: number_float_t v_infinity = INFINITY ; // create values of different floating-point types float n_float = 42.23 ; float n_float_nan = 1.0f / 0.0f ; double n_double = 23.42 ; // create (floating point) JSON numbers json j_ok ( v_ok ); json j_nan ( v_nan ); json j_infinity ( v_infinity ); json j_float ( n_float ); json j_float_nan ( n_float_nan ); json j_double ( n_double ); // serialize the JSON numbers std :: cout << j_integer_t << '\\n' ; std :: cout << j_unsigned_t << '\\n' ; std :: cout << j_enum << '\\n' ; std :: cout << j_short << '\\n' ; std :: cout << j_int << '\\n' ; std :: cout << j_long << '\\n' ; std :: cout << j_int_least32_t << '\\n' ; std :: cout << j_uint8_t << '\\n' ; std :: cout << j_ok << '\\n' ; std :: cout << j_nan << '\\n' ; std :: cout << j_infinity << '\\n' ; std :: cout << j_float << '\\n' ; std :: cout << j_float_nan << '\\n' ; std :: cout << j_double << \" \\n\\n \" ; // ============= // boolean types // ============= // create boolean values json j_truth = true ; json j_falsity = false ; // serialize the JSON booleans std :: cout << j_truth << '\\n' ; std :: cout << j_falsity << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"one\" : 1.2 , \"three\" : 3.4 , \"two\" : 2.3 } { \"one\" : true , \"three\" : false , \"two\" : true } { \"one\" : true , \"three\" : false , \"two\" : true } [ \"one\" , \"two\" , 3 , 4.5 , false ] [ 1 , 2 , 3 , 4 ] [ 10 , 9 , 8 , 7 ] [ 1.2 , 2.3 , 3.4 , 5.6 ] [ true , true , false , true ] [ 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 ] [ 1 , 2 , 3 , 4 ] [ \"four\" , \"one\" , \"three\" , \"two\" ] [ \"four\" , \"three\" , \"two\" , \"one\" ] [ \"four\" , \"one\" , \"one\" , \"two\" ] [ \"four\" , \"two\" , \"one\" , \"one\" ] \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" -42 17 17 42 -23 1024 -17 8 3.141592653589793 null null 42.22999954223633 null 23.42 true false Note the output is platform-dependent. Example: (5) create a container (array or object) from an initializer list The example below shows how JSON values are created from initializer lists. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_empty_init_list = json ({}); json j_object = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_array = { 1 , 2 , 3 , 4 }; json j_nested_object = { { \"one\" , { 1 }}, { \"two\" , { 1 , 2 }} }; json j_nested_array = { {{ 1 }, \"one\" }, {{ 1 , 2 }, \"two\" } }; // serialize the JSON value std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_nested_object << '\\n' ; std :: cout << j_nested_array << '\\n' ; } Output: {} { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 3 , 4 ] { \"one\" :[ 1 ], \"two\" :[ 1 , 2 ]} [[[ 1 ], \"one\" ],[[ 1 , 2 ], \"two\" ]] Example: (6) construct an array with count copies of given value The following code shows examples for creating arrays with several copies of a given value. #include #include using json = nlohmann :: json ; int main () { // create an array by creating copies of a JSON value json value = \"Hello\" ; json array_0 = json ( 0 , value ); json array_1 = json ( 1 , value ); json array_5 = json ( 5 , value ); // serialize the JSON arrays std :: cout << array_0 << '\\n' ; std :: cout << array_1 << '\\n' ; std :: cout << array_5 << '\\n' ; } Output: [] [ \"Hello\" ] [ \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" ] Example: (7) construct a JSON container given an iterator range The example below shows several ways to create JSON values by specifying a subrange with iterators. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_array = { \"alpha\" , \"bravo\" , \"charly\" , \"delta\" , \"easy\" }; json j_number = 42 ; json j_object = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; // create copies using iterators json j_array_range ( j_array . begin () + 1 , j_array . end () - 2 ); json j_number_range ( j_number . begin (), j_number . end ()); json j_object_range ( j_object . begin (), j_object . find ( \"two\" )); // serialize the values std :: cout << j_array_range << '\\n' ; std :: cout << j_number_range << '\\n' ; std :: cout << j_object_range << '\\n' ; // example for an exception try { json j_invalid ( j_number . begin () + 1 , j_number . end ()); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ \"bravo\" , \"charly\" ] 42 { \"one\" : \"eins\" } [ jso n .excep t io n .i n valid_i terat or. 204 ] i terat ors ou t o f ra n ge Example: (8) copy constructor The following code shows an example for the copy constructor. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j1 = { \"one\" , \"two\" , 3 , 4.5 , false }; // create a copy json j2 ( j1 ); // serialize the JSON array std :: cout << j1 << \" = \" << j2 << '\\n' ; std :: cout << std :: boolalpha << ( j1 == j2 ) << '\\n' ; } Output: [ \"one\" , \"two\" , 3 , 4.5 , false ] = [ \"one\" , \"two\" , 3 , 4.5 , false ] true Example: (9) move constructor The code below shows the move constructor explicitly called via std::move . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json a = 23 ; // move contents of a to b json b ( std :: move ( a )); // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: null 23 Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 2.1.0. Since version 3.2.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0.","title":"(Constructor)"},{"location":"api/basic_json/basic_json/#nlohmannbasic_jsonbasic_json","text":"// (1) basic_json ( const value_t v ); // (2) basic_json ( std :: nullptr_t = nullptr ) noexcept ; // (3) template < typename CompatibleType > basic_json ( CompatibleType && val ) noexcept ( noexcept ( JSONSerializer < U >:: to_json ( std :: declval < basic_json_t &> (), std :: forward < CompatibleType > ( val )))); // (4) template < typename BasicJsonType > basic_json ( const BasicJsonType & val ); // (5) basic_json ( initializer_list_t init , bool type_deduction = true , value_t manual_type = value_t :: array ); // (6) basic_json ( size_type cnt , const basic_json & val ); // (7) basic_json ( iterator first , iterator last ); basic_json ( const_iterator first , const_iterator last ); // (8) basic_json ( const basic_json & other ); // (9) basic_json ( basic_json && other ) noexcept ; 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::to_json method with U = uncvref_t , 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 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.","title":"nlohmann::basic_json::basic_json"},{"location":"api/basic_json/basic_json/#template-parameters","text":"CompatibleType a type such that: CompatibleType is not derived from std::istream , CompatibleType is not basic_json (to avoid hijacking copy/move constructors), CompatibleType is not a different basic_json type (i.e. with different template arguments) CompatibleType is not a basic_json nested type (e.g., json_pointer , iterator , etc.) json_serializer (with U = uncvref_t ) 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","title":"Template parameters"},{"location":"api/basic_json/basic_json/#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","title":"Parameters"},{"location":"api/basic_json/basic_json/#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.","title":"Exception safety"},{"location":"api/basic_json/basic_json/#exceptions","text":"(none) The function does not throw exceptions. (none) (none) The function can throw the following exceptions: Throws type_error.301 if type_deduction is false , manual_type is value_t::object , but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have been true , an array would have been created. See object(initializer_list_t) for an example. (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. (none) The function does not throw exceptions.","title":"Exceptions"},{"location":"api/basic_json/basic_json/#complexity","text":"Constant. Constant. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Usually linear in the size of the passed val , also depending on the implementation of the called to_json() method. Linear in the size of the initializer list init . Linear in cnt . Linear in distance between first and last . Linear in the size of other . Constant.","title":"Complexity"},{"location":"api/basic_json/basic_json/#notes","text":"Overload 5: Empty initializer list When used without parentheses around an empty initializer list, basic_json() is called instead of this function, yielding the JSON null value. Overload 7: Preconditions 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","title":"Notes"},{"location":"api/basic_json/basic_json/#examples","text":"Example: (1) create an empty value with a given type The following code shows the constructor for different value_t values. #include #include using json = nlohmann :: json ; int main () { // create the different JSON values with default values json j_null ( json :: value_t :: null ); json j_boolean ( json :: value_t :: boolean ); json j_number_integer ( json :: value_t :: number_integer ); json j_number_float ( json :: value_t :: number_float ); json j_object ( json :: value_t :: object ); json j_array ( json :: value_t :: array ); json j_string ( json :: value_t :: string ); // serialize the JSON values std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\" Example: (2) create a null object The following code shows the constructor with and without a null pointer parameter. #include #include using json = nlohmann :: json ; int main () { // implicitly create a JSON null value json j1 ; // explicitly create a JSON null value json j2 ( nullptr ); // serialize the JSON null value std :: cout << j1 << '\\n' << j2 << '\\n' ; } Output: null null Example: (3) create a JSON value from compatible types The following code shows the constructor with several compatible types. #include #include #include #include #include #include #include #include #include using json = nlohmann :: json ; int main () { // ============ // object types // ============ // create an object from an object_t value json :: object_t object_value = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_object_t ( object_value ); // create an object from std::map std :: map < std :: string , int > c_map { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 3 } }; json j_map ( c_map ); // create an object from std::unordered_map std :: unordered_map < const char * , double > c_umap { { \"one\" , 1.2 }, { \"two\" , 2.3 }, { \"three\" , 3.4 } }; json j_umap ( c_umap ); // create an object from std::multimap std :: multimap < std :: string , bool > c_mmap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_mmap ( c_mmap ); // only one entry for key \"three\" is used // create an object from std::unordered_multimap std :: unordered_multimap < std :: string , bool > c_ummap { { \"one\" , true }, { \"two\" , true }, { \"three\" , false }, { \"three\" , true } }; json j_ummap ( c_ummap ); // only one entry for key \"three\" is used // serialize the JSON objects std :: cout << j_object_t << '\\n' ; std :: cout << j_map << '\\n' ; std :: cout << j_umap << '\\n' ; std :: cout << j_mmap << '\\n' ; std :: cout << j_ummap << \" \\n\\n \" ; // =========== // array types // =========== // create an array from an array_t value json :: array_t array_value = { \"one\" , \"two\" , 3 , 4.5 , false }; json j_array_t ( array_value ); // create an array from std::vector std :: vector < int > c_vector { 1 , 2 , 3 , 4 }; json j_vec ( c_vector ); // create an array from std::valarray std :: valarray < short > c_valarray { 10 , 9 , 8 , 7 }; json j_valarray ( c_valarray ); // create an array from std::deque std :: deque < double > c_deque { 1.2 , 2.3 , 3.4 , 5.6 }; json j_deque ( c_deque ); // create an array from std::list std :: list < bool > c_list { true , true , false , true }; json j_list ( c_list ); // create an array from std::forward_list std :: forward_list < std :: int64_t > c_flist { 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 }; json j_flist ( c_flist ); // create an array from std::array std :: array < unsigned long , 4 > c_array {{ 1 , 2 , 3 , 4 }}; json j_array ( c_array ); // create an array from std::set std :: set < std :: string > c_set { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_set ( c_set ); // only one entry for \"one\" is used // create an array from std::unordered_set std :: unordered_set < std :: string > c_uset { \"one\" , \"two\" , \"three\" , \"four\" , \"one\" }; json j_uset ( c_uset ); // only one entry for \"one\" is used // create an array from std::multiset std :: multiset < std :: string > c_mset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_mset ( c_mset ); // both entries for \"one\" are used // create an array from std::unordered_multiset std :: unordered_multiset < std :: string > c_umset { \"one\" , \"two\" , \"one\" , \"four\" }; json j_umset ( c_umset ); // both entries for \"one\" are used // serialize the JSON arrays std :: cout << j_array_t << '\\n' ; std :: cout << j_vec << '\\n' ; std :: cout << j_valarray << '\\n' ; std :: cout << j_deque << '\\n' ; std :: cout << j_list << '\\n' ; std :: cout << j_flist << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_set << '\\n' ; std :: cout << j_uset << '\\n' ; std :: cout << j_mset << '\\n' ; std :: cout << j_umset << \" \\n\\n \" ; // ============ // string types // ============ // create string from a string_t value json :: string_t string_value = \"The quick brown fox jumps over the lazy dog.\" ; json j_string_t ( string_value ); // create a JSON string directly from a string literal json j_string_literal ( \"The quick brown fox jumps over the lazy dog.\" ); // create string from std::string std :: string s_stdstring = \"The quick brown fox jumps over the lazy dog.\" ; json j_stdstring ( s_stdstring ); // serialize the JSON strings std :: cout << j_string_t << '\\n' ; std :: cout << j_string_literal << '\\n' ; std :: cout << j_stdstring << \" \\n\\n \" ; // ============ // number types // ============ // create a JSON number from number_integer_t json :: number_integer_t value_integer_t = -42 ; json j_integer_t ( value_integer_t ); // create a JSON number from number_unsigned_t json :: number_integer_t value_unsigned_t = 17 ; json j_unsigned_t ( value_unsigned_t ); // create a JSON number from an anonymous enum enum { enum_value = 17 }; json j_enum ( enum_value ); // create values of different integer types short n_short = 42 ; int n_int = -23 ; long n_long = 1024 ; int_least32_t n_int_least32_t = -17 ; uint8_t n_uint8_t = 8 ; // create (integer) JSON numbers json j_short ( n_short ); json j_int ( n_int ); json j_long ( n_long ); json j_int_least32_t ( n_int_least32_t ); json j_uint8_t ( n_uint8_t ); // create values of different floating-point types json :: number_float_t v_ok = 3.141592653589793 ; json :: number_float_t v_nan = NAN ; json :: number_float_t v_infinity = INFINITY ; // create values of different floating-point types float n_float = 42.23 ; float n_float_nan = 1.0f / 0.0f ; double n_double = 23.42 ; // create (floating point) JSON numbers json j_ok ( v_ok ); json j_nan ( v_nan ); json j_infinity ( v_infinity ); json j_float ( n_float ); json j_float_nan ( n_float_nan ); json j_double ( n_double ); // serialize the JSON numbers std :: cout << j_integer_t << '\\n' ; std :: cout << j_unsigned_t << '\\n' ; std :: cout << j_enum << '\\n' ; std :: cout << j_short << '\\n' ; std :: cout << j_int << '\\n' ; std :: cout << j_long << '\\n' ; std :: cout << j_int_least32_t << '\\n' ; std :: cout << j_uint8_t << '\\n' ; std :: cout << j_ok << '\\n' ; std :: cout << j_nan << '\\n' ; std :: cout << j_infinity << '\\n' ; std :: cout << j_float << '\\n' ; std :: cout << j_float_nan << '\\n' ; std :: cout << j_double << \" \\n\\n \" ; // ============= // boolean types // ============= // create boolean values json j_truth = true ; json j_falsity = false ; // serialize the JSON booleans std :: cout << j_truth << '\\n' ; std :: cout << j_falsity << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"one\" : 1.2 , \"three\" : 3.4 , \"two\" : 2.3 } { \"one\" : true , \"three\" : false , \"two\" : true } { \"one\" : true , \"three\" : false , \"two\" : true } [ \"one\" , \"two\" , 3 , 4.5 , false ] [ 1 , 2 , 3 , 4 ] [ 10 , 9 , 8 , 7 ] [ 1.2 , 2.3 , 3.4 , 5.6 ] [ true , true , false , true ] [ 12345678909876 , 23456789098765 , 34567890987654 , 45678909876543 ] [ 1 , 2 , 3 , 4 ] [ \"four\" , \"one\" , \"three\" , \"two\" ] [ \"four\" , \"three\" , \"two\" , \"one\" ] [ \"four\" , \"one\" , \"one\" , \"two\" ] [ \"four\" , \"two\" , \"one\" , \"one\" ] \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" \"The quick brown fox jumps over the lazy dog.\" -42 17 17 42 -23 1024 -17 8 3.141592653589793 null null 42.22999954223633 null 23.42 true false Note the output is platform-dependent. Example: (5) create a container (array or object) from an initializer list The example below shows how JSON values are created from initializer lists. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_empty_init_list = json ({}); json j_object = { { \"one\" , 1 }, { \"two\" , 2 } }; json j_array = { 1 , 2 , 3 , 4 }; json j_nested_object = { { \"one\" , { 1 }}, { \"two\" , { 1 , 2 }} }; json j_nested_array = { {{ 1 }, \"one\" }, {{ 1 , 2 }, \"two\" } }; // serialize the JSON value std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_nested_object << '\\n' ; std :: cout << j_nested_array << '\\n' ; } Output: {} { \"one\" : 1 , \"two\" : 2 } [ 1 , 2 , 3 , 4 ] { \"one\" :[ 1 ], \"two\" :[ 1 , 2 ]} [[[ 1 ], \"one\" ],[[ 1 , 2 ], \"two\" ]] Example: (6) construct an array with count copies of given value The following code shows examples for creating arrays with several copies of a given value. #include #include using json = nlohmann :: json ; int main () { // create an array by creating copies of a JSON value json value = \"Hello\" ; json array_0 = json ( 0 , value ); json array_1 = json ( 1 , value ); json array_5 = json ( 5 , value ); // serialize the JSON arrays std :: cout << array_0 << '\\n' ; std :: cout << array_1 << '\\n' ; std :: cout << array_5 << '\\n' ; } Output: [] [ \"Hello\" ] [ \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" , \"Hello\" ] Example: (7) construct a JSON container given an iterator range The example below shows several ways to create JSON values by specifying a subrange with iterators. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_array = { \"alpha\" , \"bravo\" , \"charly\" , \"delta\" , \"easy\" }; json j_number = 42 ; json j_object = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; // create copies using iterators json j_array_range ( j_array . begin () + 1 , j_array . end () - 2 ); json j_number_range ( j_number . begin (), j_number . end ()); json j_object_range ( j_object . begin (), j_object . find ( \"two\" )); // serialize the values std :: cout << j_array_range << '\\n' ; std :: cout << j_number_range << '\\n' ; std :: cout << j_object_range << '\\n' ; // example for an exception try { json j_invalid ( j_number . begin () + 1 , j_number . end ()); } catch ( const json :: invalid_iterator & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ \"bravo\" , \"charly\" ] 42 { \"one\" : \"eins\" } [ jso n .excep t io n .i n valid_i terat or. 204 ] i terat ors ou t o f ra n ge Example: (8) copy constructor The following code shows an example for the copy constructor. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j1 = { \"one\" , \"two\" , 3 , 4.5 , false }; // create a copy json j2 ( j1 ); // serialize the JSON array std :: cout << j1 << \" = \" << j2 << '\\n' ; std :: cout << std :: boolalpha << ( j1 == j2 ) << '\\n' ; } Output: [ \"one\" , \"two\" , 3 , 4.5 , false ] = [ \"one\" , \"two\" , 3 , 4.5 , false ] true Example: (9) move constructor The code below shows the move constructor explicitly called via std::move . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json a = 23 ; // move contents of a to b json b ( std :: move ( a )); // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: null 23","title":"Examples"},{"location":"api/basic_json/basic_json/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 2.1.0. Since version 3.2.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0.","title":"Version history"},{"location":"api/basic_json/begin/","text":"nlohmann::basic_json:: begin \u00b6 iterator begin () noexcept ; const_iterator begin () const noexcept ; Returns an iterator to the first element. Return value \u00b6 iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for begin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: iterator it = array . begin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"begin"},{"location":"api/basic_json/begin/#nlohmannbasic_jsonbegin","text":"iterator begin () noexcept ; const_iterator begin () const noexcept ; Returns an iterator to the first element.","title":"nlohmann::basic_json::begin"},{"location":"api/basic_json/begin/#return-value","text":"iterator to the first element","title":"Return value"},{"location":"api/basic_json/begin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/begin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/begin/#examples","text":"Example The following code shows an example for begin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: iterator it = array . begin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/begin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/binary/","text":"nlohmann::basic_json:: binary \u00b6 // (1) static basic_json binary ( const typename binary_t :: container_type & init ); static basic_json binary ( typename binary_t :: container_type && init ); // (2) static basic_json binary ( const typename binary_t :: container_type & init , std :: uint8_t subtype ); static basic_json binary ( typename binary_t :: container_type && init , std :: uint8_t subtype ); 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. Parameters \u00b6 init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON Return value \u00b6 JSON binary array value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of init ; constant for typename binary_t::container_type&& init versions. Notes \u00b6 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. Examples \u00b6 Example The following code shows how to create a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42 Version history \u00b6 Added in version 3.8.0.","title":"binary"},{"location":"api/basic_json/binary/#nlohmannbasic_jsonbinary","text":"// (1) static basic_json binary ( const typename binary_t :: container_type & init ); static basic_json binary ( typename binary_t :: container_type && init ); // (2) static basic_json binary ( const typename binary_t :: container_type & init , std :: uint8_t subtype ); static basic_json binary ( typename binary_t :: container_type && init , std :: uint8_t subtype ); 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.","title":"nlohmann::basic_json::binary"},{"location":"api/basic_json/binary/#parameters","text":"init (in) container containing bytes to use as binary type subtype (in) subtype to use in CBOR, MessagePack, and BSON","title":"Parameters"},{"location":"api/basic_json/binary/#return-value","text":"JSON binary array value","title":"Return value"},{"location":"api/basic_json/binary/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/binary/#complexity","text":"Linear in the size of init ; constant for typename binary_t::container_type&& init versions.","title":"Complexity"},{"location":"api/basic_json/binary/#notes","text":"Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a std::vector . Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.","title":"Notes"},{"location":"api/basic_json/binary/#examples","text":"Example The following code shows how to create a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42","title":"Examples"},{"location":"api/basic_json/binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/binary_t/","text":"nlohmann::basic_json:: binary_t \u00b6 using binary_t = byte_container_with_subtype < BinaryType > ; 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++. Template parameters \u00b6 BinaryType container type to store arrays Notes \u00b6 Default type \u00b6 The default values for BinaryType is std :: vector < std :: uint8_t > . Storage \u00b6 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. Notes on subtypes \u00b6 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. Examples \u00b6 Example The following code shows that binary_t is by default, a typedef to nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> , json :: binary_t >:: value << std :: endl ; } Output: true See also \u00b6 byte_container_with_subtype Version history \u00b6 Added in version 3.8.0. Changed type of subtype to std::uint64_t in version 3.10.0.","title":"binary_t"},{"location":"api/basic_json/binary_t/#nlohmannbasic_jsonbinary_t","text":"using binary_t = byte_container_with_subtype < BinaryType > ; 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++.","title":"nlohmann::basic_json::binary_t"},{"location":"api/basic_json/binary_t/#template-parameters","text":"BinaryType container type to store arrays","title":"Template parameters"},{"location":"api/basic_json/binary_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/binary_t/#default-type","text":"The default values for BinaryType is std :: vector < std :: uint8_t > .","title":"Default type"},{"location":"api/basic_json/binary_t/#storage","text":"Binary Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of the type binary_t * must be dereferenced.","title":"Storage"},{"location":"api/basic_json/binary_t/#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.","title":"Notes on subtypes"},{"location":"api/basic_json/binary_t/#examples","text":"Example The following code shows that binary_t is by default, a typedef to nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> , json :: binary_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/binary_t/#see-also","text":"byte_container_with_subtype","title":"See also"},{"location":"api/basic_json/binary_t/#version-history","text":"Added in version 3.8.0. Changed type of subtype to std::uint64_t in version 3.10.0.","title":"Version history"},{"location":"api/basic_json/boolean_t/","text":"nlohmann::basic_json:: boolean_t \u00b6 using boolean_t = BooleanType ; The type used to store JSON booleans. RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false . To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use. Notes \u00b6 Default type \u00b6 With the default values for BooleanType ( bool ), the default value for boolean_t is bool . Storage \u00b6 Boolean values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that boolean_t is by default, a typedef to bool . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < bool , json :: boolean_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"boolean_t"},{"location":"api/basic_json/boolean_t/#nlohmannbasic_jsonboolean_t","text":"using boolean_t = BooleanType ; The type used to store JSON booleans. RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false . To store objects in C++, a type is defined by the template parameter BooleanType which chooses the type to use.","title":"nlohmann::basic_json::boolean_t"},{"location":"api/basic_json/boolean_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/boolean_t/#default-type","text":"With the default values for BooleanType ( bool ), the default value for boolean_t is bool .","title":"Default type"},{"location":"api/basic_json/boolean_t/#storage","text":"Boolean values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/boolean_t/#examples","text":"Example The following code shows that boolean_t is by default, a typedef to bool . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < bool , json :: boolean_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/boolean_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/cbegin/","text":"nlohmann::basic_json:: cbegin \u00b6 const_iterator cbegin () const noexcept ; Returns an iterator to the first element. Return value \u00b6 iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for cbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value const json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: const_iterator it = array . cbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"cbegin"},{"location":"api/basic_json/cbegin/#nlohmannbasic_jsoncbegin","text":"const_iterator cbegin () const noexcept ; Returns an iterator to the first element.","title":"nlohmann::basic_json::cbegin"},{"location":"api/basic_json/cbegin/#return-value","text":"iterator to the first element","title":"Return value"},{"location":"api/basic_json/cbegin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/cbegin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/cbegin/#examples","text":"Example The following code shows an example for cbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value const json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the first element json :: const_iterator it = array . cbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/cbegin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/cbor_tag_handler_t/","text":"nlohmann::basic_json:: cbor_tag_handler_t \u00b6 enum class cbor_tag_handler_t { error , ignore , store }; 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) Examples \u00b6 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 #include using json = nlohmann :: json ; int main () { // tagged byte string std :: vector < std :: uint8_t > vec = {{ 0xd8 , 0x42 , 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // cbor_tag_handler_t::error throws try { auto b_throw_on_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: error ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // cbor_tag_handler_t::ignore ignores the tag auto b_ignore_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: ignore ); std :: cout << b_ignore_tag << std :: endl ; // cbor_tag_handler_t::store stores the tag as binary subtype auto b_store_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: store ); std :: cout << b_store_tag << std :: endl ; } Output: [ jso n .excep t io n .parse_error. 112 ] parse error a t by te 1 : sy nta x error while parsi n g CBOR value : i n valid by te : 0 xD 8 { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 66 } Version history \u00b6 Added in version 3.9.0. Added value store in 3.10.0.","title":"cbor_tag_handler_t"},{"location":"api/basic_json/cbor_tag_handler_t/#nlohmannbasic_jsoncbor_tag_handler_t","text":"enum class cbor_tag_handler_t { error , ignore , store }; 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)","title":"nlohmann::basic_json::cbor_tag_handler_t"},{"location":"api/basic_json/cbor_tag_handler_t/#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 #include using json = nlohmann :: json ; int main () { // tagged byte string std :: vector < std :: uint8_t > vec = {{ 0xd8 , 0x42 , 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // cbor_tag_handler_t::error throws try { auto b_throw_on_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: error ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // cbor_tag_handler_t::ignore ignores the tag auto b_ignore_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: ignore ); std :: cout << b_ignore_tag << std :: endl ; // cbor_tag_handler_t::store stores the tag as binary subtype auto b_store_tag = json :: from_cbor ( vec , true , true , json :: cbor_tag_handler_t :: store ); std :: cout << b_store_tag << std :: endl ; } Output: [ jso n .excep t io n .parse_error. 112 ] parse error a t by te 1 : sy nta x error while parsi n g CBOR value : i n valid by te : 0 xD 8 { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 66 }","title":"Examples"},{"location":"api/basic_json/cbor_tag_handler_t/#version-history","text":"Added in version 3.9.0. Added value store in 3.10.0.","title":"Version history"},{"location":"api/basic_json/cend/","text":"nlohmann::basic_json:: cend \u00b6 const_iterator cend () const noexcept ; Returns an iterator to one past the last element. Return value \u00b6 iterator one past the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for cend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: const_iterator it = array . cend (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"cend"},{"location":"api/basic_json/cend/#nlohmannbasic_jsoncend","text":"const_iterator cend () const noexcept ; Returns an iterator to one past the last element.","title":"nlohmann::basic_json::cend"},{"location":"api/basic_json/cend/#return-value","text":"iterator one past the last element","title":"Return value"},{"location":"api/basic_json/cend/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/cend/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/cend/#examples","text":"Example The following code shows an example for cend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: const_iterator it = array . cend (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/cend/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/clear/","text":"nlohmann::basic_json:: clear \u00b6 void clear () noexcept ; Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type() : Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array [] Has the same effect as calling * this = basic_json ( type ()); Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear in the size of the JSON value. Notes \u00b6 All iterators, pointers and references related to this container are invalidated. Examples \u00b6 Example The example below shows the effect of clear() to different JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call clear() j_null . clear (); j_boolean . clear (); j_number_integer . clear (); j_number_float . clear (); j_object . clear (); j_array . clear (); j_string . clear (); // serialize the cleared values() std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\" Version history \u00b6 Added in version 1.0.0. Added support for binary types in version 3.8.0.","title":"clear"},{"location":"api/basic_json/clear/#nlohmannbasic_jsonclear","text":"void clear () noexcept ; Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type() : Value type initial value null null boolean false string \"\" number 0 binary An empty byte vector object {} array [] Has the same effect as calling * this = basic_json ( type ());","title":"nlohmann::basic_json::clear"},{"location":"api/basic_json/clear/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/clear/#complexity","text":"Linear in the size of the JSON value.","title":"Complexity"},{"location":"api/basic_json/clear/#notes","text":"All iterators, pointers and references related to this container are invalidated.","title":"Notes"},{"location":"api/basic_json/clear/#examples","text":"Example The example below shows the effect of clear() to different JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call clear() j_null . clear (); j_boolean . clear (); j_number_integer . clear (); j_number_float . clear (); j_object . clear (); j_array . clear (); j_string . clear (); // serialize the cleared values() std :: cout << j_null << '\\n' ; std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null false 0 0.0 {} [] \"\"","title":"Examples"},{"location":"api/basic_json/clear/#version-history","text":"Added in version 1.0.0. Added support for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/contains/","text":"nlohmann::basic_json:: contains \u00b6 // (1) bool contains ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > bool contains ( KeyType && key ) const ; // (3) bool contains ( const json_pointer & ptr ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 key (in) key value to check its existence. ptr (in) JSON pointer to check its existence. Return value \u00b6 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. Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function does not throw exceptions. The function does not throw exceptions. The function can throw the following exceptions: Throws parse_error.106 if an array index begins with 0 . Throws parse_error.109 if an array index was not a number. Complexity \u00b6 Logarithmic in the size of the JSON object. Notes \u00b6 This method always returns false when executed on a JSON type that is not an object. This method can be executed on any JSON value type. Postconditions If j . contains ( x ) returns true for a key or JSON pointer x , then it is safe to call j[x] . Examples \u00b6 Example: (1) check with key The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (2) check with key using string_view The example shows how contains() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" sv ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" sv ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" sv ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (3) check with JSON pointer The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; std :: cout << std :: boolalpha << j . contains ( \"/number\" _json_pointer ) << '\\n' << j . contains ( \"/string\" _json_pointer ) << '\\n' << j . contains ( \"/array\" _json_pointer ) << '\\n' << j . contains ( \"/array/1\" _json_pointer ) << '\\n' << j . contains ( \"/array/-\" _json_pointer ) << '\\n' << j . contains ( \"/array/4\" _json_pointer ) << '\\n' << j . contains ( \"/baz\" _json_pointer ) << std :: endl ; try { // try to use an array index with leading '0' j . contains ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } try { // try to use an array index that is not a number j . contains ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: true true true true false false false Version history \u00b6 Added in version 3.11.0. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0. Added in version 3.7.0.","title":"contains"},{"location":"api/basic_json/contains/#nlohmannbasic_jsoncontains","text":"// (1) bool contains ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > bool contains ( KeyType && key ) const ; // (3) bool contains ( const json_pointer & ptr ) const ; 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.","title":"nlohmann::basic_json::contains"},{"location":"api/basic_json/contains/#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).","title":"Template parameters"},{"location":"api/basic_json/contains/#parameters","text":"key (in) key value to check its existence. ptr (in) JSON pointer to check its existence.","title":"Parameters"},{"location":"api/basic_json/contains/#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.","title":"Return value"},{"location":"api/basic_json/contains/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/contains/#exceptions","text":"The function does not throw exceptions. The function does not throw exceptions. The function can throw the following exceptions: Throws parse_error.106 if an array index begins with 0 . Throws parse_error.109 if an array index was not a number.","title":"Exceptions"},{"location":"api/basic_json/contains/#complexity","text":"Logarithmic in the size of the JSON object.","title":"Complexity"},{"location":"api/basic_json/contains/#notes","text":"This method always returns false when executed on a JSON type that is not an object. This method can be executed on any JSON value type. Postconditions If j . contains ( x ) returns true for a key or JSON pointer x , then it is safe to call j[x] .","title":"Notes"},{"location":"api/basic_json/contains/#examples","text":"Example: (1) check with key The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (2) check with key using string_view The example shows how contains() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create some JSON values json j_object = R \" ( {\"key\": \"value\"} ) \" _json ; json j_array = R \" ( [1, 2, 3] ) \" _json ; // call contains std :: cout << std :: boolalpha << \"j_object contains 'key': \" << j_object . contains ( \"key\" sv ) << '\\n' << \"j_object contains 'another': \" << j_object . contains ( \"another\" sv ) << '\\n' << \"j_array contains 'key': \" << j_array . contains ( \"key\" sv ) << std :: endl ; } Output: j_objec t co nta i ns 'key' : true j_objec t co nta i ns 'a n o t her' : false j_array co nta i ns 'key' : false Example: (3) check with JSON pointer The example shows how contains() is used. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; std :: cout << std :: boolalpha << j . contains ( \"/number\" _json_pointer ) << '\\n' << j . contains ( \"/string\" _json_pointer ) << '\\n' << j . contains ( \"/array\" _json_pointer ) << '\\n' << j . contains ( \"/array/1\" _json_pointer ) << '\\n' << j . contains ( \"/array/-\" _json_pointer ) << '\\n' << j . contains ( \"/array/4\" _json_pointer ) << '\\n' << j . contains ( \"/baz\" _json_pointer ) << std :: endl ; try { // try to use an array index with leading '0' j . contains ( \"/array/01\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } try { // try to use an array index that is not a number j . contains ( \"/array/one\" _json_pointer ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: true true true true false false false","title":"Examples"},{"location":"api/basic_json/contains/#version-history","text":"Added in version 3.11.0. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0. Added in version 3.7.0.","title":"Version history"},{"location":"api/basic_json/count/","text":"nlohmann::basic_json:: count \u00b6 // (1) size_type count ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > size_type count ( KeyType && key ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 key (in) key value of the element to count. Return value \u00b6 Number of elements with key key . If the JSON value is not an object, the return value will be 0 . Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Complexity \u00b6 Logarithmic in the size of the JSON object. Notes \u00b6 This method always returns 0 when executed on a JSON type that is not an object. Examples \u00b6 Example: (1) count number of elements The example shows how count() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" ); auto count_three = j_object . count ( \"three\" ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0 Example: (2) count number of elements using string_view The example shows how count() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" sv ); auto count_three = j_object . count ( \"three\" sv ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0 Version history \u00b6 Added in version 3.11.0. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0.","title":"count"},{"location":"api/basic_json/count/#nlohmannbasic_jsoncount","text":"// (1) size_type count ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > size_type count ( KeyType && key ) const ; 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.","title":"nlohmann::basic_json::count"},{"location":"api/basic_json/count/#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).","title":"Template parameters"},{"location":"api/basic_json/count/#parameters","text":"key (in) key value of the element to count.","title":"Parameters"},{"location":"api/basic_json/count/#return-value","text":"Number of elements with key key . If the JSON value is not an object, the return value will be 0 .","title":"Return value"},{"location":"api/basic_json/count/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/count/#complexity","text":"Logarithmic in the size of the JSON object.","title":"Complexity"},{"location":"api/basic_json/count/#notes","text":"This method always returns 0 when executed on a JSON type that is not an object.","title":"Notes"},{"location":"api/basic_json/count/#examples","text":"Example: (1) count number of elements The example shows how count() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" ); auto count_three = j_object . count ( \"three\" ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0 Example: (2) count number of elements using string_view The example shows how count() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call count() auto count_two = j_object . count ( \"two\" sv ); auto count_three = j_object . count ( \"three\" sv ); // print values std :: cout << \"number of elements with key \\\" two \\\" : \" << count_two << '\\n' ; std :: cout << \"number of elements with key \\\" three \\\" : \" << count_three << '\\n' ; } Output: nu mber o f eleme nts wi t h key \"two\" : 1 nu mber o f eleme nts wi t h key \"three\" : 0","title":"Examples"},{"location":"api/basic_json/count/#version-history","text":"Added in version 3.11.0. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/crbegin/","text":"nlohmann::basic_json:: crbegin \u00b6 const_reverse_iterator crbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element. Return value \u00b6 reverse iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for crbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: const_reverse_iterator it = array . crbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"crbegin"},{"location":"api/basic_json/crbegin/#nlohmannbasic_jsoncrbegin","text":"const_reverse_iterator crbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element.","title":"nlohmann::basic_json::crbegin"},{"location":"api/basic_json/crbegin/#return-value","text":"reverse iterator to the first element","title":"Return value"},{"location":"api/basic_json/crbegin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/crbegin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/crbegin/#examples","text":"Example The following code shows an example for crbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: const_reverse_iterator it = array . crbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/crbegin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/crend/","text":"nlohmann::basic_json:: crend \u00b6 const_reverse_iterator crend () const noexcept ; 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. Return value \u00b6 reverse iterator to the element following the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: const_reverse_iterator it = array . crend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"crend"},{"location":"api/basic_json/crend/#nlohmannbasic_jsoncrend","text":"const_reverse_iterator crend () const noexcept ; 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.","title":"nlohmann::basic_json::crend"},{"location":"api/basic_json/crend/#return-value","text":"reverse iterator to the element following the last element","title":"Return value"},{"location":"api/basic_json/crend/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/crend/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/crend/#examples","text":"Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: const_reverse_iterator it = array . crend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/crend/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/default_object_comparator_t/","text":"nlohmann::basic_json:: default_object_comparator_t \u00b6 using default_object_comparator_t = std :: less < StringType > ; // until C++14 using default_object_comparator_t = std :: less <> ; // since C++14 The default comparator used by object_t . Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object. The actual comparator used depends on object_t and can be obtained via object_comparator_t . Examples \u00b6 Example The example below demonstrates the default comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"one < two : \" << json :: default_object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"three < four : \" << json :: default_object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: o ne < t wo : true t hree < f our : false Version history \u00b6 Added in version 3.11.0.","title":"default_object_comparator_t"},{"location":"api/basic_json/default_object_comparator_t/#nlohmannbasic_jsondefault_object_comparator_t","text":"using default_object_comparator_t = std :: less < StringType > ; // until C++14 using default_object_comparator_t = std :: less <> ; // since C++14 The default comparator used by object_t . Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object. The actual comparator used depends on object_t and can be obtained via object_comparator_t .","title":"nlohmann::basic_json::default_object_comparator_t"},{"location":"api/basic_json/default_object_comparator_t/#examples","text":"Example The example below demonstrates the default comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"one < two : \" << json :: default_object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"three < four : \" << json :: default_object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: o ne < t wo : true t hree < f our : false","title":"Examples"},{"location":"api/basic_json/default_object_comparator_t/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/diff/","text":"nlohmann::basic_json:: diff \u00b6 static basic_json diff ( const basic_json & source , const basic_json & target ); 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 ; Parameters \u00b6 source (in) JSON value to compare from target (in) JSON value to compare against Return value \u00b6 a JSON patch to convert the source to target Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the lengths of source and target . Notes \u00b6 Currently, only remove , add , and replace operations are generated. Examples \u00b6 Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } See also \u00b6 RFC 6902 (JSON Patch) Version history \u00b6 Added in version 2.0.0.","title":"diff"},{"location":"api/basic_json/diff/#nlohmannbasic_jsondiff","text":"static basic_json diff ( const basic_json & source , const basic_json & target ); 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 ;","title":"nlohmann::basic_json::diff"},{"location":"api/basic_json/diff/#parameters","text":"source (in) JSON value to compare from target (in) JSON value to compare against","title":"Parameters"},{"location":"api/basic_json/diff/#return-value","text":"a JSON patch to convert the source to target","title":"Return value"},{"location":"api/basic_json/diff/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/diff/#complexity","text":"Linear in the lengths of source and target .","title":"Complexity"},{"location":"api/basic_json/diff/#notes","text":"Currently, only remove , add , and replace operations are generated.","title":"Notes"},{"location":"api/basic_json/diff/#examples","text":"Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Examples"},{"location":"api/basic_json/diff/#see-also","text":"RFC 6902 (JSON Patch)","title":"See also"},{"location":"api/basic_json/diff/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/dump/","text":"nlohmann::basic_json:: dump \u00b6 string_t dump ( const int indent = -1 , const char indent_char = ' ' , const bool ensure_ascii = false , const error_handler_t error_handler = error_handler_t :: strict ) const ; Serialization function for JSON values. The function tries to mimic Python's json.dumps() function , and currently supports its indent and ensure_ascii parameters. Parameters \u00b6 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)). Return value \u00b6 string containing the serialization of the JSON value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Exceptions \u00b6 Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict Complexity \u00b6 Linear. Notes \u00b6 Binary values are serialized as object containing two keys: \"bytes\": an array of bytes as integers \"subtype\": the subtype as integer or null if the binary has no subtype Examples \u00b6 Example The following example shows the effect of different indent , indent_char , and ensure_ascii parameters to the result of the serialization. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hell\u00f6 \ud83d\ude00!\" ; // call dump() std :: cout << \"objects:\" << '\\n' << j_object . dump () << \" \\n\\n \" << j_object . dump ( -1 ) << \" \\n\\n \" << j_object . dump ( 0 ) << \" \\n\\n \" << j_object . dump ( 4 ) << \" \\n\\n \" << j_object . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"arrays:\" << '\\n' << j_array . dump () << \" \\n\\n \" << j_array . dump ( -1 ) << \" \\n\\n \" << j_array . dump ( 0 ) << \" \\n\\n \" << j_array . dump ( 4 ) << \" \\n\\n \" << j_array . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"strings:\" << '\\n' << j_string . dump () << '\\n' << j_string . dump ( -1 , ' ' , true ) << '\\n' ; // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: objec ts : { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } arrays : [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] s tr i n gs : \"Hell\u00f6 \ud83d\ude00!\" \"Hell\\u00f6 \\ud83d\\ude00!\" [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\" Version history \u00b6 Added in version 1.0.0. Indentation character indent_char , option ensure_ascii and exceptions added in version 3.0.0. Error handlers added in version 3.4.0. Serialization of binary values added in version 3.8.0.","title":"dump"},{"location":"api/basic_json/dump/#nlohmannbasic_jsondump","text":"string_t dump ( const int indent = -1 , const char indent_char = ' ' , const bool ensure_ascii = false , const error_handler_t error_handler = error_handler_t :: strict ) const ; Serialization function for JSON values. The function tries to mimic Python's json.dumps() function , and currently supports its indent and ensure_ascii parameters.","title":"nlohmann::basic_json::dump"},{"location":"api/basic_json/dump/#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)).","title":"Parameters"},{"location":"api/basic_json/dump/#return-value","text":"string containing the serialization of the JSON value","title":"Return value"},{"location":"api/basic_json/dump/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/dump/#exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and error_handler is set to strict","title":"Exceptions"},{"location":"api/basic_json/dump/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/dump/#notes","text":"Binary values are serialized as object containing two keys: \"bytes\": an array of bytes as integers \"subtype\": the subtype as integer or null if the binary has no subtype","title":"Notes"},{"location":"api/basic_json/dump/#examples","text":"Example The following example shows the effect of different indent , indent_char , and ensure_ascii parameters to the result of the serialization. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hell\u00f6 \ud83d\ude00!\" ; // call dump() std :: cout << \"objects:\" << '\\n' << j_object . dump () << \" \\n\\n \" << j_object . dump ( -1 ) << \" \\n\\n \" << j_object . dump ( 0 ) << \" \\n\\n \" << j_object . dump ( 4 ) << \" \\n\\n \" << j_object . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"arrays:\" << '\\n' << j_array . dump () << \" \\n\\n \" << j_array . dump ( -1 ) << \" \\n\\n \" << j_array . dump ( 0 ) << \" \\n\\n \" << j_array . dump ( 4 ) << \" \\n\\n \" << j_array . dump ( 1 , '\\t' ) << \" \\n\\n \" ; std :: cout << \"strings:\" << '\\n' << j_string . dump () << '\\n' << j_string . dump ( -1 , ' ' , true ) << '\\n' ; // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: objec ts : { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } { \"one\" : 1 , \"two\" : 2 } arrays : [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] [ 1 , 2 , 4 , 8 , 16 ] s tr i n gs : \"Hell\u00f6 \ud83d\ude00!\" \"Hell\\u00f6 \\ud83d\\ude00!\" [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\"","title":"Examples"},{"location":"api/basic_json/dump/#version-history","text":"Added in version 1.0.0. Indentation character indent_char , option ensure_ascii and exceptions added in version 3.0.0. Error handlers added in version 3.4.0. Serialization of binary values added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/emplace/","text":"nlohmann::basic_json:: emplace \u00b6 template < class ... Args > std :: pair < iterator , bool > emplace ( Args && ... args ); 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 . Template parameters \u00b6 Args compatible types to create a basic_json object Parameters \u00b6 args (in) arguments to forward to a constructor of basic_json Return value \u00b6 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. Exceptions \u00b6 Throws type_error.311 when called on a type other than JSON object or null ; example: \"cannot use emplace() with number\" Complexity \u00b6 Logarithmic in the size of the container, O(log( size() )). Examples \u00b6 Example The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values auto res1 = object . emplace ( \"three\" , 3 ); null . emplace ( \"A\" , \"a\" ); null . emplace ( \"B\" , \"b\" ); // the following call will not add an object, because there is already // a value stored at key \"B\" auto res2 = null . emplace ( \"B\" , \"c\" ); // print values std :: cout << object << '\\n' ; std :: cout << * res1 . first << \" \" << std :: boolalpha << res1 . second << '\\n' ; std :: cout << null << '\\n' ; std :: cout << * res2 . first << \" \" << std :: boolalpha << res2 . second << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } 3 true { \"A\" : \"a\" , \"B\" : \"b\" } \"b\" false Version history \u00b6 Since version 2.0.8.","title":"emplace"},{"location":"api/basic_json/emplace/#nlohmannbasic_jsonemplace","text":"template < class ... Args > std :: pair < iterator , bool > emplace ( Args && ... args ); 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 .","title":"nlohmann::basic_json::emplace"},{"location":"api/basic_json/emplace/#template-parameters","text":"Args compatible types to create a basic_json object","title":"Template parameters"},{"location":"api/basic_json/emplace/#parameters","text":"args (in) arguments to forward to a constructor of basic_json","title":"Parameters"},{"location":"api/basic_json/emplace/#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.","title":"Return value"},{"location":"api/basic_json/emplace/#exceptions","text":"Throws type_error.311 when called on a type other than JSON object or null ; example: \"cannot use emplace() with number\"","title":"Exceptions"},{"location":"api/basic_json/emplace/#complexity","text":"Logarithmic in the size of the container, O(log( size() )).","title":"Complexity"},{"location":"api/basic_json/emplace/#examples","text":"Example The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values auto res1 = object . emplace ( \"three\" , 3 ); null . emplace ( \"A\" , \"a\" ); null . emplace ( \"B\" , \"b\" ); // the following call will not add an object, because there is already // a value stored at key \"B\" auto res2 = null . emplace ( \"B\" , \"c\" ); // print values std :: cout << object << '\\n' ; std :: cout << * res1 . first << \" \" << std :: boolalpha << res1 . second << '\\n' ; std :: cout << null << '\\n' ; std :: cout << * res2 . first << \" \" << std :: boolalpha << res2 . second << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } 3 true { \"A\" : \"a\" , \"B\" : \"b\" } \"b\" false","title":"Examples"},{"location":"api/basic_json/emplace/#version-history","text":"Since version 2.0.8.","title":"Version history"},{"location":"api/basic_json/emplace_back/","text":"nlohmann::basic_json:: emplace_back \u00b6 template < class ... Args > reference emplace_back ( Args && ... args ); 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 . Template parameters \u00b6 Args compatible types to create a basic_json object Parameters \u00b6 args (in) arguments to forward to a constructor of basic_json Return value \u00b6 reference to the inserted element Exceptions \u00b6 Throws type_error.311 when called on a type other than JSON array or null ; example: \"cannot use emplace_back() with number\" Complexity \u00b6 Amortized constant. Examples \u00b6 Example The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . emplace_back ( 6 ); null . emplace_back ( \"first\" ); null . emplace_back ( 3 , \"second\" ); // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 ] [ \"first\" ,[ \"second\" , \"second\" , \"second\" ]] Version history \u00b6 Since version 2.0.8. Returns reference since 3.7.0.","title":"emplace_back"},{"location":"api/basic_json/emplace_back/#nlohmannbasic_jsonemplace_back","text":"template < class ... Args > reference emplace_back ( Args && ... args ); 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 .","title":"nlohmann::basic_json::emplace_back"},{"location":"api/basic_json/emplace_back/#template-parameters","text":"Args compatible types to create a basic_json object","title":"Template parameters"},{"location":"api/basic_json/emplace_back/#parameters","text":"args (in) arguments to forward to a constructor of basic_json","title":"Parameters"},{"location":"api/basic_json/emplace_back/#return-value","text":"reference to the inserted element","title":"Return value"},{"location":"api/basic_json/emplace_back/#exceptions","text":"Throws type_error.311 when called on a type other than JSON array or null ; example: \"cannot use emplace_back() with number\"","title":"Exceptions"},{"location":"api/basic_json/emplace_back/#complexity","text":"Amortized constant.","title":"Complexity"},{"location":"api/basic_json/emplace_back/#examples","text":"Example The example shows how emplace_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . emplace_back ( 6 ); null . emplace_back ( \"first\" ); null . emplace_back ( 3 , \"second\" ); // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 ] [ \"first\" ,[ \"second\" , \"second\" , \"second\" ]]","title":"Examples"},{"location":"api/basic_json/emplace_back/#version-history","text":"Since version 2.0.8. Returns reference since 3.7.0.","title":"Version history"},{"location":"api/basic_json/empty/","text":"nlohmann::basic_json:: empty \u00b6 bool empty () const noexcept ; Checks if a JSON value has no elements (i.e. whether its size() is 0 ). Return value \u00b6 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() Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity. Possible implementation \u00b6 bool empty () const noexcept { return size () == 0 ; } Notes \u00b6 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. Examples \u00b6 Example The following code uses empty() to check if a JSON object contains any elements. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call empty() std :: cout << std :: boolalpha ; std :: cout << j_null . empty () << '\\n' ; std :: cout << j_boolean . empty () << '\\n' ; std :: cout << j_number_integer . empty () << '\\n' ; std :: cout << j_number_float . empty () << '\\n' ; std :: cout << j_object . empty () << '\\n' ; std :: cout << j_object_empty . empty () << '\\n' ; std :: cout << j_array . empty () << '\\n' ; std :: cout << j_array_empty . empty () << '\\n' ; std :: cout << j_string . empty () << '\\n' ; } Output: true false false false false true false true false Version history \u00b6 Added in version 1.0.0. Extended to return false for binary types in version 3.8.0.","title":"empty"},{"location":"api/basic_json/empty/#nlohmannbasic_jsonempty","text":"bool empty () const noexcept ; Checks if a JSON value has no elements (i.e. whether its size() is 0 ).","title":"nlohmann::basic_json::empty"},{"location":"api/basic_json/empty/#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()","title":"Return value"},{"location":"api/basic_json/empty/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/empty/#complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity.","title":"Complexity"},{"location":"api/basic_json/empty/#possible-implementation","text":"bool empty () const noexcept { return size () == 0 ; }","title":"Possible implementation"},{"location":"api/basic_json/empty/#notes","text":"This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is false in the case of a string.","title":"Notes"},{"location":"api/basic_json/empty/#examples","text":"Example The following code uses empty() to check if a JSON object contains any elements. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call empty() std :: cout << std :: boolalpha ; std :: cout << j_null . empty () << '\\n' ; std :: cout << j_boolean . empty () << '\\n' ; std :: cout << j_number_integer . empty () << '\\n' ; std :: cout << j_number_float . empty () << '\\n' ; std :: cout << j_object . empty () << '\\n' ; std :: cout << j_object_empty . empty () << '\\n' ; std :: cout << j_array . empty () << '\\n' ; std :: cout << j_array_empty . empty () << '\\n' ; std :: cout << j_string . empty () << '\\n' ; } Output: true false false false false true false true false","title":"Examples"},{"location":"api/basic_json/empty/#version-history","text":"Added in version 1.0.0. Extended to return false for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/end/","text":"nlohmann::basic_json:: end \u00b6 iterator end () noexcept ; const_iterator end () const noexcept ; Returns an iterator to one past the last element. Return value \u00b6 iterator one past the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for end() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: iterator it = array . end (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"end"},{"location":"api/basic_json/end/#nlohmannbasic_jsonend","text":"iterator end () noexcept ; const_iterator end () const noexcept ; Returns an iterator to one past the last element.","title":"nlohmann::basic_json::end"},{"location":"api/basic_json/end/#return-value","text":"iterator one past the last element","title":"Return value"},{"location":"api/basic_json/end/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/end/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/end/#examples","text":"Example The following code shows an example for end() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to one past the last element json :: iterator it = array . end (); // decrement the iterator to point to the last element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/end/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/erase/","text":"nlohmann::basic_json:: erase \u00b6 // (1) iterator erase ( iterator pos ); const_iterator erase ( const_iterator pos ); // (2) iterator erase ( iterator first , iterator last ); const_iterator erase ( const_iterator first , const_iterator last ); // (3) size_type erase ( const typename object_t :: key_type & key ); // (4) template < typename KeyType > size_type erase ( KeyType && key ); // (5) void erase ( const size_type idx ); 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. Template parameters \u00b6 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). Parameters \u00b6 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 Return value \u00b6 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). See 3. (none) Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\" Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\" Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin() ); example: \"iterator out of range\" 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\" Complexity \u00b6 The complexity depends on the type: objects: amortized constant arrays: linear in distance between pos and the end of the container strings and binary: linear in the length of the member other types: constant The complexity depends on the type: objects: log(size()) + std::distance(first, last) arrays: linear in the distance between first and last , plus linear in the distance between last and end of the container strings and binary: linear in the length of the member other types: constant log(size()) + count(key) log(size()) + count(key) Linear in distance between idx and the end of the container. Notes \u00b6 Invalidates iterators and references at or after the point of the erase , including the end() iterator. (none) References and iterators to the erased elements are invalidated. Other references and iterators are not affected. See 3. (none) Examples \u00b6 Example: (1) remove element given an iterator The example shows the effect of erase() for different JSON types using an iterator. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin ()); j_number_integer . erase ( j_number_integer . begin ()); j_number_float . erase ( j_number_float . begin ()); j_object . erase ( j_object . find ( \"two\" )); j_array . erase ( j_array . begin () + 2 ); j_string . erase ( j_string . begin ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 2 , 8 , 16 ] null Example: (2) remove elements given an iterator range The example shows the effect of erase() for different JSON types using an iterator range. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin (), j_boolean . end ()); j_number_integer . erase ( j_number_integer . begin (), j_number_integer . end ()); j_number_float . erase ( j_number_float . begin (), j_number_float . end ()); j_object . erase ( j_object . find ( \"two\" ), j_object . end ()); j_array . erase ( j_array . begin () + 1 , j_array . begin () + 3 ); j_string . erase ( j_string . begin (), j_string . end ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 8 , 16 ] null Example: (3) remove element from a JSON object given a key The example shows the effect of erase() for different JSON types using an object key. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" ); auto count_three = j_object . erase ( \"three\" ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (4) remove element from a JSON object given a key using string_view The example shows the effect of erase() for different JSON types using an object key. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" sv ); auto count_three = j_object . erase ( \"three\" sv ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (5) remove element from a JSON array given an index The example shows the effect of erase() using an array index. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j_array = { 0 , 1 , 2 , 3 , 4 , 5 }; // call erase() j_array . erase ( 2 ); // print values std :: cout << j_array << '\\n' ; } Output: [ 0 , 1 , 3 , 4 , 5 ] Version history \u00b6 Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 1.0.0.","title":"erase"},{"location":"api/basic_json/erase/#nlohmannbasic_jsonerase","text":"// (1) iterator erase ( iterator pos ); const_iterator erase ( const_iterator pos ); // (2) iterator erase ( iterator first , iterator last ); const_iterator erase ( const_iterator first , const_iterator last ); // (3) size_type erase ( const typename object_t :: key_type & key ); // (4) template < typename KeyType > size_type erase ( KeyType && key ); // (5) void erase ( const size_type idx ); 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.","title":"nlohmann::basic_json::erase"},{"location":"api/basic_json/erase/#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).","title":"Template parameters"},{"location":"api/basic_json/erase/#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","title":"Parameters"},{"location":"api/basic_json/erase/#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). See 3. (none)","title":"Return value"},{"location":"api/basic_json/erase/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/erase/#exceptions","text":"The function can throw the following exceptions: Throws type_error.307 if called on a null value; example: \"cannot use erase() with null\" Throws invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: \"iterator does not fit current value\" Throws invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not begin() ); example: \"iterator out of range\" 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\"","title":"Exceptions"},{"location":"api/basic_json/erase/#complexity","text":"The complexity depends on the type: objects: amortized constant arrays: linear in distance between pos and the end of the container strings and binary: linear in the length of the member other types: constant The complexity depends on the type: objects: log(size()) + std::distance(first, last) arrays: linear in the distance between first and last , plus linear in the distance between last and end of the container strings and binary: linear in the length of the member other types: constant log(size()) + count(key) log(size()) + count(key) Linear in distance between idx and the end of the container.","title":"Complexity"},{"location":"api/basic_json/erase/#notes","text":"Invalidates iterators and references at or after the point of the erase , including the end() iterator. (none) References and iterators to the erased elements are invalidated. Other references and iterators are not affected. See 3. (none)","title":"Notes"},{"location":"api/basic_json/erase/#examples","text":"Example: (1) remove element given an iterator The example shows the effect of erase() for different JSON types using an iterator. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin ()); j_number_integer . erase ( j_number_integer . begin ()); j_number_float . erase ( j_number_float . begin ()); j_object . erase ( j_object . find ( \"two\" )); j_array . erase ( j_array . begin () + 2 ); j_string . erase ( j_string . begin ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 2 , 8 , 16 ] null Example: (2) remove elements given an iterator range The example shows the effect of erase() for different JSON types using an iterator range. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call erase() j_boolean . erase ( j_boolean . begin (), j_boolean . end ()); j_number_integer . erase ( j_number_integer . begin (), j_number_integer . end ()); j_number_float . erase ( j_number_float . begin (), j_number_float . end ()); j_object . erase ( j_object . find ( \"two\" ), j_object . end ()); j_array . erase ( j_array . begin () + 1 , j_array . begin () + 3 ); j_string . erase ( j_string . begin (), j_string . end ()); // print values std :: cout << j_boolean << '\\n' ; std :: cout << j_number_integer << '\\n' ; std :: cout << j_number_float << '\\n' ; std :: cout << j_object << '\\n' ; std :: cout << j_array << '\\n' ; std :: cout << j_string << '\\n' ; } Output: null null null { \"one\" : 1 } [ 1 , 8 , 16 ] null Example: (3) remove element from a JSON object given a key The example shows the effect of erase() for different JSON types using an object key. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" ); auto count_three = j_object . erase ( \"three\" ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (4) remove element from a JSON object given a key using string_view The example shows the effect of erase() for different JSON types using an object key. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call erase() auto count_one = j_object . erase ( \"one\" sv ); auto count_three = j_object . erase ( \"three\" sv ); // print values std :: cout << j_object << '\\n' ; std :: cout << count_one << \" \" << count_three << '\\n' ; } Output: { \"two\" : 2 } 1 0 Example: (5) remove element from a JSON array given an index The example shows the effect of erase() using an array index. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json j_array = { 0 , 1 , 2 , 3 , 4 , 5 }; // call erase() j_array . erase ( 2 ); // print values std :: cout << j_array << '\\n' ; } Output: [ 0 , 1 , 3 , 4 , 5 ]","title":"Examples"},{"location":"api/basic_json/erase/#version-history","text":"Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added support for binary types in version 3.8.0. Added in version 1.0.0. Added in version 3.11.0. Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/error_handler_t/","text":"nlohmann::basic_json:: error_handler_t \u00b6 enum class error_handler_t { strict , replace , ignore }; 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 Examples \u00b6 Example The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence. #include #include using json = nlohmann :: json ; int main () { // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\" Version history \u00b6 Added in version 3.4.0.","title":"error_handler_t"},{"location":"api/basic_json/error_handler_t/#nlohmannbasic_jsonerror_handler_t","text":"enum class error_handler_t { strict , replace , ignore }; 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","title":"nlohmann::basic_json::error_handler_t"},{"location":"api/basic_json/error_handler_t/#examples","text":"Example The example below shows how the different values of the error_handler_t influence the behavior of dump when reading serializing an invalid UTF-8 sequence. #include #include using json = nlohmann :: json ; int main () { // create JSON value with invalid UTF-8 byte sequence json j_invalid = \"\u00e4 \\xA9 \u00fc\" ; try { std :: cout << j_invalid . dump () << std :: endl ; } catch ( const json :: type_error & e ) { std :: cout << e . what () << std :: endl ; } std :: cout << \"string with replaced invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: replace ) << \" \\n string with ignored invalid characters: \" << j_invalid . dump ( -1 , ' ' , false , json :: error_handler_t :: ignore ) << '\\n' ; } Output: [ jso n .excep t io n . t ype_error. 316 ] i n valid UTF -8 by te a t i n dex 2 : 0 xA 9 s tr i n g wi t h replaced i n valid charac ters : \"\u00e4\ufffd\u00fc\" s tr i n g wi t h ig n ored i n valid charac ters : \"\u00e4\u00fc\"","title":"Examples"},{"location":"api/basic_json/error_handler_t/#version-history","text":"Added in version 3.4.0.","title":"Version history"},{"location":"api/basic_json/exception/","text":"nlohmann::basic_json:: exception \u00b6 class exception : public std :: exception ; This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions, see example below. Subclasses: 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 Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Notes \u00b6 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. Examples \u00b6 Example The following code shows how arbitrary library exceptions can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for a non-existing key json j = {{ \"foo\" , \"bar\" }}; json k = j . at ( \"non-existing\" ); } catch ( const json :: exception & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' n o n -e xis t i n g' n o t f ou n d excep t io n id : 403 See also \u00b6 List of exceptions Version history \u00b6 Since version 3.0.0.","title":"exception"},{"location":"api/basic_json/exception/#nlohmannbasic_jsonexception","text":"class exception : public std :: exception ; This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions, see example below. Subclasses: 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","title":"nlohmann::basic_json::exception"},{"location":"api/basic_json/exception/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/exception/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/exception/#notes","text":"To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.","title":"Notes"},{"location":"api/basic_json/exception/#examples","text":"Example The following code shows how arbitrary library exceptions can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for a non-existing key json j = {{ \"foo\" , \"bar\" }}; json k = j . at ( \"non-existing\" ); } catch ( const json :: exception & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key ' n o n -e xis t i n g' n o t f ou n d excep t io n id : 403","title":"Examples"},{"location":"api/basic_json/exception/#see-also","text":"List of exceptions","title":"See also"},{"location":"api/basic_json/exception/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/find/","text":"nlohmann::basic_json:: find \u00b6 // (1) iterator find ( const typename object_t :: key_type & key ); const_iterator find ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > iterator find ( KeyType && key ); template < typename KeyType > const_iterator find ( KeyType && key ) const ; 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. Template parameters \u00b6 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). Parameters \u00b6 key (in) key value of the element to search for. Return value \u00b6 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. Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Complexity \u00b6 Logarithmic in the size of the JSON object. Notes \u00b6 This method always returns end() when executed on a JSON type that is not an object. Examples \u00b6 Example: (1) find object element by key The example shows how find() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" ); auto it_three = j_object . find ( \"three\" ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false Example: (2) find object element by key using string_view The example shows how find() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" sv ); auto it_three = j_object . find ( \"three\" sv ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false See also \u00b6 contains checks whether a key exists Version history \u00b6 Added in version 3.11.0. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.","title":"find"},{"location":"api/basic_json/find/#nlohmannbasic_jsonfind","text":"// (1) iterator find ( const typename object_t :: key_type & key ); const_iterator find ( const typename object_t :: key_type & key ) const ; // (2) template < typename KeyType > iterator find ( KeyType && key ); template < typename KeyType > const_iterator find ( KeyType && key ) const ; 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.","title":"nlohmann::basic_json::find"},{"location":"api/basic_json/find/#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).","title":"Template parameters"},{"location":"api/basic_json/find/#parameters","text":"key (in) key value of the element to search for.","title":"Parameters"},{"location":"api/basic_json/find/#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.","title":"Return value"},{"location":"api/basic_json/find/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/find/#complexity","text":"Logarithmic in the size of the JSON object.","title":"Complexity"},{"location":"api/basic_json/find/#notes","text":"This method always returns end() when executed on a JSON type that is not an object.","title":"Notes"},{"location":"api/basic_json/find/#examples","text":"Example: (1) find object element by key The example shows how find() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" ); auto it_three = j_object . find ( \"three\" ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false Example: (2) find object element by key using string_view The example shows how find() is used. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; // call find auto it_two = j_object . find ( \"two\" sv ); auto it_three = j_object . find ( \"three\" sv ); // print values std :: cout << std :: boolalpha ; std :: cout << \" \\\" two \\\" was found: \" << ( it_two != j_object . end ()) << '\\n' ; std :: cout << \"value at key \\\" two \\\" : \" << * it_two << '\\n' ; std :: cout << \" \\\" three \\\" was found: \" << ( it_three != j_object . end ()) << '\\n' ; } Output: \"two\" was f ou n d : true value a t key \"two\" : 2 \"three\" was f ou n d : false","title":"Examples"},{"location":"api/basic_json/find/#see-also","text":"contains checks whether a key exists","title":"See also"},{"location":"api/basic_json/find/#version-history","text":"Added in version 3.11.0. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/flatten/","text":"nlohmann::basic_json:: flatten \u00b6 basic_json flatten () const ; 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. Return value \u00b6 an object that maps JSON pointers to primitive values Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Complexity \u00b6 Linear in the size the JSON value. Notes \u00b6 Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function. Examples \u00b6 Example The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // call flatten() std :: cout << std :: setw ( 4 ) << j . flatten () << '\\n' ; } Output: { \"/answer/everything\" : 42 , \"/happy\" : true , \"/list/0\" : 1 , \"/list/1\" : 0 , \"/list/2\" : 2 , \"/name\" : \"Niels\" , \"/nothing\" : null , \"/object/currency\" : \"USD\" , \"/object/value\" : 42.99 , \"/pi\" : 3.141 } See also \u00b6 unflatten the reverse function Version history \u00b6 Added in version 2.0.0.","title":"flatten"},{"location":"api/basic_json/flatten/#nlohmannbasic_jsonflatten","text":"basic_json flatten () const ; 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.","title":"nlohmann::basic_json::flatten"},{"location":"api/basic_json/flatten/#return-value","text":"an object that maps JSON pointers to primitive values","title":"Return value"},{"location":"api/basic_json/flatten/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/flatten/#complexity","text":"Linear in the size the JSON value.","title":"Complexity"},{"location":"api/basic_json/flatten/#notes","text":"Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.","title":"Notes"},{"location":"api/basic_json/flatten/#examples","text":"Example The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j = { { \"pi\" , 3.141 }, { \"happy\" , true }, { \"name\" , \"Niels\" }, { \"nothing\" , nullptr }, { \"answer\" , { { \"everything\" , 42 } } }, { \"list\" , { 1 , 0 , 2 }}, { \"object\" , { { \"currency\" , \"USD\" }, { \"value\" , 42.99 } } } }; // call flatten() std :: cout << std :: setw ( 4 ) << j . flatten () << '\\n' ; } Output: { \"/answer/everything\" : 42 , \"/happy\" : true , \"/list/0\" : 1 , \"/list/1\" : 0 , \"/list/2\" : 2 , \"/name\" : \"Niels\" , \"/nothing\" : null , \"/object/currency\" : \"USD\" , \"/object/value\" : 42.99 , \"/pi\" : 3.141 }","title":"Examples"},{"location":"api/basic_json/flatten/#see-also","text":"unflatten the reverse function","title":"See also"},{"location":"api/basic_json/flatten/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/from_bjdata/","text":"nlohmann::basic_json:: from_bjdata \u00b6 // (1) template < typename InputType > static basic_json from_bjdata ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bjdata ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in BJData format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 3.11.0.","title":"from_bjdata"},{"location":"api/basic_json/from_bjdata/#nlohmannbasic_jsonfrom_bjdata","text":"// (1) template < typename InputType > static basic_json from_bjdata ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bjdata ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_bjdata"},{"location":"api/basic_json/from_bjdata/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_bjdata/#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)","title":"Parameters"},{"location":"api/basic_json/from_bjdata/#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 .","title":"Return value"},{"location":"api/basic_json/from_bjdata/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_bjdata/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully","title":"Exceptions"},{"location":"api/basic_json/from_bjdata/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_bjdata/#examples","text":"Example The example shows the deserialization of a byte vector in BJData format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_bjdata/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/from_bson/","text":"nlohmann::basic_json:: from_bson \u00b6 // (1) template < typename InputType > static basic_json from_bson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.114 if an unsupported BSON record type is encountered. Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in BSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } See also \u00b6 BSON specification to_bson for the analogous serialization from_cbor for the related CBOR format from_msgpack for the related MessagePack format from_ubjson for the related UBJSON format Version history \u00b6 Added in version 3.4.0. Deprecation 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.","title":"from_bson"},{"location":"api/basic_json/from_bson/#nlohmannbasic_jsonfrom_bson","text":"// (1) template < typename InputType > static basic_json from_bson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_bson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_bson"},{"location":"api/basic_json/from_bson/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_bson/#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)","title":"Parameters"},{"location":"api/basic_json/from_bson/#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 .","title":"Return value"},{"location":"api/basic_json/from_bson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_bson/#exceptions","text":"Throws parse_error.114 if an unsupported BSON record type is encountered.","title":"Exceptions"},{"location":"api/basic_json/from_bson/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_bson/#examples","text":"Example The example shows the deserialization of a byte vector in BSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_bson/#see-also","text":"BSON specification to_bson for the analogous serialization from_cbor for the related CBOR format from_msgpack for the related MessagePack format from_ubjson for the related UBJSON format","title":"See also"},{"location":"api/basic_json/from_bson/#version-history","text":"Added in version 3.4.0. Deprecation 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.","title":"Version history"},{"location":"api/basic_json/from_cbor/","text":"nlohmann::basic_json:: from_cbor \u00b6 // (1) template < typename InputType > static basic_json from_cbor ( InputType && i , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); // (2) template < typename IteratorType > static basic_json from_cbor ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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 Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from CBOR were used in the given input or if the input is not valid CBOR Throws parse_error.113 if a string was expected as map key, but not found Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in CBOR format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"from_cbor"},{"location":"api/basic_json/from_cbor/#nlohmannbasic_jsonfrom_cbor","text":"// (1) template < typename InputType > static basic_json from_cbor ( InputType && i , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); // (2) template < typename IteratorType > static basic_json from_cbor ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true , const cbor_tag_handler_t tag_handler = cbor_tag_handler_t :: error ); Deserializes a given input to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_cbor"},{"location":"api/basic_json/from_cbor/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_cbor/#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","title":"Parameters"},{"location":"api/basic_json/from_cbor/#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 .","title":"Return value"},{"location":"api/basic_json/from_cbor/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_cbor/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from CBOR were used in the given input or if the input is not valid CBOR Throws parse_error.113 if a string was expected as map key, but not found","title":"Exceptions"},{"location":"api/basic_json/from_cbor/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_cbor/#examples","text":"Example The example shows the deserialization of a byte vector in CBOR format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_cbor/#version-history","text":"Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"Version history"},{"location":"api/basic_json/from_msgpack/","text":"nlohmann::basic_json:: from_msgpack \u00b6 // (1) template < typename InputType > static basic_json from_msgpack ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_msgpack ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the MessagePack serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from MessagePack were used in the given input or if the input is not valid MessagePack Throws parse_error.113 if a string was expected as map key, but not found Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in MessagePack format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"from_msgpack"},{"location":"api/basic_json/from_msgpack/#nlohmannbasic_jsonfrom_msgpack","text":"// (1) template < typename InputType > static basic_json from_msgpack ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_msgpack ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the MessagePack serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_msgpack"},{"location":"api/basic_json/from_msgpack/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_msgpack/#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)","title":"Parameters"},{"location":"api/basic_json/from_msgpack/#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 .","title":"Return value"},{"location":"api/basic_json/from_msgpack/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_msgpack/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if unsupported features from MessagePack were used in the given input or if the input is not valid MessagePack Throws parse_error.113 if a string was expected as map key, but not found","title":"Exceptions"},{"location":"api/basic_json/from_msgpack/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_msgpack/#examples","text":"Example The example shows the deserialization of a byte vector in MessagePack format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_msgpack/#version-history","text":"Added in version 2.0.9. Parameter start_index since version 2.1.1. 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.","title":"Version history"},{"location":"api/basic_json/from_ubjson/","text":"nlohmann::basic_json:: from_ubjson \u00b6 // (1) template < typename InputType > static basic_json from_ubjson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_ubjson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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) Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully Complexity \u00b6 Linear in the size of the input. Examples \u00b6 Example The example shows the deserialization of a byte vector in UBJSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 } Version history \u00b6 Added in version 3.1.0. 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.","title":"from_ubjson"},{"location":"api/basic_json/from_ubjson/#nlohmannbasic_jsonfrom_ubjson","text":"// (1) template < typename InputType > static basic_json from_ubjson ( InputType && i , const bool strict = true , const bool allow_exceptions = true ); // (2) template < typename IteratorType > static basic_json from_ubjson ( IteratorType first , IteratorType last , const bool strict = true , const bool allow_exceptions = true ); Deserializes a given input to a JSON value using the UBJSON (Universal Binary JSON) serialization format. Reads from a compatible input. Reads from an iterator range. The exact mapping and its limitations is described on a dedicated page .","title":"nlohmann::basic_json::from_ubjson"},{"location":"api/basic_json/from_ubjson/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/from_ubjson/#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)","title":"Parameters"},{"location":"api/basic_json/from_ubjson/#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 .","title":"Return value"},{"location":"api/basic_json/from_ubjson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/from_ubjson/#exceptions","text":"Throws parse_error.110 if the given input ends prematurely or the end of file was not reached when strict was set to true Throws parse_error.112 if a parse error occurs Throws parse_error.113 if a string could not be parsed successfully","title":"Exceptions"},{"location":"api/basic_json/from_ubjson/#complexity","text":"Linear in the size of the input.","title":"Complexity"},{"location":"api/basic_json/from_ubjson/#examples","text":"Example The example shows the deserialization of a byte vector in UBJSON format to a JSON value. #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Examples"},{"location":"api/basic_json/from_ubjson/#version-history","text":"Added in version 3.1.0. 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.","title":"Version history"},{"location":"api/basic_json/front/","text":"nlohmann::basic_json:: front \u00b6 reference front (); const_reference front () const ; Returns a reference to the first element in the container. For a JSON container c , the expression c . front () is equivalent to * c . begin () . Return value \u00b6 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. Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 If the JSON value is null , exception invalid_iterator.214 is thrown. Complexity \u00b6 Constant. Notes \u00b6 Precondition The array or object must not be empty. Calling front on an empty array or object yields undefined behavior. Examples \u00b6 Example The following code shows an example for front() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call front() //std::cout << j_null.front() << '\\n'; // would throw std :: cout << j_boolean . front () << '\\n' ; std :: cout << j_number_integer . front () << '\\n' ; std :: cout << j_number_float . front () << '\\n' ; std :: cout << j_object . front () << '\\n' ; //std::cout << j_object_empty.front() << '\\n'; // undefined behavior std :: cout << j_array . front () << '\\n' ; //std::cout << j_array_empty.front() << '\\n'; // undefined behavior std :: cout << j_string . front () << '\\n' ; } Output: true 17 23.42 1 1 \"Hello, world\" See also \u00b6 back to access the last element Version history \u00b6 Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"front"},{"location":"api/basic_json/front/#nlohmannbasic_jsonfront","text":"reference front (); const_reference front () const ; Returns a reference to the first element in the container. For a JSON container c , the expression c . front () is equivalent to * c . begin () .","title":"nlohmann::basic_json::front"},{"location":"api/basic_json/front/#return-value","text":"In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned.","title":"Return value"},{"location":"api/basic_json/front/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/front/#exceptions","text":"If the JSON value is null , exception invalid_iterator.214 is thrown.","title":"Exceptions"},{"location":"api/basic_json/front/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/front/#notes","text":"Precondition The array or object must not be empty. Calling front on an empty array or object yields undefined behavior.","title":"Notes"},{"location":"api/basic_json/front/#examples","text":"Example The following code shows an example for front() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call front() //std::cout << j_null.front() << '\\n'; // would throw std :: cout << j_boolean . front () << '\\n' ; std :: cout << j_number_integer . front () << '\\n' ; std :: cout << j_number_float . front () << '\\n' ; std :: cout << j_object . front () << '\\n' ; //std::cout << j_object_empty.front() << '\\n'; // undefined behavior std :: cout << j_array . front () << '\\n' ; //std::cout << j_array_empty.front() << '\\n'; // undefined behavior std :: cout << j_string . front () << '\\n' ; } Output: true 17 23.42 1 1 \"Hello, world\"","title":"Examples"},{"location":"api/basic_json/front/#see-also","text":"back to access the last element","title":"See also"},{"location":"api/basic_json/front/#version-history","text":"Added in version 1.0.0. Adjusted code to return reference to binary values in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get/","text":"nlohmann::basic_json:: get \u00b6 // (1) template < typename ValueType > ValueType get () const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), std :: declval < ValueType &> ()))); // (2) template < typename BasicJsonType > BasicJsonType get () const ; // (3) template < typename PointerType > PointerType get_ptr (); template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; 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 from_json() method. The function is equivalent to executing ValueType ret ; JSONSerializer < ValueType >:: from_json ( * this , ret ); return ret ; This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&) , and json_serializer does not have a from_json() method of the form ValueType from_json(const basic_json&) If the type is not CopyConstructible and not DefaultConstructible , the value is converted by calling the json_serializer from_json() method. The function is then equivalent to executing return JSONSerializer < ValueTypeCV >:: from_json ( * this ); This overload is chosen if: ValueType is not basic_json and json_serializer has a from_json() method of the form ValueType from_json(const basic_json&) If json_serializer has both overloads of from_json() , the latter one is chosen. Overload for basic_json specializations. The function is equivalent to executing return * this ; Explicit pointer access to the internally stored JSON value. No copies are made. Template parameters \u00b6 ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t , object_t , string_t , boolean_t , number_integer_t , or number_unsigned_t , number_float_t , or binary_t . Other types will not compile. Return value \u00b6 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 Exceptions \u00b6 Depends on what json_serializer from_json() method throws Notes \u00b6 Undefined behavior Writing data to the pointee (overload 3) of the result yields an undefined state. Examples \u00b6 Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use explicit conversions auto v1 = json_types [ \"boolean\" ]. template get < bool > (); auto v2 = json_types [ \"number\" ][ \"integer\" ]. template get < int > (); auto v3 = json_types [ \"number\" ][ \"integer\" ]. template get < short > (); auto v4 = json_types [ \"number\" ][ \"floating-point\" ]. template get < float > (); auto v5 = json_types [ \"number\" ][ \"floating-point\" ]. template get < int > (); auto v6 = json_types [ \"string\" ]. template get < std :: string > (); auto v7 = json_types [ \"array\" ]. template get < std :: vector < short >> (); auto v8 = json_types . template get < std :: unordered_map < std :: string , json >> (); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . template get < const json :: number_integer_t *> (); auto p2 = value . template get < json :: number_integer_t *> (); auto p3 = value . template get < json :: number_integer_t * const > (); auto p4 = value . template get < const json :: number_integer_t * const > (); auto p5 = value . template get < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true Version history \u00b6 Since version 2.1.0. Since version 2.1.0. Extended to work with other specializations of basic_json in version 3.2.0. Since version 1.0.0.","title":"get"},{"location":"api/basic_json/get/#nlohmannbasic_jsonget","text":"// (1) template < typename ValueType > ValueType get () const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), std :: declval < ValueType &> ()))); // (2) template < typename BasicJsonType > BasicJsonType get () const ; // (3) template < typename PointerType > PointerType get_ptr (); template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; 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 from_json() method. The function is equivalent to executing ValueType ret ; JSONSerializer < ValueType >:: from_json ( * this , ret ); return ret ; This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&) , and json_serializer does not have a from_json() method of the form ValueType from_json(const basic_json&) If the type is not CopyConstructible and not DefaultConstructible , the value is converted by calling the json_serializer from_json() method. The function is then equivalent to executing return JSONSerializer < ValueTypeCV >:: from_json ( * this ); This overload is chosen if: ValueType is not basic_json and json_serializer has a from_json() method of the form ValueType from_json(const basic_json&) If json_serializer has both overloads of from_json() , the latter one is chosen. Overload for basic_json specializations. The function is equivalent to executing return * this ; Explicit pointer access to the internally stored JSON value. No copies are made.","title":"nlohmann::basic_json::get"},{"location":"api/basic_json/get/#template-parameters","text":"ValueType the value type to return BasicJsonType a specialization of basic_json PointerType pointer type; must be a pointer to array_t , object_t , string_t , boolean_t , number_integer_t , or number_unsigned_t , number_float_t , or binary_t . Other types will not compile.","title":"Template parameters"},{"location":"api/basic_json/get/#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","title":"Return value"},{"location":"api/basic_json/get/#exceptions","text":"Depends on what json_serializer from_json() method throws","title":"Exceptions"},{"location":"api/basic_json/get/#notes","text":"Undefined behavior Writing data to the pointee (overload 3) of the result yields an undefined state.","title":"Notes"},{"location":"api/basic_json/get/#examples","text":"Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use explicit conversions auto v1 = json_types [ \"boolean\" ]. template get < bool > (); auto v2 = json_types [ \"number\" ][ \"integer\" ]. template get < int > (); auto v3 = json_types [ \"number\" ][ \"integer\" ]. template get < short > (); auto v4 = json_types [ \"number\" ][ \"floating-point\" ]. template get < float > (); auto v5 = json_types [ \"number\" ][ \"floating-point\" ]. template get < int > (); auto v6 = json_types [ \"string\" ]. template get < std :: string > (); auto v7 = json_types [ \"array\" ]. template get < std :: vector < short >> (); auto v8 = json_types . template get < std :: unordered_map < std :: string , json >> (); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a #cpp nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . template get < const json :: number_integer_t *> (); auto p2 = value . template get < json :: number_integer_t *> (); auto p3 = value . template get < json :: number_integer_t * const > (); auto p4 = value . template get < const json :: number_integer_t * const > (); auto p5 = value . template get < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true","title":"Examples"},{"location":"api/basic_json/get/#version-history","text":"Since version 2.1.0. Since version 2.1.0. Extended to work with other specializations of basic_json in version 3.2.0. Since version 1.0.0.","title":"Version history"},{"location":"api/basic_json/get_allocator/","text":"nlohmann::basic_json:: get_allocator \u00b6 static allocator_type get_allocator (); Returns the allocator associated with the container. Return value \u00b6 associated allocator Examples \u00b6 Example The example shows how get_allocator() is used to created json values. #include #include using json = nlohmann :: json ; int main () { auto alloc = json :: get_allocator (); using traits_t = std :: allocator_traits < decltype ( alloc ) > ; json * j = traits_t :: allocate ( alloc , 1 ); traits_t :: construct ( alloc , j , \"Hello, world!\" ); std :: cout << * j << std :: endl ; traits_t :: destroy ( alloc , j ); traits_t :: deallocate ( alloc , j , 1 ); } Output: \"Hello, world!\" Version history \u00b6 Added in version 1.0.0.","title":"get_allocator"},{"location":"api/basic_json/get_allocator/#nlohmannbasic_jsonget_allocator","text":"static allocator_type get_allocator (); Returns the allocator associated with the container.","title":"nlohmann::basic_json::get_allocator"},{"location":"api/basic_json/get_allocator/#return-value","text":"associated allocator","title":"Return value"},{"location":"api/basic_json/get_allocator/#examples","text":"Example The example shows how get_allocator() is used to created json values. #include #include using json = nlohmann :: json ; int main () { auto alloc = json :: get_allocator (); using traits_t = std :: allocator_traits < decltype ( alloc ) > ; json * j = traits_t :: allocate ( alloc , 1 ); traits_t :: construct ( alloc , j , \"Hello, world!\" ); std :: cout << * j << std :: endl ; traits_t :: destroy ( alloc , j ); traits_t :: deallocate ( alloc , j , 1 ); } Output: \"Hello, world!\"","title":"Examples"},{"location":"api/basic_json/get_allocator/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/get_binary/","text":"nlohmann::basic_json:: get_binary \u00b6 binary_t & get_binary (); const binary_t & get_binary () const ; Returns a reference to the stored binary value. Return value \u00b6 Reference to binary value. Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 Throws type_error.302 if the value is not binary Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows how to query a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42 Version history \u00b6 Added in version 3.8.0.","title":"get_binary"},{"location":"api/basic_json/get_binary/#nlohmannbasic_jsonget_binary","text":"binary_t & get_binary (); const binary_t & get_binary () const ; Returns a reference to the stored binary value.","title":"nlohmann::basic_json::get_binary"},{"location":"api/basic_json/get_binary/#return-value","text":"Reference to binary value.","title":"Return value"},{"location":"api/basic_json/get_binary/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/get_binary/#exceptions","text":"Throws type_error.302 if the value is not binary","title":"Exceptions"},{"location":"api/basic_json/get_binary/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/get_binary/#examples","text":"Example The following code shows how to query a binary value. #include #include using json = nlohmann :: json ; int main () { // create a binary vector std :: vector < std :: uint8_t > vec = { 0xCA , 0xFE , 0xBA , 0xBE }; // create a binary JSON value with subtype 42 json j = json :: binary ( vec , 42 ); // output type and subtype std :: cout << \"type: \" << j . type_name () << \", subtype: \" << j . get_binary (). subtype () << std :: endl ; } Output: t ype : bi nar y , sub t ype : 42","title":"Examples"},{"location":"api/basic_json/get_binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get_ptr/","text":"nlohmann::basic_json:: get_ptr \u00b6 template < typename PointerType > PointerType get_ptr () noexcept ; template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; Implicit pointer access to the internally stored JSON value. No copies are made. Template parameters \u00b6 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. Return value \u00b6 pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Notes \u00b6 Undefined behavior Writing data to the pointee of the result yields an undefined state. Examples \u00b6 Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . get_ptr < const json :: number_integer_t *> (); auto p2 = value . get_ptr < json :: number_integer_t *> (); auto p3 = value . get_ptr < json :: number_integer_t * const > (); auto p4 = value . get_ptr < const json :: number_integer_t * const > (); auto p5 = value . get_ptr < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true Version history \u00b6 Added in version 1.0.0. Extended to binary types in version 3.8.0.","title":"get_ptr"},{"location":"api/basic_json/get_ptr/#nlohmannbasic_jsonget_ptr","text":"template < typename PointerType > PointerType get_ptr () noexcept ; template < typename PointerType > constexpr const PointerType get_ptr () const noexcept ; Implicit pointer access to the internally stored JSON value. No copies are made.","title":"nlohmann::basic_json::get_ptr"},{"location":"api/basic_json/get_ptr/#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.","title":"Template parameters"},{"location":"api/basic_json/get_ptr/#return-value","text":"pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; nullptr otherwise","title":"Return value"},{"location":"api/basic_json/get_ptr/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/get_ptr/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/get_ptr/#notes","text":"Undefined behavior Writing data to the pointee of the result yields an undefined state.","title":"Notes"},{"location":"api/basic_json/get_ptr/#examples","text":"Example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match. #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting pointers auto p1 = value . get_ptr < const json :: number_integer_t *> (); auto p2 = value . get_ptr < json :: number_integer_t *> (); auto p3 = value . get_ptr < json :: number_integer_t * const > (); auto p4 = value . get_ptr < const json :: number_integer_t * const > (); auto p5 = value . get_ptr < json :: number_float_t *> (); // print the pointees std :: cout << * p1 << ' ' << * p2 << ' ' << * p3 << ' ' << * p4 << '\\n' ; std :: cout << std :: boolalpha << ( p5 == nullptr ) << '\\n' ; } Output: 17 17 17 17 true","title":"Examples"},{"location":"api/basic_json/get_ptr/#version-history","text":"Added in version 1.0.0. Extended to binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get_ref/","text":"nlohmann::basic_json:: get_ref \u00b6 template < typename ReferenceType > ReferenceType get_ref (); template < typename ReferenceType > const ReferenceType get_ref () const ; Implicit reference access to the internally stored JSON value. No copies are made. Template parameters \u00b6 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. Return value \u00b6 reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws type_error.303 otherwise Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 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\" . Complexity \u00b6 Constant. Notes \u00b6 Undefined behavior Writing data to the referee of the result yields an undefined state. Examples \u00b6 Example The example shows several calls to get_ref() . #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting references auto r1 = value . get_ref < const json :: number_integer_t &> (); auto r2 = value . get_ref < json :: number_integer_t &> (); // print the values std :: cout << r1 << ' ' << r2 << '\\n' ; // incompatible type throws exception try { auto r3 = value . get_ref < json :: number_float_t &> (); } catch ( const json :: type_error & ex ) { std :: cout << ex . what () << '\\n' ; } } Output: 17 17 [ jso n .excep t io n . t ype_error. 303 ] i n compa t ible Re feren ceType f or ge t _re f , ac tual t ype is nu mber Version history \u00b6 Added in version 1.1.0. Extended to binary types in version 3.8.0.","title":"get_ref"},{"location":"api/basic_json/get_ref/#nlohmannbasic_jsonget_ref","text":"template < typename ReferenceType > ReferenceType get_ref (); template < typename ReferenceType > const ReferenceType get_ref () const ; Implicit reference access to the internally stored JSON value. No copies are made.","title":"nlohmann::basic_json::get_ref"},{"location":"api/basic_json/get_ref/#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.","title":"Template parameters"},{"location":"api/basic_json/get_ref/#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","title":"Return value"},{"location":"api/basic_json/get_ref/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/get_ref/#exceptions","text":"Throws type_error.303 if the requested reference type does not match the stored JSON value type; example: \"incompatible ReferenceType for get_ref, actual type is binary\" .","title":"Exceptions"},{"location":"api/basic_json/get_ref/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/get_ref/#notes","text":"Undefined behavior Writing data to the referee of the result yields an undefined state.","title":"Notes"},{"location":"api/basic_json/get_ref/#examples","text":"Example The example shows several calls to get_ref() . #include #include using json = nlohmann :: json ; int main () { // create a JSON number json value = 17 ; // explicitly getting references auto r1 = value . get_ref < const json :: number_integer_t &> (); auto r2 = value . get_ref < json :: number_integer_t &> (); // print the values std :: cout << r1 << ' ' << r2 << '\\n' ; // incompatible type throws exception try { auto r3 = value . get_ref < json :: number_float_t &> (); } catch ( const json :: type_error & ex ) { std :: cout << ex . what () << '\\n' ; } } Output: 17 17 [ jso n .excep t io n . t ype_error. 303 ] i n compa t ible Re feren ceType f or ge t _re f , ac tual t ype is nu mber","title":"Examples"},{"location":"api/basic_json/get_ref/#version-history","text":"Added in version 1.1.0. Extended to binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/get_to/","text":"nlohmann::basic_json:: get_to \u00b6 template < typename ValueType > ValueType & get_to ( ValueType & v ) const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), v ))); Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer from_json() method. The function is equivalent to executing ValueType v ; JSONSerializer < ValueType >:: from_json ( * this , v ); This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&) Template parameters \u00b6 ValueType the value type to return Return value \u00b6 the input parameter, allowing chaining calls Exceptions \u00b6 Depends on what json_serializer from_json() method throws Examples \u00b6 Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std :: vector < short > , (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; bool v1 ; int v2 ; short v3 ; float v4 ; int v5 ; std :: string v6 ; std :: vector < short > v7 ; std :: unordered_map < std :: string , json > v8 ; // use explicit conversions json_types [ \"boolean\" ]. get_to ( v1 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v2 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v3 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v4 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v5 ); json_types [ \"string\" ]. get_to ( v6 ); json_types [ \"array\" ]. get_to ( v7 ); json_types . get_to ( v8 ); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] Version history \u00b6 Since version 3.3.0.","title":"get_to"},{"location":"api/basic_json/get_to/#nlohmannbasic_jsonget_to","text":"template < typename ValueType > ValueType & get_to ( ValueType & v ) const noexcept ( noexcept ( JSONSerializer < ValueType >:: from_json ( std :: declval < const basic_json_t &> (), v ))); Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the json_serializer from_json() method. The function is equivalent to executing ValueType v ; JSONSerializer < ValueType >:: from_json ( * this , v ); This overload is chosen if: ValueType is not basic_json , json_serializer has a from_json() method of the form void from_json(const basic_json&, ValueType&)","title":"nlohmann::basic_json::get_to"},{"location":"api/basic_json/get_to/#template-parameters","text":"ValueType the value type to return","title":"Template parameters"},{"location":"api/basic_json/get_to/#return-value","text":"the input parameter, allowing chaining calls","title":"Return value"},{"location":"api/basic_json/get_to/#exceptions","text":"Depends on what json_serializer from_json() method throws","title":"Exceptions"},{"location":"api/basic_json/get_to/#examples","text":"Example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std :: vector < short > , (3) A JSON object can be converted to C++ associative containers such as #cpp std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; bool v1 ; int v2 ; short v3 ; float v4 ; int v5 ; std :: string v6 ; std :: vector < short > v7 ; std :: unordered_map < std :: string , json > v8 ; // use explicit conversions json_types [ \"boolean\" ]. get_to ( v1 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v2 ); json_types [ \"number\" ][ \"integer\" ]. get_to ( v3 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v4 ); json_types [ \"number\" ][ \"floating-point\" ]. get_to ( v5 ); json_types [ \"string\" ]. get_to ( v6 ); json_types [ \"array\" ]. get_to ( v7 ); json_types . get_to ( v8 ); // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ]","title":"Examples"},{"location":"api/basic_json/get_to/#version-history","text":"Since version 3.3.0.","title":"Version history"},{"location":"api/basic_json/input_format_t/","text":"nlohmann::basic_json:: input_format_t \u00b6 enum class input_format_t { json , cbor , msgpack , ubjson , bson , bjdata }; This enumeration is used in the sax_parse function to choose the input format to parse: json JSON (JavaScript Object Notation) cbor CBOR (Concise Binary Object Representation) msgpack MessagePack ubjson UBJSON (Universal Binary JSON) bson BSON (Binary JSON) bjdata BJData (Binary JData) Examples \u00b6 Example The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true Version history \u00b6 Added in version 3.2.0.","title":"input_format_t"},{"location":"api/basic_json/input_format_t/#nlohmannbasic_jsoninput_format_t","text":"enum class input_format_t { json , cbor , msgpack , ubjson , bson , bjdata }; This enumeration is used in the sax_parse function to choose the input format to parse: json JSON (JavaScript Object Notation) cbor CBOR (Concise Binary Object Representation) msgpack MessagePack ubjson UBJSON (Universal Binary JSON) bson BSON (Binary JSON) bjdata BJData (Binary JData)","title":"nlohmann::basic_json::input_format_t"},{"location":"api/basic_json/input_format_t/#examples","text":"Example The example below shows how an input_format_t enum value is passed to sax_parse to set the input format to CBOR. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true","title":"Examples"},{"location":"api/basic_json/input_format_t/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/basic_json/insert/","text":"nlohmann::basic_json:: insert \u00b6 // (1) iterator insert ( const_iterator pos , const basic_json & val ); iterator insert ( const_iterator pos , basic_json && val ); // (2) iterator insert ( const_iterator pos , size_type cnt , const basic_json & val ); // (3) iterator insert ( const_iterator pos , const_iterator first , const_iterator last ); // (4) iterator insert ( const_iterator pos , initializer_list_t ilist ); // (5) void insert ( const_iterator first , const_iterator last ); Inserts element val into array before iterator pos . Inserts cnt copies of val into array before iterator pos . Inserts elements from range [first, last) into array before iterator pos . Inserts elements from initializer list ilist into array before iterator pos . Inserts elements from range [first, last) into object. Parameters \u00b6 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 Return value \u00b6 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 (none) Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 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\" 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\" Complexity \u00b6 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. Examples \u00b6 Example (1): insert element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 10 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 10 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 10 [ 1 , 2 , 10 , 3 , 4 ] Example (2): insert copies of element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 7 copies of number 7 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 7 , 7 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 7 , 7 , 7 , 7 , 7 , 7 , 7 , 3 , 4 ] Example (3): insert range of elements into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // create a JSON array to copy values from json v2 = { \"one\" , \"two\" , \"three\" , \"four\" }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), v2 . begin (), v2 . end ()); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: \"one\" [ 1 , 2 , 3 , 4 , \"one\" , \"two\" , \"three\" , \"four\" ] Example (4): insert elements from initializer list into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), { 7 , 8 , 9 }); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 3 , 4 , 7 , 8 , 9 ] Example (5): insert range of elements into object The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create two JSON objects json j1 = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; json j2 = {{ \"eleven\" , \"elf\" }, { \"seventeen\" , \"siebzehn\" }}; // output objects std :: cout << j1 << '\\n' ; std :: cout << j2 << '\\n' ; // insert range from j2 to j1 j1 . insert ( j2 . begin (), j2 . end ()); // output result of insert call std :: cout << j1 << '\\n' ; } Output: { \"one\" : \"eins\" , \"two\" : \"zwei\" } { \"eleven\" : \"elf\" , \"seventeen\" : \"siebzehn\" } { \"eleven\" : \"elf\" , \"one\" : \"eins\" , \"seventeen\" : \"siebzehn\" , \"two\" : \"zwei\" } Version history \u00b6 Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 3.0.0.","title":"insert"},{"location":"api/basic_json/insert/#nlohmannbasic_jsoninsert","text":"// (1) iterator insert ( const_iterator pos , const basic_json & val ); iterator insert ( const_iterator pos , basic_json && val ); // (2) iterator insert ( const_iterator pos , size_type cnt , const basic_json & val ); // (3) iterator insert ( const_iterator pos , const_iterator first , const_iterator last ); // (4) iterator insert ( const_iterator pos , initializer_list_t ilist ); // (5) void insert ( const_iterator first , const_iterator last ); Inserts element val into array before iterator pos . Inserts cnt copies of val into array before iterator pos . Inserts elements from range [first, last) into array before iterator pos . Inserts elements from initializer list ilist into array before iterator pos . Inserts elements from range [first, last) into object.","title":"nlohmann::basic_json::insert"},{"location":"api/basic_json/insert/#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","title":"Parameters"},{"location":"api/basic_json/insert/#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 (none)","title":"Return value"},{"location":"api/basic_json/insert/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/insert/#exceptions","text":"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\" 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\"","title":"Exceptions"},{"location":"api/basic_json/insert/#complexity","text":"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.","title":"Complexity"},{"location":"api/basic_json/insert/#examples","text":"Example (1): insert element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 10 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 10 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 10 [ 1 , 2 , 10 , 3 , 4 ] Example (2): insert copies of element into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert number 7 copies of number 7 before number 3 auto new_pos = v . insert ( v . begin () + 2 , 7 , 7 ); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 7 , 7 , 7 , 7 , 7 , 7 , 7 , 3 , 4 ] Example (3): insert range of elements into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // create a JSON array to copy values from json v2 = { \"one\" , \"two\" , \"three\" , \"four\" }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), v2 . begin (), v2 . end ()); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: \"one\" [ 1 , 2 , 3 , 4 , \"one\" , \"two\" , \"three\" , \"four\" ] Example (4): insert elements from initializer list into array The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create a JSON array json v = { 1 , 2 , 3 , 4 }; // insert range from v2 before the end of array v auto new_pos = v . insert ( v . end (), { 7 , 8 , 9 }); // output new array and result of insert call std :: cout << * new_pos << '\\n' ; std :: cout << v << '\\n' ; } Output: 7 [ 1 , 2 , 3 , 4 , 7 , 8 , 9 ] Example (5): insert range of elements into object The example shows how insert() is used. #include #include using json = nlohmann :: json ; int main () { // create two JSON objects json j1 = {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}; json j2 = {{ \"eleven\" , \"elf\" }, { \"seventeen\" , \"siebzehn\" }}; // output objects std :: cout << j1 << '\\n' ; std :: cout << j2 << '\\n' ; // insert range from j2 to j1 j1 . insert ( j2 . begin (), j2 . end ()); // output result of insert call std :: cout << j1 << '\\n' ; } Output: { \"one\" : \"eins\" , \"two\" : \"zwei\" } { \"eleven\" : \"elf\" , \"seventeen\" : \"siebzehn\" } { \"eleven\" : \"elf\" , \"one\" : \"eins\" , \"seventeen\" : \"siebzehn\" , \"two\" : \"zwei\" }","title":"Examples"},{"location":"api/basic_json/insert/#version-history","text":"Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 1.0.0. Added in version 3.0.0.","title":"Version history"},{"location":"api/basic_json/invalid_iterator/","text":"nlohmann::basic_json:: invalid_iterator \u00b6 class invalid_iterator : public exception ; This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx (see list of iterator errors ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .i n valid_i terat or. 207 ] ca nn o t use key() f or n o n - objec t i terat ors excep t io n id : 207 See also \u00b6 List of iterator errors parse_error for exceptions indicating a parse error 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 Version history \u00b6 Since version 3.0.0.","title":"invalid_iterator"},{"location":"api/basic_json/invalid_iterator/#nlohmannbasic_jsoninvalid_iterator","text":"class invalid_iterator : public exception ; This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx (see list of iterator errors ).","title":"nlohmann::basic_json::invalid_iterator"},{"location":"api/basic_json/invalid_iterator/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/invalid_iterator/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/invalid_iterator/#examples","text":"Example The following code shows how a invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .i n valid_i terat or. 207 ] ca nn o t use key() f or n o n - objec t i terat ors excep t io n id : 207","title":"Examples"},{"location":"api/basic_json/invalid_iterator/#see-also","text":"List of iterator errors parse_error for exceptions indicating a parse error 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","title":"See also"},{"location":"api/basic_json/invalid_iterator/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/is_array/","text":"nlohmann::basic_json:: is_array \u00b6 constexpr bool is_array () const noexcept ; This function returns true if and only if the JSON value is an array. Return value \u00b6 true if type is an array, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_array() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_array() std :: cout << std :: boolalpha ; std :: cout << j_null . is_array () << '\\n' ; std :: cout << j_boolean . is_array () << '\\n' ; std :: cout << j_number_integer . is_array () << '\\n' ; std :: cout << j_number_unsigned_integer . is_array () << '\\n' ; std :: cout << j_number_float . is_array () << '\\n' ; std :: cout << j_object . is_array () << '\\n' ; std :: cout << j_array . is_array () << '\\n' ; std :: cout << j_string . is_array () << '\\n' ; std :: cout << j_binary . is_array () << '\\n' ; } Output: false false false false false false true false false Version history \u00b6 Added in version 1.0.0.","title":"is_array"},{"location":"api/basic_json/is_array/#nlohmannbasic_jsonis_array","text":"constexpr bool is_array () const noexcept ; This function returns true if and only if the JSON value is an array.","title":"nlohmann::basic_json::is_array"},{"location":"api/basic_json/is_array/#return-value","text":"true if type is an array, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_array/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_array/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_array/#examples","text":"Example The following code exemplifies is_array() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_array() std :: cout << std :: boolalpha ; std :: cout << j_null . is_array () << '\\n' ; std :: cout << j_boolean . is_array () << '\\n' ; std :: cout << j_number_integer . is_array () << '\\n' ; std :: cout << j_number_unsigned_integer . is_array () << '\\n' ; std :: cout << j_number_float . is_array () << '\\n' ; std :: cout << j_object . is_array () << '\\n' ; std :: cout << j_array . is_array () << '\\n' ; std :: cout << j_string . is_array () << '\\n' ; std :: cout << j_binary . is_array () << '\\n' ; } Output: false false false false false false true false false","title":"Examples"},{"location":"api/basic_json/is_array/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_binary/","text":"nlohmann::basic_json:: is_binary \u00b6 constexpr bool is_binary () const noexcept ; This function returns true if and only if the JSON value is binary array. Return value \u00b6 true if type is binary, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_binary() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_binary() std :: cout << std :: boolalpha ; std :: cout << j_null . is_binary () << '\\n' ; std :: cout << j_boolean . is_binary () << '\\n' ; std :: cout << j_number_integer . is_binary () << '\\n' ; std :: cout << j_number_unsigned_integer . is_binary () << '\\n' ; std :: cout << j_number_float . is_binary () << '\\n' ; std :: cout << j_object . is_binary () << '\\n' ; std :: cout << j_array . is_binary () << '\\n' ; std :: cout << j_string . is_binary () << '\\n' ; std :: cout << j_binary . is_binary () << '\\n' ; } Output: false false false false false false false false true Version history \u00b6 Added in version 3.8.0.","title":"is_binary"},{"location":"api/basic_json/is_binary/#nlohmannbasic_jsonis_binary","text":"constexpr bool is_binary () const noexcept ; This function returns true if and only if the JSON value is binary array.","title":"nlohmann::basic_json::is_binary"},{"location":"api/basic_json/is_binary/#return-value","text":"true if type is binary, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_binary/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_binary/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_binary/#examples","text":"Example The following code exemplifies is_binary() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_binary() std :: cout << std :: boolalpha ; std :: cout << j_null . is_binary () << '\\n' ; std :: cout << j_boolean . is_binary () << '\\n' ; std :: cout << j_number_integer . is_binary () << '\\n' ; std :: cout << j_number_unsigned_integer . is_binary () << '\\n' ; std :: cout << j_number_float . is_binary () << '\\n' ; std :: cout << j_object . is_binary () << '\\n' ; std :: cout << j_array . is_binary () << '\\n' ; std :: cout << j_string . is_binary () << '\\n' ; std :: cout << j_binary . is_binary () << '\\n' ; } Output: false false false false false false false false true","title":"Examples"},{"location":"api/basic_json/is_binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/is_boolean/","text":"nlohmann::basic_json:: is_boolean \u00b6 constexpr bool is_boolean () const noexcept ; This function returns true if and only if the JSON value is true or false . Return value \u00b6 true if type is boolean, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_boolean() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_boolean() std :: cout << std :: boolalpha ; std :: cout << j_null . is_boolean () << '\\n' ; std :: cout << j_boolean . is_boolean () << '\\n' ; std :: cout << j_number_integer . is_boolean () << '\\n' ; std :: cout << j_number_unsigned_integer . is_boolean () << '\\n' ; std :: cout << j_number_float . is_boolean () << '\\n' ; std :: cout << j_object . is_boolean () << '\\n' ; std :: cout << j_array . is_boolean () << '\\n' ; std :: cout << j_string . is_boolean () << '\\n' ; std :: cout << j_binary . is_boolean () << '\\n' ; } Output: false true false false false false false false false Version history \u00b6 Added in version 1.0.0.","title":"is_boolean"},{"location":"api/basic_json/is_boolean/#nlohmannbasic_jsonis_boolean","text":"constexpr bool is_boolean () const noexcept ; This function returns true if and only if the JSON value is true or false .","title":"nlohmann::basic_json::is_boolean"},{"location":"api/basic_json/is_boolean/#return-value","text":"true if type is boolean, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_boolean/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_boolean/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_boolean/#examples","text":"Example The following code exemplifies is_boolean() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_boolean() std :: cout << std :: boolalpha ; std :: cout << j_null . is_boolean () << '\\n' ; std :: cout << j_boolean . is_boolean () << '\\n' ; std :: cout << j_number_integer . is_boolean () << '\\n' ; std :: cout << j_number_unsigned_integer . is_boolean () << '\\n' ; std :: cout << j_number_float . is_boolean () << '\\n' ; std :: cout << j_object . is_boolean () << '\\n' ; std :: cout << j_array . is_boolean () << '\\n' ; std :: cout << j_string . is_boolean () << '\\n' ; std :: cout << j_binary . is_boolean () << '\\n' ; } Output: false true false false false false false false false","title":"Examples"},{"location":"api/basic_json/is_boolean/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_discarded/","text":"nlohmann::basic_json:: is_discarded \u00b6 constexpr bool is_discarded () const noexcept ; This function returns true for a JSON value if either: the value was discarded during parsing with a callback function (see parser_callback_t ), or the value is the result of parsing invalid JSON with parameter allow_exceptions set to false ; see parse for more information. Return value \u00b6 true if type is discarded, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Notes \u00b6 Comparisons Discarded values are never compared equal with operator== . That is, checking whether a JSON value j is discarded will only work via: j . is_discarded () because j == json :: value_t :: discarded 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. Examples \u00b6 Example The following code exemplifies is_discarded() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_discarded() std :: cout << std :: boolalpha ; std :: cout << j_null . is_discarded () << '\\n' ; std :: cout << j_boolean . is_discarded () << '\\n' ; std :: cout << j_number_integer . is_discarded () << '\\n' ; std :: cout << j_number_unsigned_integer . is_discarded () << '\\n' ; std :: cout << j_number_float . is_discarded () << '\\n' ; std :: cout << j_object . is_discarded () << '\\n' ; std :: cout << j_array . is_discarded () << '\\n' ; std :: cout << j_string . is_discarded () << '\\n' ; std :: cout << j_binary . is_discarded () << '\\n' ; } Output: false false false false false false false false false Version history \u00b6 Added in version 1.0.0.","title":"is_discarded"},{"location":"api/basic_json/is_discarded/#nlohmannbasic_jsonis_discarded","text":"constexpr bool is_discarded () const noexcept ; This function returns true for a JSON value if either: the value was discarded during parsing with a callback function (see parser_callback_t ), or the value is the result of parsing invalid JSON with parameter allow_exceptions set to false ; see parse for more information.","title":"nlohmann::basic_json::is_discarded"},{"location":"api/basic_json/is_discarded/#return-value","text":"true if type is discarded, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_discarded/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_discarded/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_discarded/#notes","text":"Comparisons Discarded values are never compared equal with operator== . That is, checking whether a JSON value j is discarded will only work via: j . is_discarded () because j == json :: value_t :: discarded 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.","title":"Notes"},{"location":"api/basic_json/is_discarded/#examples","text":"Example The following code exemplifies is_discarded() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_discarded() std :: cout << std :: boolalpha ; std :: cout << j_null . is_discarded () << '\\n' ; std :: cout << j_boolean . is_discarded () << '\\n' ; std :: cout << j_number_integer . is_discarded () << '\\n' ; std :: cout << j_number_unsigned_integer . is_discarded () << '\\n' ; std :: cout << j_number_float . is_discarded () << '\\n' ; std :: cout << j_object . is_discarded () << '\\n' ; std :: cout << j_array . is_discarded () << '\\n' ; std :: cout << j_string . is_discarded () << '\\n' ; std :: cout << j_binary . is_discarded () << '\\n' ; } Output: false false false false false false false false false","title":"Examples"},{"location":"api/basic_json/is_discarded/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_null/","text":"nlohmann::basic_json:: is_null \u00b6 constexpr bool is_null () const noexcept ; This function returns true if and only if the JSON value is null . Return value \u00b6 true if type is null , false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_null() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_null() std :: cout << std :: boolalpha ; std :: cout << j_null . is_null () << '\\n' ; std :: cout << j_boolean . is_null () << '\\n' ; std :: cout << j_number_integer . is_null () << '\\n' ; std :: cout << j_number_unsigned_integer . is_null () << '\\n' ; std :: cout << j_number_float . is_null () << '\\n' ; std :: cout << j_object . is_null () << '\\n' ; std :: cout << j_array . is_null () << '\\n' ; std :: cout << j_string . is_null () << '\\n' ; std :: cout << j_binary . is_null () << '\\n' ; } Output: true false false false false false false false false Version history \u00b6 Added in version 1.0.0.","title":"is_null"},{"location":"api/basic_json/is_null/#nlohmannbasic_jsonis_null","text":"constexpr bool is_null () const noexcept ; This function returns true if and only if the JSON value is null .","title":"nlohmann::basic_json::is_null"},{"location":"api/basic_json/is_null/#return-value","text":"true if type is null , false otherwise.","title":"Return value"},{"location":"api/basic_json/is_null/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_null/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_null/#examples","text":"Example The following code exemplifies is_null() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_null() std :: cout << std :: boolalpha ; std :: cout << j_null . is_null () << '\\n' ; std :: cout << j_boolean . is_null () << '\\n' ; std :: cout << j_number_integer . is_null () << '\\n' ; std :: cout << j_number_unsigned_integer . is_null () << '\\n' ; std :: cout << j_number_float . is_null () << '\\n' ; std :: cout << j_object . is_null () << '\\n' ; std :: cout << j_array . is_null () << '\\n' ; std :: cout << j_string . is_null () << '\\n' ; std :: cout << j_binary . is_null () << '\\n' ; } Output: true false false false false false false false false","title":"Examples"},{"location":"api/basic_json/is_null/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_number/","text":"nlohmann::basic_json:: is_number \u00b6 constexpr bool is_number () const noexcept ; This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. Return value \u00b6 true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Possible implementation \u00b6 constexpr bool is_number () const noexcept { return is_number_integer () || is_number_float (); } Examples \u00b6 Example The following code exemplifies is_number() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number () << '\\n' ; std :: cout << j_boolean . is_number () << '\\n' ; std :: cout << j_number_integer . is_number () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number () << '\\n' ; std :: cout << j_number_float . is_number () << '\\n' ; std :: cout << j_object . is_number () << '\\n' ; std :: cout << j_array . is_number () << '\\n' ; std :: cout << j_string . is_number () << '\\n' ; std :: cout << j_binary . is_number () << '\\n' ; } Output: false false true true true false false false false See also \u00b6 is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number Version history \u00b6 Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"is_number"},{"location":"api/basic_json/is_number/#nlohmannbasic_jsonis_number","text":"constexpr bool is_number () const noexcept ; This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values.","title":"nlohmann::basic_json::is_number"},{"location":"api/basic_json/is_number/#return-value","text":"true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number/#possible-implementation","text":"constexpr bool is_number () const noexcept { return is_number_integer () || is_number_float (); }","title":"Possible implementation"},{"location":"api/basic_json/is_number/#examples","text":"Example The following code exemplifies is_number() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number () << '\\n' ; std :: cout << j_boolean . is_number () << '\\n' ; std :: cout << j_number_integer . is_number () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number () << '\\n' ; std :: cout << j_number_float . is_number () << '\\n' ; std :: cout << j_object . is_number () << '\\n' ; std :: cout << j_array . is_number () << '\\n' ; std :: cout << j_string . is_number () << '\\n' ; std :: cout << j_binary . is_number () << '\\n' ; } Output: false false true true true false false false false","title":"Examples"},{"location":"api/basic_json/is_number/#see-also","text":"is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number","title":"See also"},{"location":"api/basic_json/is_number/#version-history","text":"Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"Version history"},{"location":"api/basic_json/is_number_float/","text":"nlohmann::basic_json:: is_number_float \u00b6 constexpr bool is_number_float () const noexcept ; This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. Return value \u00b6 true if type is a floating-point number, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_number_float() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_float() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_float () << '\\n' ; std :: cout << j_boolean . is_number_float () << '\\n' ; std :: cout << j_number_integer . is_number_float () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_float () << '\\n' ; std :: cout << j_number_float . is_number_float () << '\\n' ; std :: cout << j_object . is_number_float () << '\\n' ; std :: cout << j_array . is_number_float () << '\\n' ; std :: cout << j_string . is_number_float () << '\\n' ; std :: cout << j_binary . is_number_float () << '\\n' ; } Output: false false false false true false false false false See also \u00b6 is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number Version history \u00b6 Added in version 1.0.0.","title":"is_number_float"},{"location":"api/basic_json/is_number_float/#nlohmannbasic_jsonis_number_float","text":"constexpr bool is_number_float () const noexcept ; This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values.","title":"nlohmann::basic_json::is_number_float"},{"location":"api/basic_json/is_number_float/#return-value","text":"true if type is a floating-point number, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number_float/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number_float/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number_float/#examples","text":"Example The following code exemplifies is_number_float() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_float() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_float () << '\\n' ; std :: cout << j_boolean . is_number_float () << '\\n' ; std :: cout << j_number_integer . is_number_float () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_float () << '\\n' ; std :: cout << j_number_float . is_number_float () << '\\n' ; std :: cout << j_object . is_number_float () << '\\n' ; std :: cout << j_array . is_number_float () << '\\n' ; std :: cout << j_string . is_number_float () << '\\n' ; std :: cout << j_binary . is_number_float () << '\\n' ; } Output: false false false false true false false false false","title":"Examples"},{"location":"api/basic_json/is_number_float/#see-also","text":"is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_unsigned() check if value is an unsigned integer number","title":"See also"},{"location":"api/basic_json/is_number_float/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_number_integer/","text":"nlohmann::basic_json:: is_number_integer \u00b6 constexpr bool is_number_integer () const noexcept ; This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. Return value \u00b6 true if type is an integer or unsigned integer number, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_number_integer() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_integer() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_integer () << '\\n' ; std :: cout << j_boolean . is_number_integer () << '\\n' ; std :: cout << j_number_integer . is_number_integer () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_integer () << '\\n' ; std :: cout << j_number_float . is_number_integer () << '\\n' ; std :: cout << j_object . is_number_integer () << '\\n' ; std :: cout << j_array . is_number_integer () << '\\n' ; std :: cout << j_string . is_number_integer () << '\\n' ; std :: cout << j_binary . is_number_integer () << '\\n' ; } Output: false false true true false false false false false See also \u00b6 is_number() check if value is a number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number Version history \u00b6 Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"is_number_integer"},{"location":"api/basic_json/is_number_integer/#nlohmannbasic_jsonis_number_integer","text":"constexpr bool is_number_integer () const noexcept ; This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values.","title":"nlohmann::basic_json::is_number_integer"},{"location":"api/basic_json/is_number_integer/#return-value","text":"true if type is an integer or unsigned integer number, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number_integer/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number_integer/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number_integer/#examples","text":"Example The following code exemplifies is_number_integer() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_integer() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_integer () << '\\n' ; std :: cout << j_boolean . is_number_integer () << '\\n' ; std :: cout << j_number_integer . is_number_integer () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_integer () << '\\n' ; std :: cout << j_number_float . is_number_integer () << '\\n' ; std :: cout << j_object . is_number_integer () << '\\n' ; std :: cout << j_array . is_number_integer () << '\\n' ; std :: cout << j_string . is_number_integer () << '\\n' ; std :: cout << j_binary . is_number_integer () << '\\n' ; } Output: false false true true false false false false false","title":"Examples"},{"location":"api/basic_json/is_number_integer/#see-also","text":"is_number() check if value is a number is_number_unsigned() check if value is an unsigned integer number is_number_float() check if value is a floating-point number","title":"See also"},{"location":"api/basic_json/is_number_integer/#version-history","text":"Added in version 1.0.0. Extended to also return true for unsigned integers in 2.0.0.","title":"Version history"},{"location":"api/basic_json/is_number_unsigned/","text":"nlohmann::basic_json:: is_number_unsigned \u00b6 constexpr bool is_number_unsigned () const noexcept ; This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. Return value \u00b6 true if type is an unsigned integer number, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_number_unsigned() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_unsigned() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_unsigned () << '\\n' ; std :: cout << j_boolean . is_number_unsigned () << '\\n' ; std :: cout << j_number_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_float . is_number_unsigned () << '\\n' ; std :: cout << j_object . is_number_unsigned () << '\\n' ; std :: cout << j_array . is_number_unsigned () << '\\n' ; std :: cout << j_string . is_number_unsigned () << '\\n' ; std :: cout << j_binary . is_number_unsigned () << '\\n' ; } Output: false false false true false false false false false See also \u00b6 is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_float() check if value is a floating-point number Version history \u00b6 Added in version 2.0.0.","title":"is_number_unsigned"},{"location":"api/basic_json/is_number_unsigned/#nlohmannbasic_jsonis_number_unsigned","text":"constexpr bool is_number_unsigned () const noexcept ; This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values.","title":"nlohmann::basic_json::is_number_unsigned"},{"location":"api/basic_json/is_number_unsigned/#return-value","text":"true if type is an unsigned integer number, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_number_unsigned/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_number_unsigned/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_number_unsigned/#examples","text":"Example The following code exemplifies is_number_unsigned() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_unsigned_integer = 12345678987654321u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_number_unsigned() std :: cout << std :: boolalpha ; std :: cout << j_null . is_number_unsigned () << '\\n' ; std :: cout << j_boolean . is_number_unsigned () << '\\n' ; std :: cout << j_number_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_unsigned_integer . is_number_unsigned () << '\\n' ; std :: cout << j_number_float . is_number_unsigned () << '\\n' ; std :: cout << j_object . is_number_unsigned () << '\\n' ; std :: cout << j_array . is_number_unsigned () << '\\n' ; std :: cout << j_string . is_number_unsigned () << '\\n' ; std :: cout << j_binary . is_number_unsigned () << '\\n' ; } Output: false false false true false false false false false","title":"Examples"},{"location":"api/basic_json/is_number_unsigned/#see-also","text":"is_number() check if value is a number is_number_integer() check if value is an integer or unsigned integer number is_number_float() check if value is a floating-point number","title":"See also"},{"location":"api/basic_json/is_number_unsigned/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/is_object/","text":"nlohmann::basic_json:: is_object \u00b6 constexpr bool is_object () const noexcept ; This function returns true if and only if the JSON value is an object. Return value \u00b6 true if type is an object, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_object() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_object() std :: cout << std :: boolalpha ; std :: cout << j_null . is_object () << '\\n' ; std :: cout << j_boolean . is_object () << '\\n' ; std :: cout << j_number_integer . is_object () << '\\n' ; std :: cout << j_number_unsigned_integer . is_object () << '\\n' ; std :: cout << j_number_float . is_object () << '\\n' ; std :: cout << j_object . is_object () << '\\n' ; std :: cout << j_array . is_object () << '\\n' ; std :: cout << j_string . is_object () << '\\n' ; std :: cout << j_binary . is_object () << '\\n' ; } Output: false false false false false true false false false Version history \u00b6 Added in version 1.0.0.","title":"is_object"},{"location":"api/basic_json/is_object/#nlohmannbasic_jsonis_object","text":"constexpr bool is_object () const noexcept ; This function returns true if and only if the JSON value is an object.","title":"nlohmann::basic_json::is_object"},{"location":"api/basic_json/is_object/#return-value","text":"true if type is an object, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_object/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_object/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_object/#examples","text":"Example The following code exemplifies is_object() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_object() std :: cout << std :: boolalpha ; std :: cout << j_null . is_object () << '\\n' ; std :: cout << j_boolean . is_object () << '\\n' ; std :: cout << j_number_integer . is_object () << '\\n' ; std :: cout << j_number_unsigned_integer . is_object () << '\\n' ; std :: cout << j_number_float . is_object () << '\\n' ; std :: cout << j_object . is_object () << '\\n' ; std :: cout << j_array . is_object () << '\\n' ; std :: cout << j_string . is_object () << '\\n' ; std :: cout << j_binary . is_object () << '\\n' ; } Output: false false false false false true false false false","title":"Examples"},{"location":"api/basic_json/is_object/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_primitive/","text":"nlohmann::basic_json:: is_primitive \u00b6 constexpr bool is_primitive () const noexcept ; This function returns true if and only if the JSON type is primitive (string, number, boolean, null , binary). Return value \u00b6 true if type is primitive (string, number, boolean, null , or binary), false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Possible implementation \u00b6 constexpr bool is_primitive () const noexcept { return is_null () || is_string () || is_boolean () || is_number () || is_binary (); } Notes \u00b6 The term primitive stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values. Examples \u00b6 Example The following code exemplifies is_primitive() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_primitive() std :: cout << std :: boolalpha ; std :: cout << j_null . is_primitive () << '\\n' ; std :: cout << j_boolean . is_primitive () << '\\n' ; std :: cout << j_number_integer . is_primitive () << '\\n' ; std :: cout << j_number_unsigned_integer . is_primitive () << '\\n' ; std :: cout << j_number_float . is_primitive () << '\\n' ; std :: cout << j_object . is_primitive () << '\\n' ; std :: cout << j_array . is_primitive () << '\\n' ; std :: cout << j_string . is_primitive () << '\\n' ; std :: cout << j_binary . is_primitive () << '\\n' ; } Output: true true true true true false false true true See also \u00b6 is_structured() returns whether JSON value is structured is_null() returns whether JSON value is null is_string() returns whether JSON value is a string is_boolean() returns whether JSON value is a boolean is_number() returns whether JSON value is a number is_binary() returns whether JSON value is a binary array Version history \u00b6 Added in version 1.0.0. Extended to return true for binary types in version 3.8.0.","title":"is_primitive"},{"location":"api/basic_json/is_primitive/#nlohmannbasic_jsonis_primitive","text":"constexpr bool is_primitive () const noexcept ; This function returns true if and only if the JSON type is primitive (string, number, boolean, null , binary).","title":"nlohmann::basic_json::is_primitive"},{"location":"api/basic_json/is_primitive/#return-value","text":"true if type is primitive (string, number, boolean, null , or binary), false otherwise.","title":"Return value"},{"location":"api/basic_json/is_primitive/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_primitive/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_primitive/#possible-implementation","text":"constexpr bool is_primitive () const noexcept { return is_null () || is_string () || is_boolean () || is_number () || is_binary (); }","title":"Possible implementation"},{"location":"api/basic_json/is_primitive/#notes","text":"The term primitive stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence, is_primitive() returns true for binary values.","title":"Notes"},{"location":"api/basic_json/is_primitive/#examples","text":"Example The following code exemplifies is_primitive() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_primitive() std :: cout << std :: boolalpha ; std :: cout << j_null . is_primitive () << '\\n' ; std :: cout << j_boolean . is_primitive () << '\\n' ; std :: cout << j_number_integer . is_primitive () << '\\n' ; std :: cout << j_number_unsigned_integer . is_primitive () << '\\n' ; std :: cout << j_number_float . is_primitive () << '\\n' ; std :: cout << j_object . is_primitive () << '\\n' ; std :: cout << j_array . is_primitive () << '\\n' ; std :: cout << j_string . is_primitive () << '\\n' ; std :: cout << j_binary . is_primitive () << '\\n' ; } Output: true true true true true false false true true","title":"Examples"},{"location":"api/basic_json/is_primitive/#see-also","text":"is_structured() returns whether JSON value is structured is_null() returns whether JSON value is null is_string() returns whether JSON value is a string is_boolean() returns whether JSON value is a boolean is_number() returns whether JSON value is a number is_binary() returns whether JSON value is a binary array","title":"See also"},{"location":"api/basic_json/is_primitive/#version-history","text":"Added in version 1.0.0. Extended to return true for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/is_string/","text":"nlohmann::basic_json:: is_string \u00b6 constexpr bool is_string () const noexcept ; This function returns true if and only if the JSON value is a string. Return value \u00b6 true if type is a string, false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies is_string() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_string() std :: cout << std :: boolalpha ; std :: cout << j_null . is_string () << '\\n' ; std :: cout << j_boolean . is_string () << '\\n' ; std :: cout << j_number_integer . is_string () << '\\n' ; std :: cout << j_number_unsigned_integer . is_string () << '\\n' ; std :: cout << j_number_float . is_string () << '\\n' ; std :: cout << j_object . is_string () << '\\n' ; std :: cout << j_array . is_string () << '\\n' ; std :: cout << j_string . is_string () << '\\n' ; std :: cout << j_binary . is_string () << '\\n' ; } Output: false false false false false false false true false Version history \u00b6 Added in version 1.0.0.","title":"is_string"},{"location":"api/basic_json/is_string/#nlohmannbasic_jsonis_string","text":"constexpr bool is_string () const noexcept ; This function returns true if and only if the JSON value is a string.","title":"nlohmann::basic_json::is_string"},{"location":"api/basic_json/is_string/#return-value","text":"true if type is a string, false otherwise.","title":"Return value"},{"location":"api/basic_json/is_string/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_string/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_string/#examples","text":"Example The following code exemplifies is_string() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_string() std :: cout << std :: boolalpha ; std :: cout << j_null . is_string () << '\\n' ; std :: cout << j_boolean . is_string () << '\\n' ; std :: cout << j_number_integer . is_string () << '\\n' ; std :: cout << j_number_unsigned_integer . is_string () << '\\n' ; std :: cout << j_number_float . is_string () << '\\n' ; std :: cout << j_object . is_string () << '\\n' ; std :: cout << j_array . is_string () << '\\n' ; std :: cout << j_string . is_string () << '\\n' ; std :: cout << j_binary . is_string () << '\\n' ; } Output: false false false false false false false true false","title":"Examples"},{"location":"api/basic_json/is_string/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/is_structured/","text":"nlohmann::basic_json:: is_structured \u00b6 constexpr bool is_structured () const noexcept ; This function returns true if and only if the JSON type is structured (array or object). Return value \u00b6 true if type is structured (array or object), false otherwise. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Possible implementation \u00b6 constexpr bool is_primitive () const noexcept { return is_array () || is_object (); } Notes \u00b6 The term structured stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). Note that though strings are containers in C++, they are treated as primitive values in JSON. Examples \u00b6 Example The following code exemplifies is_structured() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_structured() std :: cout << std :: boolalpha ; std :: cout << j_null . is_structured () << '\\n' ; std :: cout << j_boolean . is_structured () << '\\n' ; std :: cout << j_number_integer . is_structured () << '\\n' ; std :: cout << j_number_unsigned_integer . is_structured () << '\\n' ; std :: cout << j_number_float . is_structured () << '\\n' ; std :: cout << j_object . is_structured () << '\\n' ; std :: cout << j_array . is_structured () << '\\n' ; std :: cout << j_string . is_structured () << '\\n' ; std :: cout << j_binary . is_structured () << '\\n' ; } Output: false false false false false true true false false See also \u00b6 is_primitive() returns whether JSON value is primitive is_array() returns whether value is an array is_object() returns whether value is an object Version history \u00b6 Added in version 1.0.0.","title":"is_structured"},{"location":"api/basic_json/is_structured/#nlohmannbasic_jsonis_structured","text":"constexpr bool is_structured () const noexcept ; This function returns true if and only if the JSON type is structured (array or object).","title":"nlohmann::basic_json::is_structured"},{"location":"api/basic_json/is_structured/#return-value","text":"true if type is structured (array or object), false otherwise.","title":"Return value"},{"location":"api/basic_json/is_structured/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/is_structured/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/is_structured/#possible-implementation","text":"constexpr bool is_primitive () const noexcept { return is_array () || is_object (); }","title":"Possible implementation"},{"location":"api/basic_json/is_structured/#notes","text":"The term structured stems from RFC 8259 : JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays). Note that though strings are containers in C++, they are treated as primitive values in JSON.","title":"Notes"},{"location":"api/basic_json/is_structured/#examples","text":"Example The following code exemplifies is_structured() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_number_unsigned_integer = 12345678987654321u ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; json j_binary = json :: binary ({ 1 , 2 , 3 }); // call is_structured() std :: cout << std :: boolalpha ; std :: cout << j_null . is_structured () << '\\n' ; std :: cout << j_boolean . is_structured () << '\\n' ; std :: cout << j_number_integer . is_structured () << '\\n' ; std :: cout << j_number_unsigned_integer . is_structured () << '\\n' ; std :: cout << j_number_float . is_structured () << '\\n' ; std :: cout << j_object . is_structured () << '\\n' ; std :: cout << j_array . is_structured () << '\\n' ; std :: cout << j_string . is_structured () << '\\n' ; std :: cout << j_binary . is_structured () << '\\n' ; } Output: false false false false false true true false false","title":"Examples"},{"location":"api/basic_json/is_structured/#see-also","text":"is_primitive() returns whether JSON value is primitive is_array() returns whether value is an array is_object() returns whether value is an object","title":"See also"},{"location":"api/basic_json/is_structured/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/items/","text":"nlohmann::basic_json:: items \u00b6 iteration_proxy < iterator > items () noexcept ; iteration_proxy < const_iterator > items () const noexcept ; 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 ) { std :: cout << \"key: \" << it . key () << \", value:\" << it . value () << '\\n' ; } Range-based for loop without items() function: for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\n' ; } Range-based for loop with items() function: for ( auto & el : j_object . items ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; } Return value \u00b6 iteration proxy object wrapping the current value with an interface to use in range-based for loops Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Constant. Notes \u00b6 When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string. Lifetime issues Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information. Examples \u00b6 Example The following code shows an example for items() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // example for an object for ( auto & x : j_object . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } // example for an array for ( auto & x : j_array . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } } Output: key : o ne , value : 1 key : t wo , value : 2 key : 0 , value : 1 key : 1 , value : 2 key : 2 , value : 4 key : 3 , value : 8 key : 4 , value : 16 Version history \u00b6 Added iterator_wrapper in version 3.0.0. 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.","title":"items"},{"location":"api/basic_json/items/#nlohmannbasic_jsonitems","text":"iteration_proxy < iterator > items () noexcept ; iteration_proxy < const_iterator > items () const noexcept ; 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 ) { std :: cout << \"key: \" << it . key () << \", value:\" << it . value () << '\\n' ; } Range-based for loop without items() function: for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\n' ; } Range-based for loop with items() function: for ( auto & el : j_object . items ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; }","title":"nlohmann::basic_json::items"},{"location":"api/basic_json/items/#return-value","text":"iteration proxy object wrapping the current value with an interface to use in range-based for loops","title":"Return value"},{"location":"api/basic_json/items/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/items/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/items/#notes","text":"When iterating over an array, key() will return the index of the element as string (see example). For primitive types (e.g., numbers), key() returns an empty string. Lifetime issues Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.","title":"Notes"},{"location":"api/basic_json/items/#examples","text":"Example The following code shows an example for items() . #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; // example for an object for ( auto & x : j_object . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } // example for an array for ( auto & x : j_array . items ()) { std :: cout << \"key: \" << x . key () << \", value: \" << x . value () << '\\n' ; } } Output: key : o ne , value : 1 key : t wo , value : 2 key : 0 , value : 1 key : 1 , value : 2 key : 2 , value : 4 key : 3 , value : 8 key : 4 , value : 16","title":"Examples"},{"location":"api/basic_json/items/#version-history","text":"Added iterator_wrapper in version 3.0.0. 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.","title":"Version history"},{"location":"api/basic_json/json_base_class_t/","text":"nlohmann::basic_json:: json_base_class_t \u00b6 using json_base_class_t = detail :: json_base_class < CustomBaseClass > ; 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. Template parameters \u00b6 CustomBaseClass the base class to be added to basic_json Notes \u00b6 Default type \u00b6 The default value for CustomBaseClass is void . In this case an empty base class is used and no additional functionality is injected. Limitations \u00b6 The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well. Examples \u00b6 Example The following code shows how to inject custom data and methods for each node. #include #include class visitor_adaptor_with_metadata { public : template < class Fnc > void visit ( const Fnc & fnc ) const ; int metadata = 42 ; private : template < class Ptr , class Fnc > void do_visit ( const Ptr & ptr , const Fnc & fnc ) const ; }; using json = nlohmann :: basic_json < std :: map , std :: vector , std :: string , bool , std :: int64_t , std :: uint64_t , double , std :: allocator , nlohmann :: adl_serializer , std :: vector < std :: uint8_t > , visitor_adaptor_with_metadata > ; template < class Fnc > void visitor_adaptor_with_metadata :: visit ( const Fnc & fnc ) const { do_visit ( json :: json_pointer {}, fnc ); } template < class Ptr , class Fnc > void visitor_adaptor_with_metadata :: do_visit ( const Ptr & ptr , const Fnc & fnc ) const { using value_t = nlohmann :: detail :: value_t ; const json & j = * static_cast < const json *> ( this ); switch ( j . type ()) { case value_t :: object : fnc ( ptr , j ); for ( const auto & entry : j . items ()) { entry . value (). do_visit ( ptr / entry . key (), fnc ); } break ; case value_t :: array : fnc ( ptr , j ); for ( std :: size_t i = 0 ; i < j . size (); ++ i ) { j . at ( i ). do_visit ( ptr / std :: to_string ( i ), fnc ); } break ; case value_t :: null : case value_t :: string : case value_t :: boolean : case value_t :: number_integer : case value_t :: number_unsigned : case value_t :: number_float : case value_t :: binary : fnc ( ptr , j ); break ; case value_t :: discarded : default : break ; } } int main () { // create a json object json j ; j [ \"null\" ]; j [ \"object\" ][ \"uint\" ] = 1U ; j [ \"object\" ]. metadata = 21 ; // visit and output j . visit ( [ & ]( const json :: json_pointer & p , const json & j ) { std :: cout << ( p . empty () ? std :: string { \"/\" } : p . to_string ()) << \" - metadata = \" << j . metadata << \" -> \" << j . dump () << '\\n' ; }); } Output: / - me ta da ta = 42 - > { \"null\" : null , \"object\" :{ \"uint\" : 1 }} / null - me ta da ta = 42 - > null /objec t - me ta da ta = 21 - > { \"uint\" : 1 } /objec t /ui nt - me ta da ta = 42 - > 1 Version history \u00b6 Added in version 3.12.0.","title":"json_base_class_t"},{"location":"api/basic_json/json_base_class_t/#nlohmannbasic_jsonjson_base_class_t","text":"using json_base_class_t = detail :: json_base_class < CustomBaseClass > ; 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.","title":"nlohmann::basic_json::json_base_class_t"},{"location":"api/basic_json/json_base_class_t/#template-parameters","text":"CustomBaseClass the base class to be added to basic_json","title":"Template parameters"},{"location":"api/basic_json/json_base_class_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/json_base_class_t/#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.","title":"Default type"},{"location":"api/basic_json/json_base_class_t/#limitations","text":"The type CustomBaseClass has to be a default-constructible class. basic_json only supports copy/move construction/assignment if CustomBaseClass does so as well.","title":"Limitations"},{"location":"api/basic_json/json_base_class_t/#examples","text":"Example The following code shows how to inject custom data and methods for each node. #include #include class visitor_adaptor_with_metadata { public : template < class Fnc > void visit ( const Fnc & fnc ) const ; int metadata = 42 ; private : template < class Ptr , class Fnc > void do_visit ( const Ptr & ptr , const Fnc & fnc ) const ; }; using json = nlohmann :: basic_json < std :: map , std :: vector , std :: string , bool , std :: int64_t , std :: uint64_t , double , std :: allocator , nlohmann :: adl_serializer , std :: vector < std :: uint8_t > , visitor_adaptor_with_metadata > ; template < class Fnc > void visitor_adaptor_with_metadata :: visit ( const Fnc & fnc ) const { do_visit ( json :: json_pointer {}, fnc ); } template < class Ptr , class Fnc > void visitor_adaptor_with_metadata :: do_visit ( const Ptr & ptr , const Fnc & fnc ) const { using value_t = nlohmann :: detail :: value_t ; const json & j = * static_cast < const json *> ( this ); switch ( j . type ()) { case value_t :: object : fnc ( ptr , j ); for ( const auto & entry : j . items ()) { entry . value (). do_visit ( ptr / entry . key (), fnc ); } break ; case value_t :: array : fnc ( ptr , j ); for ( std :: size_t i = 0 ; i < j . size (); ++ i ) { j . at ( i ). do_visit ( ptr / std :: to_string ( i ), fnc ); } break ; case value_t :: null : case value_t :: string : case value_t :: boolean : case value_t :: number_integer : case value_t :: number_unsigned : case value_t :: number_float : case value_t :: binary : fnc ( ptr , j ); break ; case value_t :: discarded : default : break ; } } int main () { // create a json object json j ; j [ \"null\" ]; j [ \"object\" ][ \"uint\" ] = 1U ; j [ \"object\" ]. metadata = 21 ; // visit and output j . visit ( [ & ]( const json :: json_pointer & p , const json & j ) { std :: cout << ( p . empty () ? std :: string { \"/\" } : p . to_string ()) << \" - metadata = \" << j . metadata << \" -> \" << j . dump () << '\\n' ; }); } Output: / - me ta da ta = 42 - > { \"null\" : null , \"object\" :{ \"uint\" : 1 }} / null - me ta da ta = 42 - > null /objec t - me ta da ta = 21 - > { \"uint\" : 1 } /objec t /ui nt - me ta da ta = 42 - > 1","title":"Examples"},{"location":"api/basic_json/json_base_class_t/#version-history","text":"Added in version 3.12.0.","title":"Version history"},{"location":"api/basic_json/json_serializer/","text":"nlohmann::basic_json:: json_serializer \u00b6 template < typename T , typename SFINAE > using json_serializer = JSONSerializer < T , SFINAE > ; Template parameters \u00b6 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 Notes \u00b6 Default type \u00b6 The default values for json_serializer is adl_serializer . Examples \u00b6 Example The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer . #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace Version history \u00b6 Since version 2.0.0.","title":"json_serializer"},{"location":"api/basic_json/json_serializer/#nlohmannbasic_jsonjson_serializer","text":"template < typename T , typename SFINAE > using json_serializer = JSONSerializer < T , SFINAE > ;","title":"nlohmann::basic_json::json_serializer"},{"location":"api/basic_json/json_serializer/#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","title":"Template parameters"},{"location":"api/basic_json/json_serializer/#notes","text":"","title":"Notes"},{"location":"api/basic_json/json_serializer/#default-type","text":"The default values for json_serializer is adl_serializer .","title":"Default type"},{"location":"api/basic_json/json_serializer/#examples","text":"Example The example below shows how a conversion of a non-default-constructible type is implemented via a specialization of the adl_serializer . #include #include using json = nlohmann :: json ; namespace ns { // a simple struct to model a person (not default constructible) struct person { person ( std :: string n , std :: string a , int aa ) : name ( std :: move ( n )), address ( std :: move ( a )), age ( aa ) {} std :: string name ; std :: string address ; int age ; }; } // namespace ns namespace nlohmann { template <> struct adl_serializer < ns :: person > { static ns :: person from_json ( const json & j ) { return { j . at ( \"name\" ), j . at ( \"address\" ), j . at ( \"age\" )}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert person to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , ns :: person p ) { j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; } }; } // namespace nlohmann int main () { json j ; j [ \"name\" ] = \"Ned Flanders\" ; j [ \"address\" ] = \"744 Evergreen Terrace\" ; j [ \"age\" ] = 60 ; auto p = j . template get < ns :: person > (); std :: cout << p . name << \" (\" << p . age << \") lives in \" << p . address << std :: endl ; } Output: Ned Fla n ders ( 60 ) lives i n 744 Evergree n Terrace","title":"Examples"},{"location":"api/basic_json/json_serializer/#version-history","text":"Since version 2.0.0.","title":"Version history"},{"location":"api/basic_json/max_size/","text":"nlohmann::basic_json:: max_size \u00b6 size_type max_size () const noexcept ; 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. Return value \u00b6 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() Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity. Notes \u00b6 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 . Examples \u00b6 Example The following code calls max_size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call max_size() std :: cout << j_null . max_size () << '\\n' ; std :: cout << j_boolean . max_size () << '\\n' ; std :: cout << j_number_integer . max_size () << '\\n' ; std :: cout << j_number_float . max_size () << '\\n' ; std :: cout << j_object . max_size () << '\\n' ; std :: cout << j_array . max_size () << '\\n' ; std :: cout << j_string . max_size () << '\\n' ; } Output: 0 1 1 1 115292150460684697 576460752303423487 1 Note the output is platform-dependent. Version history \u00b6 Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"max_size"},{"location":"api/basic_json/max_size/#nlohmannbasic_jsonmax_size","text":"size_type max_size () const noexcept ; 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.","title":"nlohmann::basic_json::max_size"},{"location":"api/basic_json/max_size/#return-value","text":"The return value depends on the different types and is defined as follows: Value type return value null 0 (same as size() ) boolean 1 (same as size() ) string 1 (same as size() ) number 1 (same as size() ) binary 1 (same as size() ) object result of function object_t::max_size() array result of function array_t::max_size()","title":"Return value"},{"location":"api/basic_json/max_size/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/max_size/#complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.","title":"Complexity"},{"location":"api/basic_json/max_size/#notes","text":"This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of string elements the JSON value can store which is 1 .","title":"Notes"},{"location":"api/basic_json/max_size/#examples","text":"Example The following code calls max_size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call max_size() std :: cout << j_null . max_size () << '\\n' ; std :: cout << j_boolean . max_size () << '\\n' ; std :: cout << j_number_integer . max_size () << '\\n' ; std :: cout << j_number_float . max_size () << '\\n' ; std :: cout << j_object . max_size () << '\\n' ; std :: cout << j_array . max_size () << '\\n' ; std :: cout << j_string . max_size () << '\\n' ; } Output: 0 1 1 1 115292150460684697 576460752303423487 1 Note the output is platform-dependent.","title":"Examples"},{"location":"api/basic_json/max_size/#version-history","text":"Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/merge_patch/","text":"nlohmann::basic_json:: merge_patch \u00b6 void merge_patch ( const basic_json & apply_patch ); 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 ): if Patch is an Object : if Target is not an Object : Target = {} // Ignore the contents and set it to an empty Object for each Name / Value pair in Patch : if Value is null : if Name exists in Target : remove the Name / Value pair from Target else : Target [ Name ] = MergePatch ( Target [ Name ], Value ) return Target else : return Patch Thereby, Target is the current object; that is, the patch is applied to the current value. Parameters \u00b6 apply_patch (in) the patch to apply Complexity \u00b6 Linear in the lengths of apply_patch . Examples \u00b6 Example The following code shows how a JSON Merge Patch is applied to a JSON document. #include #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" } See also \u00b6 RFC 7396 (JSON Merge Patch) patch apply a JSON patch Version history \u00b6 Added in version 3.0.0.","title":"merge_patch"},{"location":"api/basic_json/merge_patch/#nlohmannbasic_jsonmerge_patch","text":"void merge_patch ( const basic_json & apply_patch ); 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 ): if Patch is an Object : if Target is not an Object : Target = {} // Ignore the contents and set it to an empty Object for each Name / Value pair in Patch : if Value is null : if Name exists in Target : remove the Name / Value pair from Target else : Target [ Name ] = MergePatch ( Target [ Name ], Value ) return Target else : return Patch Thereby, Target is the current object; that is, the patch is applied to the current value.","title":"nlohmann::basic_json::merge_patch"},{"location":"api/basic_json/merge_patch/#parameters","text":"apply_patch (in) the patch to apply","title":"Parameters"},{"location":"api/basic_json/merge_patch/#complexity","text":"Linear in the lengths of apply_patch .","title":"Complexity"},{"location":"api/basic_json/merge_patch/#examples","text":"Example The following code shows how a JSON Merge Patch is applied to a JSON document. #include #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" }","title":"Examples"},{"location":"api/basic_json/merge_patch/#see-also","text":"RFC 7396 (JSON Merge Patch) patch apply a JSON patch","title":"See also"},{"location":"api/basic_json/merge_patch/#version-history","text":"Added in version 3.0.0.","title":"Version history"},{"location":"api/basic_json/meta/","text":"nlohmann::basic_json:: meta \u00b6 static basic_json meta (); This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. Return value \u00b6 JSON object holding version information key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang , icc , gcc , ilecpp , msvc , pgcpp , sunpro , and unknown ), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32 , linux , apple , unix , and unknown . url The URL of the project as string. version The version of the library. It is an object with the following keys: major , minor , and patch as defined by Semantic Versioning , and string (the version string). Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example output of the meta() function. #include #include #include using json = nlohmann :: json ; int main () { // call meta() std :: cout << std :: setw ( 4 ) << json :: meta () << '\\n' ; } Output: { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } } Note the output is platform-dependent. See also \u00b6 NLOHMANN_JSON_VERSION_MAJOR / NLOHMANN_JSON_VERSION_MINOR / NLOHMANN_JSON_VERSION_PATCH - library version information Version history \u00b6 Added in version 2.1.0.","title":"meta"},{"location":"api/basic_json/meta/#nlohmannbasic_jsonmeta","text":"static basic_json meta (); This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.","title":"nlohmann::basic_json::meta"},{"location":"api/basic_json/meta/#return-value","text":"JSON object holding version information key description compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang , icc , gcc , ilecpp , msvc , pgcpp , sunpro , and unknown ), and version (the compiler version). copyright The copyright line for the library as string. name The name of the library as string. platform The used platform as string. Possible values are win32 , linux , apple , unix , and unknown . url The URL of the project as string. version The version of the library. It is an object with the following keys: major , minor , and patch as defined by Semantic Versioning , and string (the version string).","title":"Return value"},{"location":"api/basic_json/meta/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/meta/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/meta/#examples","text":"Example The following code shows an example output of the meta() function. #include #include #include using json = nlohmann :: json ; int main () { // call meta() std :: cout << std :: setw ( 4 ) << json :: meta () << '\\n' ; } Output: { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } } Note the output is platform-dependent.","title":"Examples"},{"location":"api/basic_json/meta/#see-also","text":"NLOHMANN_JSON_VERSION_MAJOR / NLOHMANN_JSON_VERSION_MINOR / NLOHMANN_JSON_VERSION_PATCH - library version information","title":"See also"},{"location":"api/basic_json/meta/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/basic_json/number_float_t/","text":"nlohmann::basic_json:: number_float_t \u00b6 using number_float_t = NumberFloatType ; 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. Notes \u00b6 Default type \u00b6 With the default values for NumberFloatType ( double ), the default value for number_float_t is double . Default behavior \u00b6 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 . Limits \u00b6 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 . Storage \u00b6 Floating-point number values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that number_float_t is by default, a typedef to double . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < double , json :: number_float_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"number_float_t"},{"location":"api/basic_json/number_float_t/#nlohmannbasic_jsonnumber_float_t","text":"using number_float_t = NumberFloatType ; 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.","title":"nlohmann::basic_json::number_float_t"},{"location":"api/basic_json/number_float_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/number_float_t/#default-type","text":"With the default values for NumberFloatType ( double ), the default value for number_float_t is double .","title":"Default type"},{"location":"api/basic_json/number_float_t/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"api/basic_json/number_float_t/#limits","text":"RFC 8259 states: This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null .","title":"Limits"},{"location":"api/basic_json/number_float_t/#storage","text":"Floating-point number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/number_float_t/#examples","text":"Example The following code shows that number_float_t is by default, a typedef to double . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < double , json :: number_float_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/number_float_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/number_integer_t/","text":"nlohmann::basic_json:: number_integer_t \u00b6 using number_integer_t = NumberIntegerType ; The type used to store JSON numbers (integers). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use. Notes \u00b6 Default type \u00b6 With the default values for NumberIntegerType ( std::int64_t ), the default value for number_integer_t is std :: int64_t . Default behavior \u00b6 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 . Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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. Storage \u00b6 Integer number values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that number_integer_t is by default, a typedef to std :: int64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: int64_t , json :: number_integer_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"number_integer_t"},{"location":"api/basic_json/number_integer_t/#nlohmannbasic_jsonnumber_integer_t","text":"using number_integer_t = NumberIntegerType ; The type used to store JSON numbers (integers). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter NumberIntegerType which chooses the type to use.","title":"nlohmann::basic_json::number_integer_t"},{"location":"api/basic_json/number_integer_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/number_integer_t/#default-type","text":"With the default values for NumberIntegerType ( std::int64_t ), the default value for number_integer_t is std :: int64_t .","title":"Default type"},{"location":"api/basic_json/number_integer_t/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"api/basic_json/number_integer_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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.","title":"Limits"},{"location":"api/basic_json/number_integer_t/#storage","text":"Integer number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/number_integer_t/#examples","text":"Example The following code shows that number_integer_t is by default, a typedef to std :: int64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: int64_t , json :: number_integer_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/number_integer_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/number_unsigned_t/","text":"nlohmann::basic_json:: number_unsigned_t \u00b6 using number_unsigned_t = NumberUnsignedType ; The type used to store JSON numbers (unsigned). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use. Notes \u00b6 Default type \u00b6 With the default values for NumberUnsignedType ( std::uint64_t ), the default value for number_unsigned_t is std :: uint64_t . Default behavior \u00b6 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 . Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range \\f [-2^{53}+1, 2^{53}-1]\\f [-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. Storage \u00b6 Integer number values are stored directly inside a basic_json type. Examples \u00b6 Example The following code shows that number_unsigned_t is by default, a typedef to std :: uint64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: uint64_t , json :: number_unsigned_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 2.0.0.","title":"number_unsigned_t"},{"location":"api/basic_json/number_unsigned_t/#nlohmannbasic_jsonnumber_unsigned_t","text":"using number_unsigned_t = NumberUnsignedType ; The type used to store JSON numbers (unsigned). RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t and number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter NumberUnsignedType which chooses the type to use.","title":"nlohmann::basic_json::number_unsigned_t"},{"location":"api/basic_json/number_unsigned_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/number_unsigned_t/#default-type","text":"With the default values for NumberUnsignedType ( std::uint64_t ), the default value for number_unsigned_t is std :: uint64_t .","title":"Default type"},{"location":"api/basic_json/number_unsigned_t/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"api/basic_json/number_unsigned_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range \\f [-2^{53}+1, 2^{53}-1]\\f [-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.","title":"Limits"},{"location":"api/basic_json/number_unsigned_t/#storage","text":"Integer number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"api/basic_json/number_unsigned_t/#examples","text":"Example The following code shows that number_unsigned_t is by default, a typedef to std :: uint64_t . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: uint64_t , json :: number_unsigned_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/number_unsigned_t/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/object/","text":"nlohmann::basic_json:: object \u00b6 static basic_json object ( initializer_list_t init = {}); 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. Parameters \u00b6 init (in) initializer list with JSON values to create an object from (optional) Return value \u00b6 JSON object value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 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. Complexity \u00b6 Linear in the size of init . Notes \u00b6 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) . Examples \u00b6 Example The following code shows an example for the object function. #include #include using json = nlohmann :: json ; int main () { // create JSON objects json j_no_init_list = json :: object (); json j_empty_init_list = json :: object ({}); json j_list_of_pairs = json :: object ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON objects std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; // example for an exception try { // can only create an object from a list of pairs json j_invalid_object = json :: object ({{ \"one\" , 1 , 2 }}); } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: {} {} { \"one\" : 1 , \"two\" : 2 } [ jso n .excep t io n . t ype_error. 301 ] ca nn o t crea te objec t fr om i n i t ializer lis t See also \u00b6 basic_json(initializer_list_t) - create a JSON value from an initializer list array - create a JSON array value from an initializer list Version history \u00b6 Added in version 1.0.0.","title":"object"},{"location":"api/basic_json/object/#nlohmannbasic_jsonobject","text":"static basic_json object ( initializer_list_t init = {}); 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.","title":"nlohmann::basic_json::object"},{"location":"api/basic_json/object/#parameters","text":"init (in) initializer list with JSON values to create an object from (optional)","title":"Parameters"},{"location":"api/basic_json/object/#return-value","text":"JSON object value","title":"Return value"},{"location":"api/basic_json/object/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/object/#exceptions","text":"Throws type_error.301 if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to basic_json(initializer_list_t, bool, value_t) , an array would have been created from the passed initializer list init . See example below.","title":"Exceptions"},{"location":"api/basic_json/object/#complexity","text":"Linear in the size of init .","title":"Complexity"},{"location":"api/basic_json/object/#notes","text":"This function is only added for symmetry reasons. In contrast to the related function array(initializer_list_t) , there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor basic_json(initializer_list_t, bool, value_t) .","title":"Notes"},{"location":"api/basic_json/object/#examples","text":"Example The following code shows an example for the object function. #include #include using json = nlohmann :: json ; int main () { // create JSON objects json j_no_init_list = json :: object (); json j_empty_init_list = json :: object ({}); json j_list_of_pairs = json :: object ({ { \"one\" , 1 }, { \"two\" , 2 } }); // serialize the JSON objects std :: cout << j_no_init_list << '\\n' ; std :: cout << j_empty_init_list << '\\n' ; std :: cout << j_list_of_pairs << '\\n' ; // example for an exception try { // can only create an object from a list of pairs json j_invalid_object = json :: object ({{ \"one\" , 1 , 2 }}); } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: {} {} { \"one\" : 1 , \"two\" : 2 } [ jso n .excep t io n . t ype_error. 301 ] ca nn o t crea te objec t fr om i n i t ializer lis t","title":"Examples"},{"location":"api/basic_json/object/#see-also","text":"basic_json(initializer_list_t) - create a JSON value from an initializer list array - create a JSON array value from an initializer list","title":"See also"},{"location":"api/basic_json/object/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/object_comparator_t/","text":"nlohmann::basic_json:: object_comparator_t \u00b6 using object_comparator_t = typename object_t :: key_compare ; // or using object_comparator_t = default_object_comparator_t ; The comparator used by object_t . Defined as typename object_t :: key_compare if available, and default_object_comparator_t otherwise. Examples \u00b6 Example The example below demonstrates the used object comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"json::object_comparator_t( \\\" one \\\" , \\\" two \\\" ) = \" << json :: object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"json::object_comparator_t( \\\" three \\\" , \\\" four \\\" ) = \" << json :: object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: jso n :: objec t _compara t or_ t ( \"one\" , \"two\" ) = true jso n :: objec t _compara t or_ t ( \"three\" , \"four\" ) = false Version history \u00b6 Added in version 3.0.0. Changed to be conditionally defined as typename object_t :: key_compare or default_object_comparator_t in version 3.11.0.","title":"object_comparator_t"},{"location":"api/basic_json/object_comparator_t/#nlohmannbasic_jsonobject_comparator_t","text":"using object_comparator_t = typename object_t :: key_compare ; // or using object_comparator_t = default_object_comparator_t ; The comparator used by object_t . Defined as typename object_t :: key_compare if available, and default_object_comparator_t otherwise.","title":"nlohmann::basic_json::object_comparator_t"},{"location":"api/basic_json/object_comparator_t/#examples","text":"Example The example below demonstrates the used object comparator. #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << \"json::object_comparator_t( \\\" one \\\" , \\\" two \\\" ) = \" << json :: object_comparator_t {}( \"one\" , \"two\" ) << \" \\n \" << \"json::object_comparator_t( \\\" three \\\" , \\\" four \\\" ) = \" << json :: object_comparator_t {}( \"three\" , \"four\" ) << std :: endl ; } Output: jso n :: objec t _compara t or_ t ( \"one\" , \"two\" ) = true jso n :: objec t _compara t or_ t ( \"three\" , \"four\" ) = false","title":"Examples"},{"location":"api/basic_json/object_comparator_t/#version-history","text":"Added in version 3.0.0. Changed to be conditionally defined as typename object_t :: key_compare or default_object_comparator_t in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/object_t/","text":"nlohmann::basic_json:: object_t \u00b6 using object_t = ObjectType < StringType , basic_json , default_object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; 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. Template parameters \u00b6 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 is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator ) Notes \u00b6 Default type \u00b6 With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: // until C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less < std :: string > , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > // since C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > See default_object_comparator_t for more information. Behavior \u00b6 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. Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object. Storage \u00b6 Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced. Object key order \u00b6 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. Examples \u00b6 Example The following code shows that object_t is by default, a typedef to std :: map < json :: string_t , json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: map < json :: string_t , json > , json :: object_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"object_t"},{"location":"api/basic_json/object_t/#nlohmannbasic_jsonobject_t","text":"using object_t = ObjectType < StringType , basic_json , default_object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; 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.","title":"nlohmann::basic_json::object_t"},{"location":"api/basic_json/object_t/#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 is used to order elements inside the container. AllocatorType the allocator to use for objects (e.g., std::allocator )","title":"Template parameters"},{"location":"api/basic_json/object_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/object_t/#default-type","text":"With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: // until C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less < std :: string > , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > // since C++14 std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > See default_object_comparator_t for more information.","title":"Default type"},{"location":"api/basic_json/object_t/#behavior","text":"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.","title":"Behavior"},{"location":"api/basic_json/object_t/#limits","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.","title":"Limits"},{"location":"api/basic_json/object_t/#storage","text":"Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.","title":"Storage"},{"location":"api/basic_json/object_t/#object-key-order","text":"The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259 , because any order implements the specified \"unordered\" nature of JSON objects.","title":"Object key order"},{"location":"api/basic_json/object_t/#examples","text":"Example The following code shows that object_t is by default, a typedef to std :: map < json :: string_t , json > . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: map < json :: string_t , json > , json :: object_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/object_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/operator%2B%3D/","text":"nlohmann::basic_json:: operator+= \u00b6 // (1) reference operator += ( basic_json && val ); reference operator += ( const basic_json & val ); // (2) reference operator += ( const typename object_t :: value_type & val ); // (3) reference operator += ( initializer_list_t init ); 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&&) . Parameters \u00b6 val (in) the value to add to the JSON array/object init (in) an initializer list Return value \u00b6 * this Exceptions \u00b6 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\" Complexity \u00b6 Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init . Notes \u00b6 (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 , see #235 for more information. Examples \u00b6 Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]] Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"operator+="},{"location":"api/basic_json/operator%2B%3D/#nlohmannbasic_jsonoperator","text":"// (1) reference operator += ( basic_json && val ); reference operator += ( const basic_json & val ); // (2) reference operator += ( const typename object_t :: value_type & val ); // (3) reference operator += ( initializer_list_t init ); 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&&) .","title":"nlohmann::basic_json::operator+="},{"location":"api/basic_json/operator%2B%3D/#parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list","title":"Parameters"},{"location":"api/basic_json/operator%2B%3D/#return-value","text":"* this","title":"Return value"},{"location":"api/basic_json/operator%2B%3D/#exceptions","text":"All functions can throw the following exception: - Throws type_error.308 when called on a type other than JSON array or null; example: \"cannot use operator+=() with number\"","title":"Exceptions"},{"location":"api/basic_json/operator%2B%3D/#complexity","text":"Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init .","title":"Complexity"},{"location":"api/basic_json/operator%2B%3D/#notes","text":"(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list , see #235 for more information.","title":"Notes"},{"location":"api/basic_json/operator%2B%3D/#examples","text":"Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]]","title":"Examples"},{"location":"api/basic_json/operator%2B%3D/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"Version history"},{"location":"api/basic_json/operator%3D/","text":"nlohmann::basic_json:: operator= \u00b6 basic_json & operator = ( basic_json other ) noexcept ( std :: is_nothrow_move_constructible < value_t >:: value && std :: is_nothrow_move_assignable < value_t >:: value && std :: is_nothrow_move_constructible < json_value >:: value && std :: is_nothrow_move_assignable < json_value >:: value ); 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. Parameters \u00b6 other (in) value to copy from Complexity \u00b6 Linear. Examples \u00b6 Example The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b . Finally, the copy of a (which is the null value after the swap) is destroyed. #include #include using json = nlohmann :: json ; int main () { // create JSON values json a = 23 ; json b = 42 ; // copy-assign a to b b = a ; // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: 23 23 Version history \u00b6 Added in version 1.0.0.","title":"operator="},{"location":"api/basic_json/operator%3D/#nlohmannbasic_jsonoperator","text":"basic_json & operator = ( basic_json other ) noexcept ( std :: is_nothrow_move_constructible < value_t >:: value && std :: is_nothrow_move_assignable < value_t >:: value && std :: is_nothrow_move_constructible < json_value >:: value && std :: is_nothrow_move_assignable < json_value >:: value ); 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.","title":"nlohmann::basic_json::operator="},{"location":"api/basic_json/operator%3D/#parameters","text":"other (in) value to copy from","title":"Parameters"},{"location":"api/basic_json/operator%3D/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator%3D/#examples","text":"Example The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b . Finally, the copy of a (which is the null value after the swap) is destroyed. #include #include using json = nlohmann :: json ; int main () { // create JSON values json a = 23 ; json b = 42 ; // copy-assign a to b b = a ; // serialize the JSON arrays std :: cout << a << '\\n' ; std :: cout << b << '\\n' ; } Output: 23 23","title":"Examples"},{"location":"api/basic_json/operator%3D/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/operator%5B%5D/","text":"nlohmann::basic_json:: operator[] \u00b6 // (1) reference operator []( size_type idx ); const_reference operator []( size_type idx ) const ; // (2) reference operator []( typename object_t :: key_type key ); const_reference operator []( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference operator []( KeyType && key ); template < typename KeyType > const_reference operator []( KeyType && key ) const ; // (4) reference operator []( const json_pointer & ptr ); const_reference operator []( const json_pointer & ptr ) const ; 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 . Template parameters \u00b6 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). Parameters \u00b6 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 Return value \u00b6 (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 Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense. The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense. 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'. Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version. Throws out_of_range.404 if the JSON pointer ptr can not be resolved. Complexity \u00b6 Constant if idx is in the range of the array. Otherwise, linear in idx - size() . Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container. Notes \u00b6 Undefined behavior and runtime assertions 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. Examples \u00b6 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 #include using json = nlohmann :: json ; int main () { // create a JSON array json array = { 1 , 2 , 3 , 4 , 5 }; // output element at index 3 (fourth element) std :: cout << array [ 3 ] << '\\n' ; // change last element to 6 array [ array . size () - 1 ] = 6 ; // output changed array std :: cout << array << '\\n' ; // write beyond array limit array [ 10 ] = 11 ; // output changed array std :: cout << array << '\\n' ; } Output: 4 [ 1 , 2 , 3 , 4 , 6 ] [ 1 , 2 , 3 , 4 , 6 , null , null , null , null , null , 11 ] Example: (1) access specified array element (const) The example below shows how array elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; } Output: \"third\" Example: (2) access specified object element The example below shows how object elements can be read and written using the [] operator. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" ]; // write to nonexisting key object [ \"five\" ][ \"really\" ][ \"nested\" ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (2) access specified object element (const) The example below shows how object elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << '\\n' ; } Output: 2 Example: (3) access specified object element using string_view The example below shows how object elements can be read using the [] operator. #include #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" sv ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" sv ]; // write to nonexisting key object [ \"five\" sv ][ \"really\" sv ][ \"nested\" sv ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (3) access specified object element using string_view (const) The example below shows how object elements can be read using the [] operator. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << '\\n' ; } Output: 2 Example: (4) access specified element via JSON Pointer The example below shows how values can be read and written using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; // writing access // change the string j [ \"/string\" _json_pointer ] = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // \"change\" a nonexisting object entry j [ \"/boolean\" _json_pointer ] = true ; // output the changed object std :: cout << j << '\\n' ; // change an array element j [ \"/array/1\" _json_pointer ] = 21 ; // \"change\" an array element with nonexisting index j [ \"/array/4\" _json_pointer ] = 44 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // \"change\" the array element past the end j [ \"/array/-\" _json_pointer ] = 55 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" { \"array\" :[ 1 , 2 ], \"boolean\" : true , \"number\" : 1 , \"string\" : \"bar\" } [ 1 , 21 , null , null , 44 ] [ 1 , 21 , null , null , 44 , 55 ] Example: (4) access specified element via JSON Pointer (const) The example below shows how values can be read using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2 See also \u00b6 documentation on unchecked access documentation on runtime assertions see at for access by reference with range checking see value for access with default value Version history \u00b6 Added in version 1.0.0. Added in version 1.0.0. Added overloads for T* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0. Added in version 3.11.0. Added in version 2.0.0.","title":"operator[]"},{"location":"api/basic_json/operator%5B%5D/#nlohmannbasic_jsonoperator","text":"// (1) reference operator []( size_type idx ); const_reference operator []( size_type idx ) const ; // (2) reference operator []( typename object_t :: key_type key ); const_reference operator []( const typename object_t :: key_type & key ) const ; // (3) template < typename KeyType > reference operator []( KeyType && key ); template < typename KeyType > const_reference operator []( KeyType && key ) const ; // (4) reference operator []( const json_pointer & ptr ); const_reference operator []( const json_pointer & ptr ) const ; 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 .","title":"nlohmann::basic_json::operator[]"},{"location":"api/basic_json/operator%5B%5D/#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).","title":"Template parameters"},{"location":"api/basic_json/operator%5B%5D/#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","title":"Parameters"},{"location":"api/basic_json/operator%5B%5D/#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","title":"Return value"},{"location":"api/basic_json/operator%5B%5D/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/operator%5B%5D/#exceptions","text":"The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an array or null; in that case, using the [] operator with an index makes no sense. The function can throw the following exceptions: Throws type_error.305 if the JSON value is not an object or null; in that case, using the [] operator with a key makes no sense. 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'. Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. Throws out_of_range.402 if the array index '-' is used in the passed JSON pointer ptr for the const version. Throws out_of_range.404 if the JSON pointer ptr can not be resolved.","title":"Exceptions"},{"location":"api/basic_json/operator%5B%5D/#complexity","text":"Constant if idx is in the range of the array. Otherwise, linear in idx - size() . Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container.","title":"Complexity"},{"location":"api/basic_json/operator%5B%5D/#notes","text":"Undefined behavior and runtime assertions 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.","title":"Notes"},{"location":"api/basic_json/operator%5B%5D/#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 #include using json = nlohmann :: json ; int main () { // create a JSON array json array = { 1 , 2 , 3 , 4 , 5 }; // output element at index 3 (fourth element) std :: cout << array [ 3 ] << '\\n' ; // change last element to 6 array [ array . size () - 1 ] = 6 ; // output changed array std :: cout << array << '\\n' ; // write beyond array limit array [ 10 ] = 11 ; // output changed array std :: cout << array << '\\n' ; } Output: 4 [ 1 , 2 , 3 , 4 , 6 ] [ 1 , 2 , 3 , 4 , 6 , null , null , null , null , null , 11 ] Example: (1) access specified array element (const) The example below shows how array elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create JSON array const json array = { \"first\" , \"2nd\" , \"third\" , \"fourth\" }; // output element at index 2 (third element) std :: cout << array . at ( 2 ) << '\\n' ; } Output: \"third\" Example: (2) access specified object element The example below shows how object elements can be read and written using the [] operator. #include #include #include using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" ]; // write to nonexisting key object [ \"five\" ][ \"really\" ][ \"nested\" ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (2) access specified object element (const) The example below shows how object elements can be read using the [] operator. #include #include using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" ] << '\\n' ; } Output: 2 Example: (3) access specified object element using string_view The example below shows how object elements can be read using the [] operator. #include #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << \" \\n\\n \" ; // change element with key \"three\" object [ \"three\" sv ] = 3 ; // output changed array std :: cout << std :: setw ( 4 ) << object << \" \\n\\n \" ; // mention nonexisting key object [ \"four\" sv ]; // write to nonexisting key object [ \"five\" sv ][ \"really\" sv ][ \"nested\" sv ] = true ; // output changed object std :: cout << std :: setw ( 4 ) << object << '\\n' ; } Output: 2 { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"five\" : { \"really\" : { \"nested\" : true } }, \"four\" : null , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Example: (3) access specified object element using string_view (const) The example below shows how object elements can be read using the [] operator. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object const json object = { { \"one\" , 1 }, { \"two\" , 2 }, { \"three\" , 2.9 } }; // output element with key \"two\" std :: cout << object [ \"two\" sv ] << '\\n' ; } Output: 2 Example: (4) access specified element via JSON Pointer The example below shows how values can be read and written using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; // writing access // change the string j [ \"/string\" _json_pointer ] = \"bar\" ; // output the changed string std :: cout << j [ \"string\" ] << '\\n' ; // \"change\" a nonexisting object entry j [ \"/boolean\" _json_pointer ] = true ; // output the changed object std :: cout << j << '\\n' ; // change an array element j [ \"/array/1\" _json_pointer ] = 21 ; // \"change\" an array element with nonexisting index j [ \"/array/4\" _json_pointer ] = 44 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; // \"change\" the array element past the end j [ \"/array/-\" _json_pointer ] = 55 ; // output the changed array std :: cout << j [ \"array\" ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2 \"bar\" { \"array\" :[ 1 , 2 ], \"boolean\" : true , \"number\" : 1 , \"string\" : \"bar\" } [ 1 , 21 , null , null , 44 ] [ 1 , 21 , null , null , 44 , 55 ] Example: (4) access specified element via JSON Pointer (const) The example below shows how values can be read using JSON Pointers. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value const json j = { { \"number\" , 1 }, { \"string\" , \"foo\" }, { \"array\" , { 1 , 2 }} }; // read-only access // output element with JSON pointer \"/number\" std :: cout << j [ \"/number\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/string\" std :: cout << j [ \"/string\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array\" std :: cout << j [ \"/array\" _json_pointer ] << '\\n' ; // output element with JSON pointer \"/array/1\" std :: cout << j [ \"/array/1\" _json_pointer ] << '\\n' ; } Output: 1 \"foo\" [ 1 , 2 ] 2","title":"Examples"},{"location":"api/basic_json/operator%5B%5D/#see-also","text":"documentation on unchecked access documentation on runtime assertions see at for access by reference with range checking see value for access with default value","title":"See also"},{"location":"api/basic_json/operator%5B%5D/#version-history","text":"Added in version 1.0.0. Added in version 1.0.0. Added overloads for T* key in version 1.1.0. Removed overloads for T* key (replaced by 3) in version 3.11.0. Added in version 3.11.0. Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/operator_ValueType/","text":"nlohmann::basic_json:: operator ValueType \u00b6 template < typename ValueType > JSON_EXPLICIT operator ValueType () const ; 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 . Template parameters \u00b6 ValueType the value type to return Return value \u00b6 copy of the JSON value, converted to ValueType Exceptions \u00b6 Depends on what json_serializer from_json() method throws Complexity \u00b6 Linear in the size of the JSON value. Notes \u00b6 Definition of JSON_EXPLICIT By default JSON_EXPLICIT is defined to the empty string, so the signature is: template < typename ValueType > operator ValueType () const ; If JSON_USE_IMPLICIT_CONVERSIONS is set to 0 , JSON_EXPLICIT is defined to explicit : template < typename ValueType > explicit operator ValueType () const ; 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 . Examples \u00b6 Example The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use implicit conversions bool v1 = json_types [ \"boolean\" ]; int v2 = json_types [ \"number\" ][ \"integer\" ]; short v3 = json_types [ \"number\" ][ \"integer\" ]; float v4 = json_types [ \"number\" ][ \"floating-point\" ]; int v5 = json_types [ \"number\" ][ \"floating-point\" ]; std :: string v6 = json_types [ \"string\" ]; std :: vector < short > v7 = json_types [ \"array\" ]; std :: unordered_map < std :: string , json > v8 = json_types ; // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } // example for an exception try { bool v1 = json_types [ \"string\" ]; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] [ jso n .excep t io n . t ype_error. 302 ] t ype mus t be boolea n , bu t is s tr i n g Version history \u00b6 Since version 1.0.0. Macros JSON_EXPLICIT / JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.","title":"operator ValueType"},{"location":"api/basic_json/operator_ValueType/#nlohmannbasic_jsonoperator-valuetype","text":"template < typename ValueType > JSON_EXPLICIT operator ValueType () const ; 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 .","title":"nlohmann::basic_json::operator ValueType"},{"location":"api/basic_json/operator_ValueType/#template-parameters","text":"ValueType the value type to return","title":"Template parameters"},{"location":"api/basic_json/operator_ValueType/#return-value","text":"copy of the JSON value, converted to ValueType","title":"Return value"},{"location":"api/basic_json/operator_ValueType/#exceptions","text":"Depends on what json_serializer from_json() method throws","title":"Exceptions"},{"location":"api/basic_json/operator_ValueType/#complexity","text":"Linear in the size of the JSON value.","title":"Complexity"},{"location":"api/basic_json/operator_ValueType/#notes","text":"Definition of JSON_EXPLICIT By default JSON_EXPLICIT is defined to the empty string, so the signature is: template < typename ValueType > operator ValueType () const ; If JSON_USE_IMPLICIT_CONVERSIONS is set to 0 , JSON_EXPLICIT is defined to explicit : template < typename ValueType > explicit operator ValueType () const ; 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 .","title":"Notes"},{"location":"api/basic_json/operator_ValueType/#examples","text":"Example The example below shows several conversions from JSON values to other types. There are a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard std::vector , (3) A JSON object can be converted to C++ associative containers such as std::unordered_map . #include #include #include using json = nlohmann :: json ; int main () { // create a JSON value with different types json json_types = { { \"boolean\" , true }, { \"number\" , { { \"integer\" , 42 }, { \"floating-point\" , 17.23 } } }, { \"string\" , \"Hello, world!\" }, { \"array\" , { 1 , 2 , 3 , 4 , 5 }}, { \"null\" , nullptr } }; // use implicit conversions bool v1 = json_types [ \"boolean\" ]; int v2 = json_types [ \"number\" ][ \"integer\" ]; short v3 = json_types [ \"number\" ][ \"integer\" ]; float v4 = json_types [ \"number\" ][ \"floating-point\" ]; int v5 = json_types [ \"number\" ][ \"floating-point\" ]; std :: string v6 = json_types [ \"string\" ]; std :: vector < short > v7 = json_types [ \"array\" ]; std :: unordered_map < std :: string , json > v8 = json_types ; // print the conversion results std :: cout << v1 << '\\n' ; std :: cout << v2 << ' ' << v3 << '\\n' ; std :: cout << v4 << ' ' << v5 << '\\n' ; std :: cout << v6 << '\\n' ; for ( auto i : v7 ) { std :: cout << i << ' ' ; } std :: cout << \" \\n\\n \" ; for ( auto i : v8 ) { std :: cout << i . first << \": \" << i . second << '\\n' ; } // example for an exception try { bool v1 = json_types [ \"string\" ]; } catch ( const json :: type_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: 1 42 42 17.23 17 Hello , world! 1 2 3 4 5 s tr i n g : \"Hello, world!\" nu mber : { \"floating-point\" : 17.23 , \"integer\" : 42 } null : null boolea n : true array : [ 1 , 2 , 3 , 4 , 5 ] [ jso n .excep t io n . t ype_error. 302 ] t ype mus t be boolea n , bu t is s tr i n g","title":"Examples"},{"location":"api/basic_json/operator_ValueType/#version-history","text":"Since version 1.0.0. Macros JSON_EXPLICIT / JSON_USE_IMPLICIT_CONVERSIONS added in version 3.9.0.","title":"Version history"},{"location":"api/basic_json/operator_eq/","text":"nlohmann::basic_json:: operator== \u00b6 // until C++20 bool operator == ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator == ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator == ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator == ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator == ( ScalarType rhs ) const noexcept ; // (2) }; 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. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing special values 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 > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-defined operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } ... } Comparing different basic_json specializations Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects { \"version\" : 1 , \"type\" : \"integer\" } and { \"type\" : \"integer\" , \"version\" : 1 } depends on whether nlohmann::json or nlohmann::ordered_json is used: #include #include #include using json = nlohmann :: json ; int main () { nlohmann :: json uj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: json uj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; nlohmann :: ordered_json oj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: ordered_json oj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; std :: cout << std :: boolalpha << ( uj1 == uj2 ) << '\\n' << ( oj1 == oj2 ) << std :: endl ; } Output: true false Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 == array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 == object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 == number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 == string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } true 17 == 17.0 true \"foo\" == \"bar\" false Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" == nullptr \" << ( array == nullptr ) << '\\n' ; std :: cout << object << \" == nullptr \" << ( object == nullptr ) << '\\n' ; std :: cout << number << \" == nullptr \" << ( number == nullptr ) << '\\n' ; std :: cout << string << \" == nullptr \" << ( string == nullptr ) << '\\n' ; std :: cout << null << \" == nullptr \" << ( null == nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == null p tr false { \"A\" : \"a\" , \"B\" : \"b\" } == null p tr false 17 == null p tr false \"foo\" == null p tr false null == null p tr true Version history \u00b6 Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"operator=="},{"location":"api/basic_json/operator_eq/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator == ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator == ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator == ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator == ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator == ( ScalarType rhs ) const noexcept ; // (2) }; 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.","title":"nlohmann::basic_json::operator=="},{"location":"api/basic_json/operator_eq/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_eq/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_eq/#return-value","text":"whether the values lhs / *this and rhs are equal","title":"Return value"},{"location":"api/basic_json/operator_eq/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_eq/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_eq/#notes","text":"Comparing special values 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 > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-defined operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } ... } Comparing different basic_json specializations Comparing different basic_json specializations can have surprising effects. For instance, the result of comparing the JSON objects { \"version\" : 1 , \"type\" : \"integer\" } and { \"type\" : \"integer\" , \"version\" : 1 } depends on whether nlohmann::json or nlohmann::ordered_json is used: #include #include #include using json = nlohmann :: json ; int main () { nlohmann :: json uj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: json uj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; nlohmann :: ordered_json oj1 = {{ \"version\" , 1 }, { \"type\" , \"integer\" }}; nlohmann :: ordered_json oj2 = {{ \"type\" , \"integer\" }, { \"version\" , 1 }}; std :: cout << std :: boolalpha << ( uj1 == uj2 ) << '\\n' << ( oj1 == oj2 ) << std :: endl ; } Output: true false","title":"Notes"},{"location":"api/basic_json/operator_eq/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 == array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 == object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 == number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 == string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } true 17 == 17.0 true \"foo\" == \"bar\" false Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" == nullptr \" << ( array == nullptr ) << '\\n' ; std :: cout << object << \" == nullptr \" << ( object == nullptr ) << '\\n' ; std :: cout << number << \" == nullptr \" << ( number == nullptr ) << '\\n' ; std :: cout << string << \" == nullptr \" << ( string == nullptr ) << '\\n' ; std :: cout << null << \" == nullptr \" << ( null == nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == null p tr false { \"A\" : \"a\" , \"B\" : \"b\" } == null p tr false 17 == null p tr false \"foo\" == null p tr false null == null p tr true","title":"Examples"},{"location":"api/basic_json/operator_eq/#version-history","text":"Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_ge/","text":"nlohmann::basic_json:: operator>= \u00b6 // until C++20 bool operator >= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator >= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator >= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is less than or equal to rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" >= \" << array_2 << \" \" << ( array_1 >= array_2 ) << '\\n' ; std :: cout << object_1 << \" >= \" << object_2 << \" \" << ( object_1 >= object_2 ) << '\\n' ; std :: cout << number_1 << \" >= \" << number_2 << \" \" << ( number_1 >= number_2 ) << '\\n' ; std :: cout << string_1 << \" >= \" << string_2 << \" \" << ( string_1 >= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] >= [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } >= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 >= 17.0000000000001 false \"foo\" >= \"bar\" true See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator>="},{"location":"api/basic_json/operator_ge/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator >= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator >= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator >= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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.","title":"nlohmann::basic_json::operator>="},{"location":"api/basic_json/operator_ge/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_ge/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_ge/#return-value","text":"whether lhs is less than or equal to rhs","title":"Return value"},{"location":"api/basic_json/operator_ge/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_ge/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_ge/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_ge/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" >= \" << array_2 << \" \" << ( array_1 >= array_2 ) << '\\n' ; std :: cout << object_1 << \" >= \" << object_2 << \" \" << ( object_1 >= object_2 ) << '\\n' ; std :: cout << number_1 << \" >= \" << number_2 << \" \" << ( number_1 >= number_2 ) << '\\n' ; std :: cout << string_1 << \" >= \" << string_2 << \" \" << ( string_1 >= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] >= [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } >= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 >= 17.0000000000001 false \"foo\" >= \"bar\" true","title":"Examples"},{"location":"api/basic_json/operator_ge/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_ge/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_gt/","text":"nlohmann::basic_json:: operator> \u00b6 // until C++20 bool operator > ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator > ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator > ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is greater than rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" > \" << array_2 << \" \" << ( array_1 > array_2 ) << '\\n' ; std :: cout << object_1 << \" > \" << object_2 << \" \" << ( object_1 > object_2 ) << '\\n' ; std :: cout << number_1 << \" > \" << number_2 << \" \" << ( number_1 > number_2 ) << '\\n' ; std :: cout << string_1 << \" > \" << string_2 << \" \" << ( string_1 > string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] > [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } > { \"A\" : \"a\" , \"B\" : \"b\" } false 17 > 17.0000000000001 false \"foo\" > \"bar\" true See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator>"},{"location":"api/basic_json/operator_gt/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator > ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator > ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator > ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.","title":"nlohmann::basic_json::operator>"},{"location":"api/basic_json/operator_gt/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_gt/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_gt/#return-value","text":"whether lhs is greater than rhs","title":"Return value"},{"location":"api/basic_json/operator_gt/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_gt/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_gt/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_gt/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" > \" << array_2 << \" \" << ( array_1 > array_2 ) << '\\n' ; std :: cout << object_1 << \" > \" << object_2 << \" \" << ( object_1 > object_2 ) << '\\n' ; std :: cout << number_1 << \" > \" << number_2 << \" \" << ( number_1 > number_2 ) << '\\n' ; std :: cout << string_1 << \" > \" << string_2 << \" \" << ( string_1 > string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] > [ 1 , 2 , 4 ] false { \"A\" : \"a\" , \"B\" : \"b\" } > { \"A\" : \"a\" , \"B\" : \"b\" } false 17 > 17.0000000000001 false \"foo\" > \"bar\" true","title":"Examples"},{"location":"api/basic_json/operator_gt/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_gt/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_le/","text":"nlohmann::basic_json:: operator<= \u00b6 // until C++20 bool operator <= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator <= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator <= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is less than or equal to rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" <= \" << array_2 << \" \" << ( array_1 <= array_2 ) << '\\n' ; std :: cout << object_1 << \" <= \" << object_2 << \" \" << ( object_1 <= object_2 ) << '\\n' ; std :: cout << number_1 << \" <= \" << number_2 << \" \" << ( number_1 <= number_2 ) << '\\n' ; std :: cout << string_1 << \" <= \" << string_2 << \" \" << ( string_1 <= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] <= [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } <= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 <= 17.0000000000001 true \"foo\" <= \"bar\" false See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator<="},{"location":"api/basic_json/operator_le/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator <= ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator <= ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator <= ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than or equal to a scalar or a scalar is less than or equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.","title":"nlohmann::basic_json::operator<="},{"location":"api/basic_json/operator_le/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_le/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_le/#return-value","text":"whether lhs is less than or equal to rhs","title":"Return value"},{"location":"api/basic_json/operator_le/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_le/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_le/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_le/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" <= \" << array_2 << \" \" << ( array_1 <= array_2 ) << '\\n' ; std :: cout << object_1 << \" <= \" << object_2 << \" \" << ( object_1 <= object_2 ) << '\\n' ; std :: cout << number_1 << \" <= \" << number_2 << \" \" << ( number_1 <= number_2 ) << '\\n' ; std :: cout << string_1 << \" <= \" << string_2 << \" \" << ( string_1 <= string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] <= [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } <= { \"A\" : \"a\" , \"B\" : \"b\" } true 17 <= 17.0000000000001 true \"foo\" <= \"bar\" false","title":"Examples"},{"location":"api/basic_json/operator_le/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_le/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_lt/","text":"nlohmann::basic_json:: operator< \u00b6 // until C++20 bool operator < ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator < ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator < ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether lhs is less than rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> . Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 < array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 < object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 < number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 < string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } false 17 == 17.0000000000001 true \"foo\" == \"bar\" false See also \u00b6 operator<=> comparison: 3-way Version history \u00b6 Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"operator<"},{"location":"api/basic_json/operator_lt/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator < ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator < ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator < ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) 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 wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1.","title":"nlohmann::basic_json::operator<"},{"location":"api/basic_json/operator_lt/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_lt/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_lt/#return-value","text":"whether lhs is less than rhs","title":"Return value"},{"location":"api/basic_json/operator_lt/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_lt/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_lt/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator<=> .","title":"Notes"},{"location":"api/basic_json/operator_lt/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.0000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" == \" << array_2 << \" \" << ( array_1 < array_2 ) << '\\n' ; std :: cout << object_1 << \" == \" << object_2 << \" \" << ( object_1 < object_2 ) << '\\n' ; std :: cout << number_1 << \" == \" << number_2 << \" \" << ( number_1 < number_2 ) << '\\n' ; std :: cout << string_1 << \" == \" << string_2 << \" \" << ( string_1 < string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] == [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } == { \"A\" : \"a\" , \"B\" : \"b\" } false 17 == 17.0000000000001 true \"foo\" == \"bar\" false","title":"Examples"},{"location":"api/basic_json/operator_lt/#see-also","text":"operator<=> comparison: 3-way","title":"See also"},{"location":"api/basic_json/operator_lt/#version-history","text":"Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_ne/","text":"nlohmann::basic_json:: operator!= \u00b6 // until C++20 bool operator != ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator != ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator != ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator != ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator != ( ScalarType rhs ) const noexcept ; // (2) }; 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. Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are not equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number. Examples \u00b6 Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" != \" << array_2 << \" \" << ( array_1 != array_2 ) << '\\n' ; std :: cout << object_1 << \" != \" << object_2 << \" \" << ( object_1 != object_2 ) << '\\n' ; std :: cout << number_1 << \" != \" << number_2 << \" \" << ( number_1 != number_2 ) << '\\n' ; std :: cout << string_1 << \" != \" << string_2 << \" \" << ( string_1 != string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } != { \"A\" : \"a\" , \"B\" : \"b\" } false 17 != 17.0 false \"foo\" != \"bar\" true Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" != nullptr \" << ( array != nullptr ) << '\\n' ; std :: cout << object << \" != nullptr \" << ( object != nullptr ) << '\\n' ; std :: cout << number << \" != nullptr \" << ( number != nullptr ) << '\\n' ; std :: cout << string << \" != nullptr \" << ( string != nullptr ) << '\\n' ; std :: cout << null << \" != nullptr \" << ( null != nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != null p tr true { \"A\" : \"a\" , \"B\" : \"b\" } != null p tr true 17 != null p tr true \"foo\" != null p tr true null != null p tr false Version history \u00b6 Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"operator!="},{"location":"api/basic_json/operator_ne/#nlohmannbasic_jsonoperator","text":"// until C++20 bool operator != ( const_reference lhs , const_reference rhs ) noexcept ; // (1) template < typename ScalarType > bool operator != ( const_reference lhs , const ScalarType rhs ) noexcept ; // (2) template < typename ScalarType > bool operator != ( ScalarType lhs , const const_reference rhs ) noexcept ; // (2) // since C++20 class basic_json { bool operator != ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > bool operator != ( ScalarType rhs ) const noexcept ; // (2) }; 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.","title":"nlohmann::basic_json::operator!="},{"location":"api/basic_json/operator_ne/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_ne/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_ne/#return-value","text":"whether the values lhs / *this and rhs are not equal","title":"Return value"},{"location":"api/basic_json/operator_ne/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_ne/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_ne/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield false : 1. Comparing a NaN with itself. 2. Comparing a NaN with another NaN . 3. Comparing a NaN and any other number.","title":"Notes"},{"location":"api/basic_json/operator_ne/#examples","text":"Example The example demonstrates comparing several JSON types. #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number_1 = 17 ; json number_2 = 17.000000000000001L ; json string_1 = \"foo\" ; json string_2 = \"bar\" ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array_1 << \" != \" << array_2 << \" \" << ( array_1 != array_2 ) << '\\n' ; std :: cout << object_1 << \" != \" << object_2 << \" \" << ( object_1 != object_2 ) << '\\n' ; std :: cout << number_1 << \" != \" << number_2 << \" \" << ( number_1 != number_2 ) << '\\n' ; std :: cout << string_1 << \" != \" << string_2 << \" \" << ( string_1 != string_2 ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != [ 1 , 2 , 4 ] true { \"A\" : \"a\" , \"B\" : \"b\" } != { \"A\" : \"a\" , \"B\" : \"b\" } false 17 != 17.0 false \"foo\" != \"bar\" true Example The example demonstrates comparing several JSON types against the null pointer (JSON null ). #include #include using json = nlohmann :: json ; int main () { // create several JSON values json array = { 1 , 2 , 3 }; json object = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json number = 17 ; json string = \"foo\" ; json null ; // output values and comparisons std :: cout << std :: boolalpha ; std :: cout << array << \" != nullptr \" << ( array != nullptr ) << '\\n' ; std :: cout << object << \" != nullptr \" << ( object != nullptr ) << '\\n' ; std :: cout << number << \" != nullptr \" << ( number != nullptr ) << '\\n' ; std :: cout << string << \" != nullptr \" << ( string != nullptr ) << '\\n' ; std :: cout << null << \" != nullptr \" << ( null != nullptr ) << '\\n' ; } Output: [ 1 , 2 , 3 ] != null p tr true { \"A\" : \"a\" , \"B\" : \"b\" } != null p tr true 17 != null p tr true \"foo\" != null p tr true null != null p tr false","title":"Examples"},{"location":"api/basic_json/operator_ne/#version-history","text":"Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_spaceship/","text":"nlohmann::basic_json:: operator<=> \u00b6 // since C++20 class basic_json { std :: partial_ordering operator <=> ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > std :: partial_ordering operator <=> ( const ScalarType rhs ) const noexcept ; // (2) }; 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). Template parameters \u00b6 ScalarType a scalar type according to std::is_scalar::value Parameters \u00b6 rhs (in) second value to consider Return value \u00b6 the std::partial_ordering of the 3-way comparison of *this and rhs Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Linear. Notes \u00b6 Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered : Comparing a NaN with itself. Comparing a NaN with another NaN . Comparing a NaN and any other number. Examples \u00b6 Example: (1) comparing JSON values The example demonstrates comparing several JSON values. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number = 17 ; json string = \"foo\" ; json discarded = json ( json :: value_t :: discarded ); // output values and comparisons std :: cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string ( array_1 <=> array_2 ) << '\\n' ; // *NOPAD* std :: cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string ( object_1 <=> object_2 ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << number << \" := \" << to_string ( string <=> number ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << discarded << \" := \" << to_string ( string <=> discarded ) << '\\n' ; // *NOPAD* } Output: [ 1 , 2 , 3 ] <=> [ 1 , 2 , 4 ] : = less { \"A\" : \"a\" , \"B\" : \"b\" } <=> { \"A\" : \"a\" , \"B\" : \"b\" } : = equivale nt \"foo\" <=> 17 : = grea ter \"foo\" <=> : = u n ordered Example: (2) comparing JSON values and scalars The example demonstrates comparing several JSON values and scalars. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { using float_limits = std :: numeric_limits < json :: number_float_t > ; constexpr auto nan = float_limits :: quiet_NaN (); // create several JSON values json boolean = false ; json number = 17 ; json string = \"17\" ; // output values and comparisons std :: cout << std :: boolalpha << std :: fixed ; std :: cout << boolean << \" <=> \" << true << \" := \" << to_string ( boolean <=> true ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << 17.0 << \" := \" << to_string ( number <=> 17.0 ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << nan << \" := \" << to_string ( number <=> nan ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << 17 << \" := \" << to_string ( string <=> 17 ) << '\\n' ; // *NOPAD* } Output: false <=> true : = less 17 <=> 17.000000 : = equivale nt 17 <=> nan : = u n ordered \"17\" <=> 17 : = grea ter See also \u00b6 operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator<= - comparison: less than or equal operator> - comparison: greater than operator>= - comparison: greater than or equal Version history \u00b6 Added in version 3.11.0. Added in version 3.11.0.","title":"operator<=>"},{"location":"api/basic_json/operator_spaceship/#nlohmannbasic_jsonoperator","text":"// since C++20 class basic_json { std :: partial_ordering operator <=> ( const_reference rhs ) const noexcept ; // (1) template < typename ScalarType > std :: partial_ordering operator <=> ( const ScalarType rhs ) const noexcept ; // (2) }; 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).","title":"nlohmann::basic_json::operator<=>"},{"location":"api/basic_json/operator_spaceship/#template-parameters","text":"ScalarType a scalar type according to std::is_scalar::value","title":"Template parameters"},{"location":"api/basic_json/operator_spaceship/#parameters","text":"rhs (in) second value to consider","title":"Parameters"},{"location":"api/basic_json/operator_spaceship/#return-value","text":"the std::partial_ordering of the 3-way comparison of *this and rhs","title":"Return value"},{"location":"api/basic_json/operator_spaceship/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_spaceship/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/operator_spaceship/#notes","text":"Comparing NaN NaN values are unordered within the domain of numbers. The following comparisons all yield std::partial_ordering::unordered : Comparing a NaN with itself. Comparing a NaN with another NaN . Comparing a NaN and any other number.","title":"Notes"},{"location":"api/basic_json/operator_spaceship/#examples","text":"Example: (1) comparing JSON values The example demonstrates comparing several JSON values. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { // create several JSON values json array_1 = { 1 , 2 , 3 }; json array_2 = { 1 , 2 , 4 }; json object_1 = {{ \"A\" , \"a\" }, { \"B\" , \"b\" }}; json object_2 = {{ \"B\" , \"b\" }, { \"A\" , \"a\" }}; json number = 17 ; json string = \"foo\" ; json discarded = json ( json :: value_t :: discarded ); // output values and comparisons std :: cout << array_1 << \" <=> \" << array_2 << \" := \" << to_string ( array_1 <=> array_2 ) << '\\n' ; // *NOPAD* std :: cout << object_1 << \" <=> \" << object_2 << \" := \" << to_string ( object_1 <=> object_2 ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << number << \" := \" << to_string ( string <=> number ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << discarded << \" := \" << to_string ( string <=> discarded ) << '\\n' ; // *NOPAD* } Output: [ 1 , 2 , 3 ] <=> [ 1 , 2 , 4 ] : = less { \"A\" : \"a\" , \"B\" : \"b\" } <=> { \"A\" : \"a\" , \"B\" : \"b\" } : = equivale nt \"foo\" <=> 17 : = grea ter \"foo\" <=> : = u n ordered Example: (2) comparing JSON values and scalars The example demonstrates comparing several JSON values and scalars. #include #include #include using json = nlohmann :: json ; const char * to_string ( const std :: partial_ordering & po ) { if ( std :: is_lt ( po )) { return \"less\" ; } else if ( std :: is_gt ( po )) { return \"greater\" ; } else if ( std :: is_eq ( po )) { return \"equivalent\" ; } return \"unordered\" ; } int main () { using float_limits = std :: numeric_limits < json :: number_float_t > ; constexpr auto nan = float_limits :: quiet_NaN (); // create several JSON values json boolean = false ; json number = 17 ; json string = \"17\" ; // output values and comparisons std :: cout << std :: boolalpha << std :: fixed ; std :: cout << boolean << \" <=> \" << true << \" := \" << to_string ( boolean <=> true ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << 17.0 << \" := \" << to_string ( number <=> 17.0 ) << '\\n' ; // *NOPAD* std :: cout << number << \" <=> \" << nan << \" := \" << to_string ( number <=> nan ) << '\\n' ; // *NOPAD* std :: cout << string << \" <=> \" << 17 << \" := \" << to_string ( string <=> 17 ) << '\\n' ; // *NOPAD* } Output: false <=> true : = less 17 <=> 17.000000 : = equivale nt 17 <=> nan : = u n ordered \"17\" <=> 17 : = grea ter","title":"Examples"},{"location":"api/basic_json/operator_spaceship/#see-also","text":"operator== - comparison: equal operator!= - comparison: not equal operator< - comparison: less than operator<= - comparison: less than or equal operator> - comparison: greater than operator>= - comparison: greater than or equal","title":"See also"},{"location":"api/basic_json/operator_spaceship/#version-history","text":"Added in version 3.11.0. Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/operator_value_t/","text":"nlohmann::basic_json:: operator value_t \u00b6 constexpr operator value_t () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration. Return value \u00b6 the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies operator value_t() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call operator value_t() json :: value_t t_null = j_null ; json :: value_t t_boolean = j_boolean ; json :: value_t t_number_integer = j_number_integer ; json :: value_t t_number_unsigned = j_number_unsigned ; json :: value_t t_number_float = j_number_float ; json :: value_t t_object = j_object ; json :: value_t t_array = j_array ; json :: value_t t_string = j_string ; // print types std :: cout << std :: boolalpha ; std :: cout << ( t_null == json :: value_t :: null ) << '\\n' ; std :: cout << ( t_boolean == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( t_number_integer == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( t_number_unsigned == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( t_number_float == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( t_object == json :: value_t :: object ) << '\\n' ; std :: cout << ( t_array == json :: value_t :: array ) << '\\n' ; std :: cout << ( t_string == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true Version history \u00b6 Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"operator value_t"},{"location":"api/basic_json/operator_value_t/#nlohmannbasic_jsonoperator-value_t","text":"constexpr operator value_t () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration.","title":"nlohmann::basic_json::operator value_t"},{"location":"api/basic_json/operator_value_t/#return-value","text":"the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded","title":"Return value"},{"location":"api/basic_json/operator_value_t/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/operator_value_t/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/operator_value_t/#examples","text":"Example The following code exemplifies operator value_t() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call operator value_t() json :: value_t t_null = j_null ; json :: value_t t_boolean = j_boolean ; json :: value_t t_number_integer = j_number_integer ; json :: value_t t_number_unsigned = j_number_unsigned ; json :: value_t t_number_float = j_number_float ; json :: value_t t_object = j_object ; json :: value_t t_array = j_array ; json :: value_t t_string = j_string ; // print types std :: cout << std :: boolalpha ; std :: cout << ( t_null == json :: value_t :: null ) << '\\n' ; std :: cout << ( t_boolean == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( t_number_integer == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( t_number_unsigned == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( t_number_float == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( t_object == json :: value_t :: object ) << '\\n' ; std :: cout << ( t_array == json :: value_t :: array ) << '\\n' ; std :: cout << ( t_string == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true","title":"Examples"},{"location":"api/basic_json/operator_value_t/#version-history","text":"Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/other_error/","text":"nlohmann::basic_json:: other_error \u00b6 class other_error : public exception ; This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx (see list of other errors ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .o t her_error. 501 ] u nsu ccess ful : { \"op\" : \"test\" , \"path\" : \"/best_biscuit/name\" , \"value\" : \"Choco Leibniz\" } excep t io n id : 501 See also \u00b6 List of other errors 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 Version history \u00b6 Since version 3.0.0.","title":"other_error"},{"location":"api/basic_json/other_error/#nlohmannbasic_jsonother_error","text":"class other_error : public exception ; This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx (see list of other errors ).","title":"nlohmann::basic_json::other_error"},{"location":"api/basic_json/other_error/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/other_error/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/other_error/#examples","text":"Example The following code shows how a other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .o t her_error. 501 ] u nsu ccess ful : { \"op\" : \"test\" , \"path\" : \"/best_biscuit/name\" , \"value\" : \"Choco Leibniz\" } excep t io n id : 501","title":"Examples"},{"location":"api/basic_json/other_error/#see-also","text":"List of other errors 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","title":"See also"},{"location":"api/basic_json/other_error/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/out_of_range/","text":"nlohmann::basic_json:: out_of_range \u00b6 class out_of_range : public exception ; 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 ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge excep t io n id : 401 See also \u00b6 List of out-of-range errors 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 other_error for exceptions indicating other library errors Version history \u00b6 Since version 3.0.0.","title":"out_of_range"},{"location":"api/basic_json/out_of_range/#nlohmannbasic_jsonout_of_range","text":"class out_of_range : public exception ; 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 ).","title":"nlohmann::basic_json::out_of_range"},{"location":"api/basic_json/out_of_range/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/out_of_range/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/out_of_range/#examples","text":"Example The following code shows how a out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n .ou t _o f _ra n ge. 401 ] array i n dex 4 is ou t o f ra n ge excep t io n id : 401","title":"Examples"},{"location":"api/basic_json/out_of_range/#see-also","text":"List of out-of-range errors 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 other_error for exceptions indicating other library errors","title":"See also"},{"location":"api/basic_json/out_of_range/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/parse/","text":"nlohmann::basic_json:: parse \u00b6 // (1) template < typename InputType > static basic_json parse ( InputType && i , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); // (2) template < typename IteratorType > static basic_json parse ( IteratorType first , IteratorType last , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); Deserialize from a compatible input. Deserialize from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len Parameters \u00b6 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 Return value \u00b6 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 . Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails. Complexity \u00b6 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. Notes \u00b6 (1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion . Examples \u00b6 Parsing from a character array The example below demonstrates the parse() function reading from an array. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text char text [] = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a string The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from an input stream The example below demonstrates the parse() function with and without callback function. #include #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // fill a stream with JSON text std :: stringstream ss ; ss << text ; // parse and serialize JSON json j_complete = json :: parse ( ss ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // fill a stream with JSON text ss . clear (); ss << text ; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( ss , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a contiguous container The example below demonstrates the parse() function reading from a contiguous container. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as std::vector std :: vector < std :: uint8_t > text = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , '\\0' }; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from a non null-terminated string The example below demonstrates the parse() function reading from a string that is not null-terminated. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as string that is not null-terminated const char * ptr = \"[1,2,3]another value\" ; // parse and serialize JSON json j_complete = json :: parse ( ptr , ptr + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from an iterator pair The example below demonstrates the parse() function reading from an iterator pair. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given an input with other values std :: vector < std :: uint8_t > input = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , 'o' , 't' , 'h' , 'e' , 'r' }; // parse and serialize JSON json j_complete = json :: parse ( input . begin (), input . begin () + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Effect of allow_exceptions parameter The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function. #include #include using json = nlohmann :: json ; int main () { // an invalid JSON text std :: string text = R \" ( { \"key\": \"value without closing quotes } ) \" ; // parse with exceptions try { json j = json :: parse ( text ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // parse without exceptions json j = json :: parse ( text , nullptr , false ); if ( j . is_discarded ()) { std :: cout << \"the input is invalid JSON\" << std :: endl ; } else { std :: cout << \"the input is valid JSON: \" << j << std :: endl ; } } Output: [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 4 , colum n 0 : sy nta x error while parsi n g value - i n valid s tr i n g : co ntr ol charac ter U+ 000 A (LF) mus t be escaped t o \\u 000 A or \\ n ; las t read : '\"value without closing quotes' the input is invalid JSON See also \u00b6 accept - check if the input is valid JSON operator>> - deserialize from stream Version history \u00b6 Added in version 1.0.0. Overload for contiguous containers (1) added in version 2.0.3. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"parse"},{"location":"api/basic_json/parse/#nlohmannbasic_jsonparse","text":"// (1) template < typename InputType > static basic_json parse ( InputType && i , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); // (2) template < typename IteratorType > static basic_json parse ( IteratorType first , IteratorType last , const parser_callback_t cb = nullptr , const bool allow_exceptions = true , const bool ignore_comments = false ); Deserialize from a compatible input. Deserialize from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.","title":"nlohmann::basic_json::parse"},{"location":"api/basic_json/parse/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer (must not be null) a C-style array of characters a pointer to a null-terminated string of single byte characters 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::iterator a pair of pointers such as ptr and ptr + len","title":"Template parameters"},{"location":"api/basic_json/parse/#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","title":"Parameters"},{"location":"api/basic_json/parse/#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 .","title":"Return value"},{"location":"api/basic_json/parse/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/parse/#exceptions","text":"Throws parse_error.101 in case of an unexpected token. Throws parse_error.102 if to_unicode fails or surrogate error. Throws parse_error.103 if to_unicode fails.","title":"Exceptions"},{"location":"api/basic_json/parse/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb or reading from (1) the input i or (2) the iterator range [ first , last ] has a super-linear complexity.","title":"Complexity"},{"location":"api/basic_json/parse/#notes","text":"(1) A UTF-8 byte order mark is silently ignored. Runtime assertion The precondition that a passed FILE pointer must not be null is enforced with a runtime assertion .","title":"Notes"},{"location":"api/basic_json/parse/#examples","text":"Parsing from a character array The example below demonstrates the parse() function reading from an array. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text char text [] = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a string The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from an input stream The example below demonstrates the parse() function with and without callback function. #include #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // fill a stream with JSON text std :: stringstream ss ; ss << text ; // parse and serialize JSON json j_complete = json :: parse ( ss ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // fill a stream with JSON text ss . clear (); ss << text ; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( ss , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Parsing from a contiguous container The example below demonstrates the parse() function reading from a contiguous container. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as std::vector std :: vector < std :: uint8_t > text = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , '\\0' }; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from a non null-terminated string The example below demonstrates the parse() function reading from a string that is not null-terminated. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given as string that is not null-terminated const char * ptr = \"[1,2,3]another value\" ; // parse and serialize JSON json j_complete = json :: parse ( ptr , ptr + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Parsing from an iterator pair The example below demonstrates the parse() function reading from an iterator pair. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text given an input with other values std :: vector < std :: uint8_t > input = { '[' , '1' , ',' , '2' , ',' , '3' , ']' , 'o' , 't' , 'h' , 'e' , 'r' }; // parse and serialize JSON json j_complete = json :: parse ( input . begin (), input . begin () + 7 ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; } Output: [ 1 , 2 , 3 ] Effect of allow_exceptions parameter The example below demonstrates the effect of the allow_exceptions parameter in the \u00b4parse()` function. #include #include using json = nlohmann :: json ; int main () { // an invalid JSON text std :: string text = R \" ( { \"key\": \"value without closing quotes } ) \" ; // parse with exceptions try { json j = json :: parse ( text ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << std :: endl ; } // parse without exceptions json j = json :: parse ( text , nullptr , false ); if ( j . is_discarded ()) { std :: cout << \"the input is invalid JSON\" << std :: endl ; } else { std :: cout << \"the input is valid JSON: \" << j << std :: endl ; } } Output: [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 4 , colum n 0 : sy nta x error while parsi n g value - i n valid s tr i n g : co ntr ol charac ter U+ 000 A (LF) mus t be escaped t o \\u 000 A or \\ n ; las t read : '\"value without closing quotes' the input is invalid JSON","title":"Examples"},{"location":"api/basic_json/parse/#see-also","text":"accept - check if the input is valid JSON operator>> - deserialize from stream","title":"See also"},{"location":"api/basic_json/parse/#version-history","text":"Added in version 1.0.0. Overload for contiguous containers (1) added in version 2.0.3. Ignoring comments via ignore_comments added in version 3.9.0. 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.","title":"Version history"},{"location":"api/basic_json/parse_error/","text":"nlohmann::basic_json:: parse_error \u00b6 class parse_error : public exception ; 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 ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception byte - byte index of the parse error Notes \u00b6 For an input with n n bytes, 1 is the index of the first character and n+1 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. Examples \u00b6 Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message : [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 1 , colum n 8 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d ' [ ' , ' { ' , or a li teral excep t io n id : 101 by te posi t io n o f error : 8 See also \u00b6 List of parse errors 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 Version history \u00b6 Since version 3.0.0.","title":"parse_error"},{"location":"api/basic_json/parse_error/#nlohmannbasic_jsonparse_error","text":"class parse_error : public exception ; 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 ).","title":"nlohmann::basic_json::parse_error"},{"location":"api/basic_json/parse_error/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/parse_error/#member-variables","text":"id - the id of the exception byte - byte index of the parse error","title":"Member variables"},{"location":"api/basic_json/parse_error/#notes","text":"For an input with n n bytes, 1 is the index of the first character and n+1 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.","title":"Notes"},{"location":"api/basic_json/parse_error/#examples","text":"Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message : [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 1 , colum n 8 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d ' [ ' , ' { ' , or a li teral excep t io n id : 101 by te posi t io n o f error : 8","title":"Examples"},{"location":"api/basic_json/parse_error/#see-also","text":"List of parse errors 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","title":"See also"},{"location":"api/basic_json/parse_error/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/parse_event_t/","text":"nlohmann::basic_json:: parse_event_t \u00b6 enum class parse_event_t : std :: uint8_t { object_start , object_end , array_start , array_end , key , value }; The parser callback distinguishes the following events: object_start : the parser read { and started to process a JSON object key : the parser read a key of a value in an object object_end : the parser read } and finished processing a JSON object array_start : the parser read [ and started to process a JSON array array_end : the parser read ] and finished processing a JSON array value : the parser finished reading a JSON value Examples \u00b6 Version history \u00b6 Added in version 1.0.0.","title":"parse_event_t"},{"location":"api/basic_json/parse_event_t/#nlohmannbasic_jsonparse_event_t","text":"enum class parse_event_t : std :: uint8_t { object_start , object_end , array_start , array_end , key , value }; The parser callback distinguishes the following events: object_start : the parser read { and started to process a JSON object key : the parser read a key of a value in an object object_end : the parser read } and finished processing a JSON object array_start : the parser read [ and started to process a JSON array array_end : the parser read ] and finished processing a JSON array value : the parser finished reading a JSON value","title":"nlohmann::basic_json::parse_event_t"},{"location":"api/basic_json/parse_event_t/#examples","text":"","title":"Examples"},{"location":"api/basic_json/parse_event_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/parser_callback_t/","text":"nlohmann::basic_json:: parser_callback_t \u00b6 template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ; With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Discarding a value (i.e., returning false ) has different effects depending on the context in which function was called: 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. Parameters \u00b6 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 Return value \u00b6 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. Examples \u00b6 Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } Version history \u00b6 Added in version 1.0.0.","title":"parser_callback_t"},{"location":"api/basic_json/parser_callback_t/#nlohmannbasic_jsonparser_callback_t","text":"template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ; With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Discarding a value (i.e., returning false ) has different effects depending on the context in which function was called: 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.","title":"nlohmann::basic_json::parser_callback_t"},{"location":"api/basic_json/parser_callback_t/#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","title":"Parameters"},{"location":"api/basic_json/parser_callback_t/#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.","title":"Return value"},{"location":"api/basic_json/parser_callback_t/#examples","text":"Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } }","title":"Examples"},{"location":"api/basic_json/parser_callback_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/patch/","text":"nlohmann::basic_json:: patch \u00b6 basic_json patch ( const basic_json & json_patch ) const ; 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. Parameters \u00b6 json_patch (in) JSON patch document Return value \u00b6 patched document Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Exceptions \u00b6 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. Complexity \u00b6 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. Notes \u00b6 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. Examples \u00b6 Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } See also \u00b6 RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch_inplace applies a JSON Patch without creating a copy of the document merge_patch applies a JSON Merge Patch Version history \u00b6 Added in version 2.0.0.","title":"patch"},{"location":"api/basic_json/patch/#nlohmannbasic_jsonpatch","text":"basic_json patch ( const basic_json & json_patch ) const ; 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.","title":"nlohmann::basic_json::patch"},{"location":"api/basic_json/patch/#parameters","text":"json_patch (in) JSON patch document","title":"Parameters"},{"location":"api/basic_json/patch/#return-value","text":"patched document","title":"Return value"},{"location":"api/basic_json/patch/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/patch/#exceptions","text":"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.","title":"Exceptions"},{"location":"api/basic_json/patch/#complexity","text":"Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.","title":"Complexity"},{"location":"api/basic_json/patch/#notes","text":"The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value.","title":"Notes"},{"location":"api/basic_json/patch/#examples","text":"Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Examples"},{"location":"api/basic_json/patch/#see-also","text":"RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch_inplace applies a JSON Patch without creating a copy of the document merge_patch applies a JSON Merge Patch","title":"See also"},{"location":"api/basic_json/patch/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/patch_inplace/","text":"nlohmann::basic_json:: patch_inplace \u00b6 void patch_inplace ( const basic_json & json_patch ) const ; 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. Parameters \u00b6 json_patch (in) JSON patch document Exception safety \u00b6 No guarantees, value may be corrupted by an unsuccessful patch operation. Exceptions \u00b6 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. Complexity \u00b6 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. Notes \u00b6 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. Examples \u00b6 Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // output original document std :: cout << \"Before \\n \" << std :: setw ( 4 ) << doc << std :: endl ; // apply the patch doc . patch_inplace ( patch ); // output patched document std :: cout << \" \\n After \\n \" << std :: setw ( 4 ) << doc << std :: endl ; } Output: Be f ore { \"baz\" : \"qux\" , \"foo\" : \"bar\" } A fter { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } See also \u00b6 RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch applies a JSON Merge Patch merge_patch applies a JSON Merge Patch Version history \u00b6 Added in version 3.11.0.","title":"patch_inplace"},{"location":"api/basic_json/patch_inplace/#nlohmannbasic_jsonpatch_inplace","text":"void patch_inplace ( const basic_json & json_patch ) const ; 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.","title":"nlohmann::basic_json::patch_inplace"},{"location":"api/basic_json/patch_inplace/#parameters","text":"json_patch (in) JSON patch document","title":"Parameters"},{"location":"api/basic_json/patch_inplace/#exception-safety","text":"No guarantees, value may be corrupted by an unsuccessful patch operation.","title":"Exception safety"},{"location":"api/basic_json/patch_inplace/#exceptions","text":"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.","title":"Exceptions"},{"location":"api/basic_json/patch_inplace/#complexity","text":"Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected.","title":"Complexity"},{"location":"api/basic_json/patch_inplace/#notes","text":"Unlike patch , patch_inplace applies the operation \"in place\" and no copy of the JSON value is created. That makes it faster for large documents by avoiding the copy. However, the JSON value might be corrupted if the function throws an exception.","title":"Notes"},{"location":"api/basic_json/patch_inplace/#examples","text":"Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // output original document std :: cout << \"Before \\n \" << std :: setw ( 4 ) << doc << std :: endl ; // apply the patch doc . patch_inplace ( patch ); // output patched document std :: cout << \" \\n After \\n \" << std :: setw ( 4 ) << doc << std :: endl ; } Output: Be f ore { \"baz\" : \"qux\" , \"foo\" : \"bar\" } A fter { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Examples"},{"location":"api/basic_json/patch_inplace/#see-also","text":"RFC 6902 (JSON Patch) RFC 6901 (JSON Pointer) patch applies a JSON Merge Patch merge_patch applies a JSON Merge Patch","title":"See also"},{"location":"api/basic_json/patch_inplace/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/push_back/","text":"nlohmann::basic_json:: push_back \u00b6 // (1) void push_back ( basic_json && val ); void push_back ( const basic_json & val ); // (2) void push_back ( const typename object_t :: value_type & val ); // (3) void push_back ( initializer_list_t init ); 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&&) . Parameters \u00b6 val (in) the value to add to the JSON array/object init (in) an initializer list Exceptions \u00b6 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\" Complexity \u00b6 Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init . Notes \u00b6 (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 , see #235 for more information. Examples \u00b6 Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]] Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"push_back"},{"location":"api/basic_json/push_back/#nlohmannbasic_jsonpush_back","text":"// (1) void push_back ( basic_json && val ); void push_back ( const basic_json & val ); // (2) void push_back ( const typename object_t :: value_type & val ); // (3) void push_back ( initializer_list_t init ); 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&&) .","title":"nlohmann::basic_json::push_back"},{"location":"api/basic_json/push_back/#parameters","text":"val (in) the value to add to the JSON array/object init (in) an initializer list","title":"Parameters"},{"location":"api/basic_json/push_back/#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\"","title":"Exceptions"},{"location":"api/basic_json/push_back/#complexity","text":"Amortized constant. Logarithmic in the size of the container, O(log( size() )). Linear in the size of the initializer list init .","title":"Complexity"},{"location":"api/basic_json/push_back/#notes","text":"(3) This function is required to resolve an ambiguous overload error, because pairs like {\"key\", \"value\"} can be both interpreted as object_t::value_type or std::initializer_list , see #235 for more information.","title":"Notes"},{"location":"api/basic_json/push_back/#examples","text":"Example: (1) add element to array The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array. #include #include using json = nlohmann :: json ; int main () { // create JSON values json array = { 1 , 2 , 3 , 4 , 5 }; json null ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; // add values array . push_back ( 6 ); array += 7 ; null += \"first\" ; null += \"second\" ; // print values std :: cout << array << '\\n' ; std :: cout << null << '\\n' ; } Output: [ 1 , 2 , 3 , 4 , 5 ] null [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ \"first\" , \"second\" ] Example: (2) add element to object The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values object . push_back ( json :: object_t :: value_type ( \"three\" , 3 )); object += json :: object_t :: value_type ( \"four\" , 4 ); null += json :: object_t :: value_type ( \"A\" , \"a\" ); null += json :: object_t :: value_type ( \"B\" , \"b\" ); // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } { \"A\" : \"a\" , \"B\" : \"b\" } Example: (3) add to object from initializer list The example shows how initializer lists are treated as objects when possible. #include #include using json = nlohmann :: json ; int main () { // create JSON values json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json null ; // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // add values: object . push_back ({ \"three\" , 3 }); // object is extended object += { \"four\" , 4 }; // object is extended null . push_back ({ \"five\" , 5 }); // null is converted to array // print values std :: cout << object << '\\n' ; std :: cout << null << '\\n' ; // would throw: //object.push_back({1, 2, 3}); } Output: { \"one\" : 1 , \"two\" : 2 } null { \"four\" : 4 , \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } [[ \"five\" , 5 ]]","title":"Examples"},{"location":"api/basic_json/push_back/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 2.0.0.","title":"Version history"},{"location":"api/basic_json/rbegin/","text":"nlohmann::basic_json:: rbegin \u00b6 reverse_iterator rbegin () noexcept ; const_reverse_iterator rbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element. Return value \u00b6 reverse iterator to the first element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for rbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: reverse_iterator it = array . rbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5 Version history \u00b6 Added in version 1.0.0.","title":"rbegin"},{"location":"api/basic_json/rbegin/#nlohmannbasic_jsonrbegin","text":"reverse_iterator rbegin () noexcept ; const_reverse_iterator rbegin () const noexcept ; Returns an iterator to the reverse-beginning; that is, the last element.","title":"nlohmann::basic_json::rbegin"},{"location":"api/basic_json/rbegin/#return-value","text":"reverse iterator to the first element","title":"Return value"},{"location":"api/basic_json/rbegin/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/rbegin/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/rbegin/#examples","text":"Example The following code shows an example for rbegin() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-beginning json :: reverse_iterator it = array . rbegin (); // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 5","title":"Examples"},{"location":"api/basic_json/rbegin/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/rend/","text":"nlohmann::basic_json:: rend \u00b6 reverse_iterator rend () noexcept ; const_reverse_iterator rend () const noexcept ; 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. Return value \u00b6 reverse iterator to the element following the last element Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: reverse_iterator it = array . rend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1 Version history \u00b6 Added in version 1.0.0.","title":"rend"},{"location":"api/basic_json/rend/#nlohmannbasic_jsonrend","text":"reverse_iterator rend () noexcept ; const_reverse_iterator rend () const noexcept ; 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.","title":"nlohmann::basic_json::rend"},{"location":"api/basic_json/rend/#return-value","text":"reverse iterator to the element following the last element","title":"Return value"},{"location":"api/basic_json/rend/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/rend/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/rend/#examples","text":"Example The following code shows an example for eend() . #include #include using json = nlohmann :: json ; int main () { // create an array value json array = { 1 , 2 , 3 , 4 , 5 }; // get an iterator to the reverse-end json :: reverse_iterator it = array . rend (); // increment the iterator to point to the first element -- it ; // serialize the element that the iterator points to std :: cout << * it << '\\n' ; } Output: 1","title":"Examples"},{"location":"api/basic_json/rend/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/sax_parse/","text":"nlohmann::basic_json:: sax_parse \u00b6 // (1) template < typename InputType , typename SAX > static bool sax_parse ( InputType && i , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); // (2) template < class IteratorType , class SAX > static bool sax_parse ( IteratorType first , IteratorType last , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); Read from input and generate SAX events Read from a compatible input. Read from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. The SAX event lister must follow the interface of json_sax . Template parameters \u00b6 InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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 Parameters \u00b6 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 Return value \u00b6 return value of the last processed SAX event Exception safety \u00b6 Complexity \u00b6 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. Notes \u00b6 A UTF-8 byte order mark is silently ignored. Examples \u00b6 Example The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0. 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 ); .","title":"sax_parse"},{"location":"api/basic_json/sax_parse/#nlohmannbasic_jsonsax_parse","text":"// (1) template < typename InputType , typename SAX > static bool sax_parse ( InputType && i , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); // (2) template < class IteratorType , class SAX > static bool sax_parse ( IteratorType first , IteratorType last , SAX * sax , input_format_t format = input_format_t :: json , const bool strict = true , const bool ignore_comments = false ); Read from input and generate SAX events Read from a compatible input. Read from a pair of character iterators The value_type of the iterator must be an integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. The SAX event lister must follow the interface of json_sax .","title":"nlohmann::basic_json::sax_parse"},{"location":"api/basic_json/sax_parse/#template-parameters","text":"InputType A compatible input, for instance: an std::istream object a FILE pointer a C-style array of characters 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","title":"Template parameters"},{"location":"api/basic_json/sax_parse/#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","title":"Parameters"},{"location":"api/basic_json/sax_parse/#return-value","text":"return value of the last processed SAX event","title":"Return value"},{"location":"api/basic_json/sax_parse/#exception-safety","text":"","title":"Exception safety"},{"location":"api/basic_json/sax_parse/#complexity","text":"Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer sax has a super-linear complexity.","title":"Complexity"},{"location":"api/basic_json/sax_parse/#notes","text":"A UTF-8 byte order mark is silently ignored.","title":"Notes"},{"location":"api/basic_json/sax_parse/#examples","text":"Example The example below demonstrates the sax_parse() function reading from string and processing the events with a user-defined SAX event consumer. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/basic_json/sax_parse/#version-history","text":"Added in version 3.2.0. 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 ); .","title":"Version history"},{"location":"api/basic_json/size/","text":"nlohmann::basic_json:: size \u00b6 size_type size () const noexcept ; Returns the number of elements in a JSON value. Return value \u00b6 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() Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity. Notes \u00b6 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. Examples \u00b6 Example The following code calls size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call size() std :: cout << j_null . size () << '\\n' ; std :: cout << j_boolean . size () << '\\n' ; std :: cout << j_number_integer . size () << '\\n' ; std :: cout << j_number_float . size () << '\\n' ; std :: cout << j_object . size () << '\\n' ; std :: cout << j_object_empty . size () << '\\n' ; std :: cout << j_array . size () << '\\n' ; std :: cout << j_array_empty . size () << '\\n' ; std :: cout << j_string . size () << '\\n' ; } Output: 0 1 1 1 2 0 5 0 1 Version history \u00b6 Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"size"},{"location":"api/basic_json/size/#nlohmannbasic_jsonsize","text":"size_type size () const noexcept ; Returns the number of elements in a JSON value.","title":"nlohmann::basic_json::size"},{"location":"api/basic_json/size/#return-value","text":"The return value depends on the different types and is defined as follows: Value type return value null 0 boolean 1 string 1 number 1 binary 1 object result of function object_t::size() array result of function array_t::size()","title":"Return value"},{"location":"api/basic_json/size/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/size/#complexity","text":"Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.","title":"Complexity"},{"location":"api/basic_json/size/#notes","text":"This function does not return the length of a string stored as JSON value -- it returns the number of elements in the JSON value which is 1 in the case of a string.","title":"Notes"},{"location":"api/basic_json/size/#examples","text":"Example The following code calls size() on the different value types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = 17 ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_object_empty ( json :: value_t :: object ); json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_array_empty ( json :: value_t :: array ); json j_string = \"Hello, world\" ; // call size() std :: cout << j_null . size () << '\\n' ; std :: cout << j_boolean . size () << '\\n' ; std :: cout << j_number_integer . size () << '\\n' ; std :: cout << j_number_float . size () << '\\n' ; std :: cout << j_object . size () << '\\n' ; std :: cout << j_object_empty . size () << '\\n' ; std :: cout << j_array . size () << '\\n' ; std :: cout << j_array_empty . size () << '\\n' ; std :: cout << j_string . size () << '\\n' ; } Output: 0 1 1 1 2 0 5 0 1","title":"Examples"},{"location":"api/basic_json/size/#version-history","text":"Added in version 1.0.0. Extended to return 1 for binary types in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/std_hash/","text":"std:: hash \u00b6 namespace std { struct hash < nlohmann :: basic_json > ; } 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. Examples \u00b6 Example The example shows how to calculate hash values for different JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { std :: cout << \"hash(null) = \" << std :: hash < json > {}( json ( nullptr )) << '\\n' << \"hash(false) = \" << std :: hash < json > {}( json ( false )) << '\\n' << \"hash(0) = \" << std :: hash < json > {}( json ( 0 )) << '\\n' << \"hash(0U) = \" << std :: hash < json > {}( json ( 0U )) << '\\n' << \"hash( \\\"\\\" ) = \" << std :: hash < json > {}( json ( \"\" )) << '\\n' << \"hash({}) = \" << std :: hash < json > {}( json :: object ()) << '\\n' << \"hash([]) = \" << std :: hash < json > {}( json :: array ()) << '\\n' << \"hash({ \\\" hello \\\" : \\\" world \\\" }) = \" << std :: hash < json > {}( \"{ \\\" hello \\\" : \\\" world \\\" }\" _json ) << std :: endl ; } Output: hash( null ) = 2654435769 hash( false ) = 2654436030 hash( 0 ) = 2654436095 hash( 0 U) = 2654436156 hash( \"\" ) = 6142509191626859748 hash( {} ) = 2654435832 hash( [] ) = 2654435899 hash( { \"hello\" : \"world\" } ) = 4469488738203676328 Note the output is platform-dependent. Version history \u00b6 Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"std::hash<basic_json>"},{"location":"api/basic_json/std_hash/#stdhashnlohmannbasic_json","text":"namespace std { struct hash < nlohmann :: basic_json > ; } 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.","title":"std::hash<nlohmann::basic_json>"},{"location":"api/basic_json/std_hash/#examples","text":"Example The example shows how to calculate hash values for different JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { std :: cout << \"hash(null) = \" << std :: hash < json > {}( json ( nullptr )) << '\\n' << \"hash(false) = \" << std :: hash < json > {}( json ( false )) << '\\n' << \"hash(0) = \" << std :: hash < json > {}( json ( 0 )) << '\\n' << \"hash(0U) = \" << std :: hash < json > {}( json ( 0U )) << '\\n' << \"hash( \\\"\\\" ) = \" << std :: hash < json > {}( json ( \"\" )) << '\\n' << \"hash({}) = \" << std :: hash < json > {}( json :: object ()) << '\\n' << \"hash([]) = \" << std :: hash < json > {}( json :: array ()) << '\\n' << \"hash({ \\\" hello \\\" : \\\" world \\\" }) = \" << std :: hash < json > {}( \"{ \\\" hello \\\" : \\\" world \\\" }\" _json ) << std :: endl ; } Output: hash( null ) = 2654435769 hash( false ) = 2654436030 hash( 0 ) = 2654436095 hash( 0 U) = 2654436156 hash( \"\" ) = 6142509191626859748 hash( {} ) = 2654435832 hash( [] ) = 2654435899 hash( { \"hello\" : \"world\" } ) = 4469488738203676328 Note the output is platform-dependent.","title":"Examples"},{"location":"api/basic_json/std_hash/#version-history","text":"Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"Version history"},{"location":"api/basic_json/std_swap/","text":"std::swap \u00b6 namespace std { void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ); } Exchanges the values of two JSON objects. Parameters \u00b6 j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1 Possible implementation \u00b6 void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ) { j1 . swap ( j2 ); } Examples \u00b6 Example The following code shows how two values are swapped with std::swap . #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j1 = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j2 = { 1 , 2 , 4 , 8 , 16 }; std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n' ; // swap values std :: swap ( j1 , j2 ); std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std :: endl ; } Output: j 1 = { \"one\" : 1 , \"two\" : 2 } | j 2 = [ 1 , 2 , 4 , 8 , 16 ] j 1 = [ 1 , 2 , 4 , 8 , 16 ] | j 2 = { \"one\" : 1 , \"two\" : 2 } See also \u00b6 swap Version history \u00b6 Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"std::swap<basic_json>"},{"location":"api/basic_json/std_swap/#stdswapbasic_json","text":"namespace std { void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ); } Exchanges the values of two JSON objects.","title":"std::swap<basic_json>"},{"location":"api/basic_json/std_swap/#parameters","text":"j1 (in, out) value to be replaced by j2 j2 (in, out) value to be replaced by j1","title":"Parameters"},{"location":"api/basic_json/std_swap/#possible-implementation","text":"void swap ( nlohmann :: basic_json & j1 , nlohmann :: basic_json & j2 ) { j1 . swap ( j2 ); }","title":"Possible implementation"},{"location":"api/basic_json/std_swap/#examples","text":"Example The following code shows how two values are swapped with std::swap . #include #include #include using json = nlohmann :: json ; int main () { // create JSON values json j1 = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j2 = { 1 , 2 , 4 , 8 , 16 }; std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << '\\n' ; // swap values std :: swap ( j1 , j2 ); std :: cout << \"j1 = \" << j1 << \" | j2 = \" << j2 << std :: endl ; } Output: j 1 = { \"one\" : 1 , \"two\" : 2 } | j 2 = [ 1 , 2 , 4 , 8 , 16 ] j 1 = [ 1 , 2 , 4 , 8 , 16 ] | j 2 = { \"one\" : 1 , \"two\" : 2 }","title":"Examples"},{"location":"api/basic_json/std_swap/#see-also","text":"swap","title":"See also"},{"location":"api/basic_json/std_swap/#version-history","text":"Added in version 1.0.0. Extended for arbitrary basic_json types in version 3.10.5.","title":"Version history"},{"location":"api/basic_json/string_t/","text":"nlohmann::basic_json:: string_t \u00b6 using string_t = StringType ; The type used to store JSON strings. RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. Template parameters \u00b6 StringType the container to store strings (e.g., std::string ). Note this container is used for keys/names in objects, see object_t . Notes \u00b6 Default type \u00b6 With the default values for StringType ( std::string ), the default value for string_t is std :: string . Encoding \u00b6 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. String comparison \u00b6 RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit. Storage \u00b6 String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced. Examples \u00b6 Example The following code shows that string_t is by default, a typedef to std :: string . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: string , json :: string_t >:: value << std :: endl ; } Output: true Version history \u00b6 Added in version 1.0.0.","title":"string_t"},{"location":"api/basic_json/string_t/#nlohmannbasic_jsonstring_t","text":"using string_t = StringType ; The type used to store JSON strings. RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.","title":"nlohmann::basic_json::string_t"},{"location":"api/basic_json/string_t/#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 .","title":"Template parameters"},{"location":"api/basic_json/string_t/#notes","text":"","title":"Notes"},{"location":"api/basic_json/string_t/#default-type","text":"With the default values for StringType ( std::string ), the default value for string_t is std :: string .","title":"Default type"},{"location":"api/basic_json/string_t/#encoding","text":"Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.","title":"Encoding"},{"location":"api/basic_json/string_t/#string-comparison","text":"RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit.","title":"String comparison"},{"location":"api/basic_json/string_t/#storage","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.","title":"Storage"},{"location":"api/basic_json/string_t/#examples","text":"Example The following code shows that string_t is by default, a typedef to std :: string . #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: boolalpha << std :: is_same < std :: string , json :: string_t >:: value << std :: endl ; } Output: true","title":"Examples"},{"location":"api/basic_json/string_t/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/basic_json/swap/","text":"nlohmann::basic_json:: swap \u00b6 // (1) void swap ( reference other ) noexcept ; // (2) void swap ( reference left , reference right ) noexcept ; // (3) void swap ( array_t & other ); // (4) void swap ( object_t & other ); // (5) void swap ( string_t & other ); // (6) void swap ( binary_t & other ); // (7) void swap ( typename binary_t :: container_type & other ); 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. Parameters \u00b6 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 Exceptions \u00b6 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\" Complexity \u00b6 Constant. Examples \u00b6 Example: Swap JSON value (1, 2) The example below shows how JSON values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create two JSON values json j1 = { 1 , 2 , 3 , 4 , 5 }; json j2 = {{ \"pi\" , 3.141592653589793 }, { \"e\" , 2.718281828459045 }}; // swap the values j1 . swap ( j2 ); // output the values std :: cout << \"j1 = \" << j1 << '\\n' ; std :: cout << \"j2 = \" << j2 << '\\n' ; } Output: j 1 = { \"e\" : 2.718281828459045 , \"pi\" : 3.141592653589793 } j 2 = [ 1 , 2 , 3 , 4 , 5 ] Example: Swap array (3) The example below shows how arrays can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = {{ \"array\" , { 1 , 2 , 3 , 4 }}}; // create an array_t json :: array_t array = { \"Snap\" , \"Crackle\" , \"Pop\" }; // swap the array stored in the JSON value value [ \"array\" ]. swap ( array ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"array = \" << array << '\\n' ; } Output: value = { \"array\" :[ \"Snap\" , \"Crackle\" , \"Pop\" ]} array = [ 1 , 2 , 3 , 4 ] Example: Swap object (4) The example below shows how objects can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { { \"translation\" , {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}} }; // create an object_t json :: object_t object = {{ \"cow\" , \"Kuh\" }, { \"dog\" , \"Hund\" }}; // swap the object stored in the JSON value value [ \"translation\" ]. swap ( object ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"object = \" << object << '\\n' ; } Output: value = { \"translation\" :{ \"cow\" : \"Kuh\" , \"dog\" : \"Hund\" }} objec t = { \"one\" : \"eins\" , \"two\" : \"zwei\" } Example: Swap string (5) The example below shows how strings can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { \"the good\" , \"the bad\" , \"the ugly\" }; // create string_t json :: string_t string = \"the fast\" ; // swap the object stored in the JSON value value [ 1 ]. swap ( string ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"string = \" << string << '\\n' ; } Output: value = [ \"the good\" , \"the fast\" , \"the ugly\" ] s tr i n g = t he bad Example: Swap string (6) The example below shows how binary values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a binary value json value = json :: binary ({ 1 , 2 , 3 }); // create a binary_t json :: binary_t binary = {{ 4 , 5 , 6 }}; // swap the object stored in the JSON value value . swap ( binary ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"binary = \" << json ( binary ) << '\\n' ; } Output: value = { \"bytes\" :[ 4 , 5 , 6 ], \"subtype\" : null } bi nar y = { \"bytes\" :[ 1 , 2 , 3 ], \"subtype\" : null } See also \u00b6 std::swap Version history \u00b6 Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 3.8.0. Since version 3.8.0.","title":"swap"},{"location":"api/basic_json/swap/#nlohmannbasic_jsonswap","text":"// (1) void swap ( reference other ) noexcept ; // (2) void swap ( reference left , reference right ) noexcept ; // (3) void swap ( array_t & other ); // (4) void swap ( object_t & other ); // (5) void swap ( string_t & other ); // (6) void swap ( binary_t & other ); // (7) void swap ( typename binary_t :: container_type & other ); 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.","title":"nlohmann::basic_json::swap"},{"location":"api/basic_json/swap/#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","title":"Parameters"},{"location":"api/basic_json/swap/#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\"","title":"Exceptions"},{"location":"api/basic_json/swap/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/swap/#examples","text":"Example: Swap JSON value (1, 2) The example below shows how JSON values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create two JSON values json j1 = { 1 , 2 , 3 , 4 , 5 }; json j2 = {{ \"pi\" , 3.141592653589793 }, { \"e\" , 2.718281828459045 }}; // swap the values j1 . swap ( j2 ); // output the values std :: cout << \"j1 = \" << j1 << '\\n' ; std :: cout << \"j2 = \" << j2 << '\\n' ; } Output: j 1 = { \"e\" : 2.718281828459045 , \"pi\" : 3.141592653589793 } j 2 = [ 1 , 2 , 3 , 4 , 5 ] Example: Swap array (3) The example below shows how arrays can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = {{ \"array\" , { 1 , 2 , 3 , 4 }}}; // create an array_t json :: array_t array = { \"Snap\" , \"Crackle\" , \"Pop\" }; // swap the array stored in the JSON value value [ \"array\" ]. swap ( array ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"array = \" << array << '\\n' ; } Output: value = { \"array\" :[ \"Snap\" , \"Crackle\" , \"Pop\" ]} array = [ 1 , 2 , 3 , 4 ] Example: Swap object (4) The example below shows how objects can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { { \"translation\" , {{ \"one\" , \"eins\" }, { \"two\" , \"zwei\" }}} }; // create an object_t json :: object_t object = {{ \"cow\" , \"Kuh\" }, { \"dog\" , \"Hund\" }}; // swap the object stored in the JSON value value [ \"translation\" ]. swap ( object ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"object = \" << object << '\\n' ; } Output: value = { \"translation\" :{ \"cow\" : \"Kuh\" , \"dog\" : \"Hund\" }} objec t = { \"one\" : \"eins\" , \"two\" : \"zwei\" } Example: Swap string (5) The example below shows how strings can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a JSON value json value = { \"the good\" , \"the bad\" , \"the ugly\" }; // create string_t json :: string_t string = \"the fast\" ; // swap the object stored in the JSON value value [ 1 ]. swap ( string ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"string = \" << string << '\\n' ; } Output: value = [ \"the good\" , \"the fast\" , \"the ugly\" ] s tr i n g = t he bad Example: Swap string (6) The example below shows how binary values can be swapped with swap() . #include #include using json = nlohmann :: json ; int main () { // create a binary value json value = json :: binary ({ 1 , 2 , 3 }); // create a binary_t json :: binary_t binary = {{ 4 , 5 , 6 }}; // swap the object stored in the JSON value value . swap ( binary ); // output the values std :: cout << \"value = \" << value << '\\n' ; std :: cout << \"binary = \" << json ( binary ) << '\\n' ; } Output: value = { \"bytes\" :[ 4 , 5 , 6 ], \"subtype\" : null } bi nar y = { \"bytes\" :[ 1 , 2 , 3 ], \"subtype\" : null }","title":"Examples"},{"location":"api/basic_json/swap/#see-also","text":"std::swap","title":"See also"},{"location":"api/basic_json/swap/#version-history","text":"Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 1.0.0. Since version 3.8.0. Since version 3.8.0.","title":"Version history"},{"location":"api/basic_json/to_bjdata/","text":"nlohmann::basic_json:: to_bjdata \u00b6 // (1) static std :: vector < std :: uint8_t > to_bjdata ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_bjdata ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_bjdata ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 . Parameters \u00b6 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. Return value \u00b6 BJData serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in BJData format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678 Version history \u00b6 Added in version 3.11.0.","title":"to_bjdata"},{"location":"api/basic_json/to_bjdata/#nlohmannbasic_jsonto_bjdata","text":"// (1) static std :: vector < std :: uint8_t > to_bjdata ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_bjdata ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_bjdata ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 .","title":"nlohmann::basic_json::to_bjdata"},{"location":"api/basic_json/to_bjdata/#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.","title":"Parameters"},{"location":"api/basic_json/to_bjdata/#return-value","text":"BJData serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_bjdata/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_bjdata/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_bjdata/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in BJData format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678","title":"Examples"},{"location":"api/basic_json/to_bjdata/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/basic_json/to_bson/","text":"nlohmann::basic_json:: to_bson \u00b6 // (1) static std :: vector < std :: uint8_t > to_bson ( const basic_json & j ); // (2) static void to_bson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_bson ( const basic_json & j , detail :: output_adapter < char > o ); 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 . Parameters \u00b6 j (in) JSON value to serialize o (in) output adapter to write serialization to Return value \u00b6 BSON serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in BSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 1 b 0 x 00 0 x 00 0 x 00 0 x 08 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x 00 0 x 01 0 x 10 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00 Version history \u00b6 Added in version 3.4.0.","title":"to_bson"},{"location":"api/basic_json/to_bson/#nlohmannbasic_jsonto_bson","text":"// (1) static std :: vector < std :: uint8_t > to_bson ( const basic_json & j ); // (2) static void to_bson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_bson ( const basic_json & j , detail :: output_adapter < char > o ); 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 .","title":"nlohmann::basic_json::to_bson"},{"location":"api/basic_json/to_bson/#parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to","title":"Parameters"},{"location":"api/basic_json/to_bson/#return-value","text":"BSON serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_bson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_bson/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_bson/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in BSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 1 b 0 x 00 0 x 00 0 x 00 0 x 08 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x 00 0 x 01 0 x 10 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00 0 x 00","title":"Examples"},{"location":"api/basic_json/to_bson/#version-history","text":"Added in version 3.4.0.","title":"Version history"},{"location":"api/basic_json/to_cbor/","text":"nlohmann::basic_json:: to_cbor \u00b6 // (1) static std :: vector < std :: uint8_t > to_cbor ( const basic_json & j ); // (2) static void to_cbor ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_cbor ( const basic_json & j , detail :: output_adapter < char > o ); 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 . Parameters \u00b6 j (in) JSON value to serialize o (in) output adapter to write serialization to Return value \u00b6 CBOR serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in CBOR format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 xa 2 0 x 67 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x f 5 0 x 66 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 Version history \u00b6 Added in version 2.0.9. Compact representation of floating-point numbers added in version 3.8.0.","title":"to_cbor"},{"location":"api/basic_json/to_cbor/#nlohmannbasic_jsonto_cbor","text":"// (1) static std :: vector < std :: uint8_t > to_cbor ( const basic_json & j ); // (2) static void to_cbor ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_cbor ( const basic_json & j , detail :: output_adapter < char > o ); 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 .","title":"nlohmann::basic_json::to_cbor"},{"location":"api/basic_json/to_cbor/#parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to","title":"Parameters"},{"location":"api/basic_json/to_cbor/#return-value","text":"CBOR serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_cbor/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_cbor/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_cbor/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in CBOR format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 xa 2 0 x 67 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 x f 5 0 x 66 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00","title":"Examples"},{"location":"api/basic_json/to_cbor/#version-history","text":"Added in version 2.0.9. Compact representation of floating-point numbers added in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/to_msgpack/","text":"nlohmann::basic_json:: to_msgpack \u00b6 // (1) static std :: vector < std :: uint8_t > to_msgpack ( const basic_json & j ); // (2) static void to_msgpack ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_msgpack ( const basic_json & j , detail :: output_adapter < char > o ); 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 . Parameters \u00b6 j (in) JSON value to serialize o (in) output adapter to write serialization to Return value \u00b6 MessagePack serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in MessagePack format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 82 0 xa 7 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 xc 3 0 xa 6 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00 Version history \u00b6 Added in version 2.0.9.","title":"to_msgpack"},{"location":"api/basic_json/to_msgpack/#nlohmannbasic_jsonto_msgpack","text":"// (1) static std :: vector < std :: uint8_t > to_msgpack ( const basic_json & j ); // (2) static void to_msgpack ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o ); static void to_msgpack ( const basic_json & j , detail :: output_adapter < char > o ); 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 .","title":"nlohmann::basic_json::to_msgpack"},{"location":"api/basic_json/to_msgpack/#parameters","text":"j (in) JSON value to serialize o (in) output adapter to write serialization to","title":"Parameters"},{"location":"api/basic_json/to_msgpack/#return-value","text":"MessagePack serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_msgpack/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_msgpack/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_msgpack/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in MessagePack format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0 x 82 0 xa 7 0 x 63 0 x 6 f 0 x 6 d 0 x 70 0 x 61 0 x 63 0 x 74 0 xc 3 0 xa 6 0 x 73 0 x 63 0 x 68 0 x 65 0 x 6 d 0 x 61 0 x 00","title":"Examples"},{"location":"api/basic_json/to_msgpack/#version-history","text":"Added in version 2.0.9.","title":"Version history"},{"location":"api/basic_json/to_string/","text":"to_string(basic_json) \u00b6 template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ); This function implements a user-defined to_string for JSON objects. Template parameters \u00b6 BasicJsonType a specialization of basic_json Return value \u00b6 string containing the serialization of the JSON value Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Exceptions \u00b6 Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded Complexity \u00b6 Linear. Possible implementation \u00b6 template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ) { return j . dump (); } Examples \u00b6 Example The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup. #include #include using json = nlohmann :: json ; using std :: to_string ; int main () { // create values json j = {{ \"one\" , 1 }, { \"two\" , 2 }}; int i = 42 ; // use ADL to select best to_string function auto j_str = to_string ( j ); // calling nlohmann::to_string auto i_str = to_string ( i ); // calling std::to_string // serialize without indentation std :: cout << j_str << \" \\n\\n \" << i_str << std :: endl ; } Output: { \"one\" : 1 , \"two\" : 2 } 42 See also \u00b6 dump Version history \u00b6 Added in version 3.7.0.","title":"to_string"},{"location":"api/basic_json/to_string/#to_stringbasic_json","text":"template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ); This function implements a user-defined to_string for JSON objects.","title":"to_string(basic_json)"},{"location":"api/basic_json/to_string/#template-parameters","text":"BasicJsonType a specialization of basic_json","title":"Template parameters"},{"location":"api/basic_json/to_string/#return-value","text":"string containing the serialization of the JSON value","title":"Return value"},{"location":"api/basic_json/to_string/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_string/#exceptions","text":"Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded","title":"Exceptions"},{"location":"api/basic_json/to_string/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/to_string/#possible-implementation","text":"template < typename BasicJsonType > std :: string to_string ( const BasicJsonType & j ) { return j . dump (); }","title":"Possible implementation"},{"location":"api/basic_json/to_string/#examples","text":"Example The following code shows how the library's to_string() function integrates with others, allowing argument-dependent lookup. #include #include using json = nlohmann :: json ; using std :: to_string ; int main () { // create values json j = {{ \"one\" , 1 }, { \"two\" , 2 }}; int i = 42 ; // use ADL to select best to_string function auto j_str = to_string ( j ); // calling nlohmann::to_string auto i_str = to_string ( i ); // calling std::to_string // serialize without indentation std :: cout << j_str << \" \\n\\n \" << i_str << std :: endl ; } Output: { \"one\" : 1 , \"two\" : 2 } 42","title":"Examples"},{"location":"api/basic_json/to_string/#see-also","text":"dump","title":"See also"},{"location":"api/basic_json/to_string/#version-history","text":"Added in version 3.7.0.","title":"Version history"},{"location":"api/basic_json/to_ubjson/","text":"nlohmann::basic_json:: to_ubjson \u00b6 // (1) static std :: vector < std :: uint8_t > to_ubjson ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_ubjson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_ubjson ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 . Parameters \u00b6 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. Return value \u00b6 UBJSON serialization as byte vector (none) Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes in the JSON value. Complexity \u00b6 Linear in the size of the JSON value j . Examples \u00b6 Example The example shows the serialization of a JSON value to a byte vector in UBJSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678 Version history \u00b6 Added in version 3.1.0.","title":"to_ubjson"},{"location":"api/basic_json/to_ubjson/#nlohmannbasic_jsonto_ubjson","text":"// (1) static std :: vector < std :: uint8_t > to_ubjson ( const basic_json & j , const bool use_size = false , const bool use_type = false ); // (2) static void to_ubjson ( const basic_json & j , detail :: output_adapter < std :: uint8_t > o , const bool use_size = false , const bool use_type = false ); static void to_ubjson ( const basic_json & j , detail :: output_adapter < char > o , const bool use_size = false , const bool use_type = false ); 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 .","title":"nlohmann::basic_json::to_ubjson"},{"location":"api/basic_json/to_ubjson/#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.","title":"Parameters"},{"location":"api/basic_json/to_ubjson/#return-value","text":"UBJSON serialization as byte vector (none)","title":"Return value"},{"location":"api/basic_json/to_ubjson/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes in the JSON value.","title":"Exception safety"},{"location":"api/basic_json/to_ubjson/#complexity","text":"Linear in the size of the JSON value j .","title":"Complexity"},{"location":"api/basic_json/to_ubjson/#examples","text":"Example The example shows the serialization of a JSON value to a byte vector in UBJSON format. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i 7 compac t Ti 6 schemaF } [ i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 ] [ #i 8 i 1 i 2 i 3 i 4 i 5 i 6 i 7 i 8 [ $i#i 812345678","title":"Examples"},{"location":"api/basic_json/to_ubjson/#version-history","text":"Added in version 3.1.0.","title":"Version history"},{"location":"api/basic_json/type/","text":"nlohmann::basic_json:: type \u00b6 constexpr value_t type () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration. Return value \u00b6 the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies type() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true Version history \u00b6 Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"type"},{"location":"api/basic_json/type/#nlohmannbasic_jsontype","text":"constexpr value_t type () const noexcept ; Return the type of the JSON value as a value from the value_t enumeration.","title":"nlohmann::basic_json::type"},{"location":"api/basic_json/type/#return-value","text":"the type of the JSON value Value type return value null value_t::null boolean value_t::boolean string value_t::string number (integer) value_t::number_integer number (unsigned integer) value_t::number_unsigned number (floating-point) value_t::number_float object value_t::object array value_t::array binary value_t::binary discarded value_t::discarded","title":"Return value"},{"location":"api/basic_json/type/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/type/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/type/#examples","text":"Example The following code exemplifies type() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true","title":"Examples"},{"location":"api/basic_json/type/#version-history","text":"Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/type_error/","text":"nlohmann::basic_json:: type_error \u00b6 class type_error : public exception ; 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 ). Member functions \u00b6 what - returns explanatory string Member variables \u00b6 id - the id of the exception Examples \u00b6 Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n . t ype_error. 308 ] ca nn o t use push_back() wi t h s tr i n g excep t io n id : 308 See also \u00b6 List of type errors parse_error for exceptions indicating a parse error invalid_iterator for exceptions indicating errors with iterators out_of_range for exceptions indicating access out of the defined range other_error for exceptions indicating other library errors Version history \u00b6 Since version 3.0.0.","title":"type_error"},{"location":"api/basic_json/type_error/#nlohmannbasic_jsontype_error","text":"class type_error : public exception ; 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 ).","title":"nlohmann::basic_json::type_error"},{"location":"api/basic_json/type_error/#member-functions","text":"what - returns explanatory string","title":"Member functions"},{"location":"api/basic_json/type_error/#member-variables","text":"id - the id of the exception","title":"Member variables"},{"location":"api/basic_json/type_error/#examples","text":"Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message : [ jso n .excep t io n . t ype_error. 308 ] ca nn o t use push_back() wi t h s tr i n g excep t io n id : 308","title":"Examples"},{"location":"api/basic_json/type_error/#see-also","text":"List of type errors parse_error for exceptions indicating a parse error invalid_iterator for exceptions indicating errors with iterators out_of_range for exceptions indicating access out of the defined range other_error for exceptions indicating other library errors","title":"See also"},{"location":"api/basic_json/type_error/#version-history","text":"Since version 3.0.0.","title":"Version history"},{"location":"api/basic_json/type_name/","text":"nlohmann::basic_json:: type_name \u00b6 const char * type_name () const noexcept ; Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type. Return value \u00b6 a string representation of the type ( value_t ): Value type return value null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\" Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The following code exemplifies type_name() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type_name() std :: cout << j_null << \" is a \" << j_null . type_name () << '\\n' ; std :: cout << j_boolean << \" is a \" << j_boolean . type_name () << '\\n' ; std :: cout << j_number_integer << \" is a \" << j_number_integer . type_name () << '\\n' ; std :: cout << j_number_unsigned << \" is a \" << j_number_unsigned . type_name () << '\\n' ; std :: cout << j_number_float << \" is a \" << j_number_float . type_name () << '\\n' ; std :: cout << j_object << \" is an \" << j_object . type_name () << '\\n' ; std :: cout << j_array << \" is an \" << j_array . type_name () << '\\n' ; std :: cout << j_string << \" is a \" << j_string . type_name () << '\\n' ; } Output: null is a null true is a boolea n -17 is a nu mber 42 is a nu mber 23.42 is a nu mber { \"one\" : 1 , \"two\" : 2 } is a n objec t [ 1 , 2 , 4 , 8 , 16 ] is a n array \"Hello, world\" is a s tr i n g Version history \u00b6 Added in version 1.0.0. Part of the public API version since 2.1.0. Changed return value to const char* and added noexcept in version 3.0.0. Added support for binary type in version 3.8.0.","title":"type_name"},{"location":"api/basic_json/type_name/#nlohmannbasic_jsontype_name","text":"const char * type_name () const noexcept ; Returns the type name as string to be used in error messages -- usually to indicate that a function was called on a wrong JSON type.","title":"nlohmann::basic_json::type_name"},{"location":"api/basic_json/type_name/#return-value","text":"a string representation of the type ( value_t ): Value type return value null \"null\" boolean \"boolean\" string \"string\" number (integer, unsigned integer, floating-point) \"number\" object \"object\" array \"array\" binary \"binary\" discarded \"discarded\"","title":"Return value"},{"location":"api/basic_json/type_name/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/type_name/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/basic_json/type_name/#examples","text":"Example The following code exemplifies type_name() for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type_name() std :: cout << j_null << \" is a \" << j_null . type_name () << '\\n' ; std :: cout << j_boolean << \" is a \" << j_boolean . type_name () << '\\n' ; std :: cout << j_number_integer << \" is a \" << j_number_integer . type_name () << '\\n' ; std :: cout << j_number_unsigned << \" is a \" << j_number_unsigned . type_name () << '\\n' ; std :: cout << j_number_float << \" is a \" << j_number_float . type_name () << '\\n' ; std :: cout << j_object << \" is an \" << j_object . type_name () << '\\n' ; std :: cout << j_array << \" is an \" << j_array . type_name () << '\\n' ; std :: cout << j_string << \" is a \" << j_string . type_name () << '\\n' ; } Output: null is a null true is a boolea n -17 is a nu mber 42 is a nu mber 23.42 is a nu mber { \"one\" : 1 , \"two\" : 2 } is a n objec t [ 1 , 2 , 4 , 8 , 16 ] is a n array \"Hello, world\" is a s tr i n g","title":"Examples"},{"location":"api/basic_json/type_name/#version-history","text":"Added in version 1.0.0. Part of the public API version since 2.1.0. Changed return value to const char* and added noexcept in version 3.0.0. Added support for binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/unflatten/","text":"nlohmann::basic_json:: unflatten \u00b6 basic_json unflatten () const ; The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints: The value must be an object. The keys must be JSON pointers (see RFC 6901 ) The mapped values must be primitive JSON types. Return value \u00b6 the original JSON from a flattened version Exception safety \u00b6 Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.314 if value is not an object Throws type_error.315 if object values are not primitive Complexity \u00b6 Linear in the size the JSON value. Notes \u00b6 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 () . Examples \u00b6 Example The following code shows how a flattened JSON object is unflattened into the original nested JSON object. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j_flattened = { { \"/answer/everything\" , 42 }, { \"/happy\" , true }, { \"/list/0\" , 1 }, { \"/list/1\" , 0 }, { \"/list/2\" , 2 }, { \"/name\" , \"Niels\" }, { \"/nothing\" , nullptr }, { \"/object/currency\" , \"USD\" }, { \"/object/value\" , 42.99 }, { \"/pi\" , 3.141 } }; // call unflatten() std :: cout << std :: setw ( 4 ) << j_flattened . unflatten () << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 } See also \u00b6 flatten the reverse function Version history \u00b6 Added in version 2.0.0.","title":"unflatten"},{"location":"api/basic_json/unflatten/#nlohmannbasic_jsonunflatten","text":"basic_json unflatten () const ; The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints: The value must be an object. The keys must be JSON pointers (see RFC 6901 ) The mapped values must be primitive JSON types.","title":"nlohmann::basic_json::unflatten"},{"location":"api/basic_json/unflatten/#return-value","text":"the original JSON from a flattened version","title":"Return value"},{"location":"api/basic_json/unflatten/#exception-safety","text":"Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/basic_json/unflatten/#exceptions","text":"The function can throw the following exceptions: Throws type_error.314 if value is not an object Throws type_error.315 if object values are not primitive","title":"Exceptions"},{"location":"api/basic_json/unflatten/#complexity","text":"Linear in the size the JSON value.","title":"Complexity"},{"location":"api/basic_json/unflatten/#notes","text":"Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j , the following is always true: j == j . flatten (). unflatten () .","title":"Notes"},{"location":"api/basic_json/unflatten/#examples","text":"Example The following code shows how a flattened JSON object is unflattened into the original nested JSON object. #include #include #include using json = nlohmann :: json ; int main () { // create JSON value json j_flattened = { { \"/answer/everything\" , 42 }, { \"/happy\" , true }, { \"/list/0\" , 1 }, { \"/list/1\" , 0 }, { \"/list/2\" , 2 }, { \"/name\" , \"Niels\" }, { \"/nothing\" , nullptr }, { \"/object/currency\" , \"USD\" }, { \"/object/value\" , 42.99 }, { \"/pi\" , 3.141 } }; // call unflatten() std :: cout << std :: setw ( 4 ) << j_flattened . unflatten () << '\\n' ; } Output: { \"answer\" : { \"everything\" : 42 }, \"happy\" : true , \"list\" : [ 1 , 0 , 2 ], \"name\" : \"Niels\" , \"nothing\" : null , \"object\" : { \"currency\" : \"USD\" , \"value\" : 42.99 }, \"pi\" : 3.141 }","title":"Examples"},{"location":"api/basic_json/unflatten/#see-also","text":"flatten the reverse function","title":"See also"},{"location":"api/basic_json/unflatten/#version-history","text":"Added in version 2.0.0.","title":"Version history"},{"location":"api/basic_json/update/","text":"nlohmann::basic_json:: update \u00b6 // (1) void update ( const_reference j , bool merge_objects = false ); // (2) void update ( const_iterator first , const_iterator last , bool merge_objects = false ); Inserts all values from JSON object j . Inserts all values from range [first, last) When merge_objects is false (default), existing keys are overwritten. When merge_objects is true , recursively merges objects with common keys. The function is motivated by Python's dict.update function. Parameters \u00b6 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 Exceptions \u00b6 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\" Complexity \u00b6 O(N*log(size() + N)), where N is the number of elements to insert. O(N*log(size() + N)), where N is the number of elements to insert. Examples \u00b6 Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 ); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 , true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 . begin (), o2 . end ()); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 . begin (), o2 . end (), true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects: { \"color\" : \"red\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" } } The user may override the default settings selectively: { \"color\" : \"blue\" , \"name\" : { \"es\" : \"rat\u00f3n\" }, } Then update manages the merging of default settings and user settings: auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings ); Now effective_settings contains the default settings, but those keys set by the user are overwritten: { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"es\" : \"rat\u00f3n\" } } Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true : auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings , true ); { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" , \"es\" : \"rat\u00f3n\" } } Version history \u00b6 Added in version 3.0.0. Added merge_objects parameter in 3.10.4.","title":"update"},{"location":"api/basic_json/update/#nlohmannbasic_jsonupdate","text":"// (1) void update ( const_reference j , bool merge_objects = false ); // (2) void update ( const_iterator first , const_iterator last , bool merge_objects = false ); Inserts all values from JSON object j . Inserts all values from range [first, last) When merge_objects is false (default), existing keys are overwritten. When merge_objects is true , recursively merges objects with common keys. The function is motivated by Python's dict.update function.","title":"nlohmann::basic_json::update"},{"location":"api/basic_json/update/#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","title":"Parameters"},{"location":"api/basic_json/update/#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\"","title":"Exceptions"},{"location":"api/basic_json/update/#complexity","text":"O(N*log(size() + N)), where N is the number of elements to insert. O(N*log(size() + N)), where N is the number of elements to insert.","title":"Complexity"},{"location":"api/basic_json/update/#examples","text":"Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 ); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 , true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example The example shows how update() is used. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create two JSON objects json o1 = R \" ( {\"color\": \"red\", \"price\": 17.99, \"names\": {\"de\": \"Flugzeug\"}} ) \" _json ; json o2 = R \" ( {\"color\": \"blue\", \"speed\": 100, \"names\": {\"en\": \"plane\"}} ) \" _json ; json o3 = o1 ; // add all keys from o2 to o1 (updating \"color\", replacing \"names\") o1 . update ( o2 . begin (), o2 . end ()); // add all keys from o2 to o1 (updating \"color\", merging \"names\") o3 . update ( o2 . begin (), o2 . end (), true ); // output updated object o1 and o3 std :: cout << std :: setw ( 2 ) << o1 << '\\n' ; std :: cout << std :: setw ( 2 ) << o3 << '\\n' ; } Output: { \"color\" : \"blue\" , \"names\" : { \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } { \"color\" : \"blue\" , \"names\" : { \"de\" : \"Flugzeug\" , \"en\" : \"plane\" }, \"price\" : 17.99 , \"speed\" : 100 } Example One common use case for this function is the handling of user settings. Assume your application can be configured in some aspects: { \"color\" : \"red\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" } } The user may override the default settings selectively: { \"color\" : \"blue\" , \"name\" : { \"es\" : \"rat\u00f3n\" }, } Then update manages the merging of default settings and user settings: auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings ); Now effective_settings contains the default settings, but those keys set by the user are overwritten: { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"es\" : \"rat\u00f3n\" } } Note existing keys were just overwritten. To merge objects, merge_objects setting should be set to true : auto user_settings = json :: parse ( \"config.json\" ); auto effective_settings = get_default_settings (); effective_settings . update ( user_settings , true ); { \"color\" : \"blue\" , \"active\" : true , \"name\" : { \"de\" : \"Maus\" , \"en\" : \"mouse\" , \"es\" : \"rat\u00f3n\" } }","title":"Examples"},{"location":"api/basic_json/update/#version-history","text":"Added in version 3.0.0. Added merge_objects parameter in 3.10.4.","title":"Version history"},{"location":"api/basic_json/value/","text":"nlohmann::basic_json:: value \u00b6 // (1) template < class ValueType > ValueType value ( const typename object_t :: key_type & key , ValueType && default_value ) const ; // (2) template < class ValueType , class KeyType > ValueType value ( KeyType && key , ValueType && default_value ) const ; // (3) template < class ValueType > ValueType value ( const json_pointer & ptr , const ValueType & default_value ) const ; Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists. The function is basically equivalent to executing try { return at ( key ); } catch ( out_of_range ) { return default_value ; } See 1. This overload is only available if KeyType is comparable with typename object_t :: key_type and typename object_comparator_t :: is_transparent denotes a type. Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists. The function is basically equivalent to executing try { return at ( ptr ); } catch ( out_of_range ) { return default_value ; } Differences to at and operator[] 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. Template parameters \u00b6 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. Parameters \u00b6 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 Return value \u00b6 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 Exception safety \u00b6 Strong guarantee: if an exception is thrown, there are no changes to any JSON value. Exceptions \u00b6 The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at key Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense. See 1. The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at ptr Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense. Complexity \u00b6 Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container. Examples \u00b6 Example: (1) access specified object element with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" , 0 ); double v_floating = j . value ( \"floating\" , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (2) access specified object element using string_view with default value The example below shows how object elements can be queried with a default value. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" sv , 0 ); double v_floating = j . value ( \"floating\" sv , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" sv , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" sv , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (3) access specified object element via JSON Pointer with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"/integer\" _json_pointer , 0 ); double v_floating = j . value ( \"/floating\" _json_pointer , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"/nonexisting\" _json_pointer , \"oops\" ); bool v_boolean = j . value ( \"/nonexisting\" _json_pointer , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false See also \u00b6 see at for access by reference with range checking see operator[] for unchecked access by reference Version history \u00b6 Added in version 1.0.0. Changed parameter default_value type from const ValueType& to ValueType&& in version 3.11.0. Added in version 3.11.0. Made ValueType the first template parameter in version 3.11.2. Added in version 2.0.2.","title":"value"},{"location":"api/basic_json/value/#nlohmannbasic_jsonvalue","text":"// (1) template < class ValueType > ValueType value ( const typename object_t :: key_type & key , ValueType && default_value ) const ; // (2) template < class ValueType , class KeyType > ValueType value ( KeyType && key , ValueType && default_value ) const ; // (3) template < class ValueType > ValueType value ( const json_pointer & ptr , const ValueType & default_value ) const ; Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists. The function is basically equivalent to executing try { return at ( key ); } catch ( out_of_range ) { return default_value ; } See 1. This overload is only available if KeyType is comparable with typename object_t :: key_type and typename object_comparator_t :: is_transparent denotes a type. Returns either a copy of an object's element at the specified JSON pointer ptr or a given default value if no value at ptr exists. The function is basically equivalent to executing try { return at ( ptr ); } catch ( out_of_range ) { return default_value ; } Differences to at and operator[] 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.","title":"nlohmann::basic_json::value"},{"location":"api/basic_json/value/#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.","title":"Template parameters"},{"location":"api/basic_json/value/#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","title":"Parameters"},{"location":"api/basic_json/value/#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","title":"Return value"},{"location":"api/basic_json/value/#exception-safety","text":"Strong guarantee: if an exception is thrown, there are no changes to any JSON value.","title":"Exception safety"},{"location":"api/basic_json/value/#exceptions","text":"The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at key Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense. See 1. The function can throw the following exceptions: Throws type_error.302 if default_value does not match the type of the value at ptr Throws type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.","title":"Exceptions"},{"location":"api/basic_json/value/#complexity","text":"Logarithmic in the size of the container. Logarithmic in the size of the container. Logarithmic in the size of the container.","title":"Complexity"},{"location":"api/basic_json/value/#examples","text":"Example: (1) access specified object element with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" , 0 ); double v_floating = j . value ( \"floating\" , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (2) access specified object element using string_view with default value The example below shows how object elements can be queried with a default value. #include #include #include using namespace std :: string_view_literals ; using json = nlohmann :: json ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"integer\" sv , 0 ); double v_floating = j . value ( \"floating\" sv , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"nonexisting\" sv , \"oops\" ); bool v_boolean = j . value ( \"nonexisting\" sv , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false Example: (3) access specified object element via JSON Pointer with default value The example below shows how object elements can be queried with a default value. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON object with different entry types json j = { { \"integer\" , 1 }, { \"floating\" , 42.23 }, { \"string\" , \"hello world\" }, { \"boolean\" , true }, { \"object\" , {{ \"key1\" , 1 }, { \"key2\" , 2 }}}, { \"array\" , { 1 , 2 , 3 }} }; // access existing values int v_integer = j . value ( \"/integer\" _json_pointer , 0 ); double v_floating = j . value ( \"/floating\" _json_pointer , 47.11 ); // access nonexisting values and rely on default value std :: string v_string = j . value ( \"/nonexisting\" _json_pointer , \"oops\" ); bool v_boolean = j . value ( \"/nonexisting\" _json_pointer , false ); // output values std :: cout << std :: boolalpha << v_integer << \" \" << v_floating << \" \" << v_string << \" \" << v_boolean << \" \\n \" ; } Output: 1 42.23 oops false","title":"Examples"},{"location":"api/basic_json/value/#see-also","text":"see at for access by reference with range checking see operator[] for unchecked access by reference","title":"See also"},{"location":"api/basic_json/value/#version-history","text":"Added in version 1.0.0. Changed parameter default_value type from const ValueType& to ValueType&& in version 3.11.0. Added in version 3.11.0. Made ValueType the first template parameter in version 3.11.2. Added in version 2.0.2.","title":"Version history"},{"location":"api/basic_json/value_t/","text":"nlohmann::basic_json:: value_t \u00b6 enum class value_t : std :: uint8_t { null , object , array , string , boolean , number_integer , number_unsigned , number_float , binary , discarded }; 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. Notes \u00b6 Ordering The order of types is as follows: null boolean number_integer , number_unsigned , number_float object array string binary discarded is unordered. Types of numbers There are three enumerators for numbers ( number_integer , number_unsigned , and number_float ) to distinguish between different types of numbers: 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 Examples \u00b6 Example The following code how type() queries the value_t for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true Version history \u00b6 Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"value_t"},{"location":"api/basic_json/value_t/#nlohmannbasic_jsonvalue_t","text":"enum class value_t : std :: uint8_t { null , object , array , string , boolean , number_integer , number_unsigned , number_float , binary , discarded }; 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.","title":"nlohmann::basic_json::value_t"},{"location":"api/basic_json/value_t/#notes","text":"Ordering The order of types is as follows: null boolean number_integer , number_unsigned , number_float object array string binary discarded is unordered. Types of numbers There are three enumerators for numbers ( number_integer , number_unsigned , and number_float ) to distinguish between different types of numbers: 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","title":"Notes"},{"location":"api/basic_json/value_t/#examples","text":"Example The following code how type() queries the value_t for all JSON types. #include #include using json = nlohmann :: json ; int main () { // create JSON values json j_null ; json j_boolean = true ; json j_number_integer = -17 ; json j_number_unsigned = 42u ; json j_number_float = 23.42 ; json j_object = {{ \"one\" , 1 }, { \"two\" , 2 }}; json j_array = { 1 , 2 , 4 , 8 , 16 }; json j_string = \"Hello, world\" ; // call type() std :: cout << std :: boolalpha ; std :: cout << ( j_null . type () == json :: value_t :: null ) << '\\n' ; std :: cout << ( j_boolean . type () == json :: value_t :: boolean ) << '\\n' ; std :: cout << ( j_number_integer . type () == json :: value_t :: number_integer ) << '\\n' ; std :: cout << ( j_number_unsigned . type () == json :: value_t :: number_unsigned ) << '\\n' ; std :: cout << ( j_number_float . type () == json :: value_t :: number_float ) << '\\n' ; std :: cout << ( j_object . type () == json :: value_t :: object ) << '\\n' ; std :: cout << ( j_array . type () == json :: value_t :: array ) << '\\n' ; std :: cout << ( j_string . type () == json :: value_t :: string ) << '\\n' ; } Output: true true true true true true true true","title":"Examples"},{"location":"api/basic_json/value_t/#version-history","text":"Added in version 1.0.0. Added unsigned integer type in version 2.0.0. Added binary type in version 3.8.0.","title":"Version history"},{"location":"api/basic_json/~basic_json/","text":"nlohmann::basic_json:: ~basic_json \u00b6 ~ basic_json () noexcept ; Destroys the JSON value and frees all allocated memory. Exception safety \u00b6 No-throw guarantee: this member function never throws exceptions. Complexity \u00b6 Linear. Version history \u00b6 Added in version 1.0.0.","title":"(Destructor)"},{"location":"api/basic_json/~basic_json/#nlohmannbasic_jsonbasic_json","text":"~ basic_json () noexcept ; Destroys the JSON value and frees all allocated memory.","title":"nlohmann::basic_json::~basic_json"},{"location":"api/basic_json/~basic_json/#exception-safety","text":"No-throw guarantee: this member function never throws exceptions.","title":"Exception safety"},{"location":"api/basic_json/~basic_json/#complexity","text":"Linear.","title":"Complexity"},{"location":"api/basic_json/~basic_json/#version-history","text":"Added in version 1.0.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/","text":"nlohmann:: byte_container_with_subtype \u00b6 template < typename BinaryType > class byte_container_with_subtype : public BinaryType ; 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. Template parameters \u00b6 BinaryType container to store bytes ( std :: vector < std :: uint8_t > by default) Member types \u00b6 container_type - the type of the underlying container ( BinaryType ) subtype_type - the type of the subtype ( std :: uint64_t ) Member functions \u00b6 (constructor) operator== - comparison: equal operator!= - comparison: not equal set_subtype - sets the binary subtype subtype - return the binary subtype has_subtype - return whether the value has a subtype clear_subtype - clears the binary subtype Version history \u00b6 Added in version 3.8.0. Changed type of subtypes to std :: uint64_t in 3.10.0.","title":"Overview"},{"location":"api/byte_container_with_subtype/#nlohmannbyte_container_with_subtype","text":"template < typename BinaryType > class byte_container_with_subtype : public BinaryType ; 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.","title":"nlohmann::byte_container_with_subtype"},{"location":"api/byte_container_with_subtype/#template-parameters","text":"BinaryType container to store bytes ( std :: vector < std :: uint8_t > by default)","title":"Template parameters"},{"location":"api/byte_container_with_subtype/#member-types","text":"container_type - the type of the underlying container ( BinaryType ) subtype_type - the type of the subtype ( std :: uint64_t )","title":"Member types"},{"location":"api/byte_container_with_subtype/#member-functions","text":"(constructor) operator== - comparison: equal operator!= - comparison: not equal set_subtype - sets the binary subtype subtype - return the binary subtype has_subtype - return whether the value has a subtype clear_subtype - clears the binary subtype","title":"Member functions"},{"location":"api/byte_container_with_subtype/#version-history","text":"Added in version 3.8.0. Changed type of subtypes to std :: uint64_t in 3.10.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/","text":"nlohmann::byte_container_with_subtype:: byte_container_with_subtype \u00b6 // (1) byte_container_with_subtype (); // (2) byte_container_with_subtype ( const container_type & container ); byte_container_with_subtype ( container_type && container ); // (3) byte_container_with_subtype ( const container_type & container , subtype_type subtype ); byte_container_with_subtype ( container_type && container , subtype_type subtype ); Create empty binary container without subtype. Create binary container without subtype. Create binary container with subtype. Parameters \u00b6 container (in) binary container subtype (in) subtype Examples \u00b6 Example The example below demonstrates how byte containers can be created. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { // (1) create empty container auto c1 = byte_container_with_subtype (); std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // (2) create container auto c2 = byte_container_with_subtype ( bytes ); // (3) create container with subtype auto c3 = byte_container_with_subtype ( bytes , 42 ); std :: cout << json ( c1 ) << \" \\n \" << json ( c2 ) << \" \\n \" << json ( c3 ) << std :: endl ; } Output: { \"bytes\" :[], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } Version history \u00b6 Since version 3.8.0.","title":"(constructor)"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#nlohmannbyte_container_with_subtypebyte_container_with_subtype","text":"// (1) byte_container_with_subtype (); // (2) byte_container_with_subtype ( const container_type & container ); byte_container_with_subtype ( container_type && container ); // (3) byte_container_with_subtype ( const container_type & container , subtype_type subtype ); byte_container_with_subtype ( container_type && container , subtype_type subtype ); Create empty binary container without subtype. Create binary container without subtype. Create binary container with subtype.","title":"nlohmann::byte_container_with_subtype::byte_container_with_subtype"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#parameters","text":"container (in) binary container subtype (in) subtype","title":"Parameters"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#examples","text":"Example The example below demonstrates how byte containers can be created. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { // (1) create empty container auto c1 = byte_container_with_subtype (); std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // (2) create container auto c2 = byte_container_with_subtype ( bytes ); // (3) create container with subtype auto c3 = byte_container_with_subtype ( bytes , 42 ); std :: cout << json ( c1 ) << \" \\n \" << json ( c2 ) << \" \\n \" << json ( c3 ) << std :: endl ; } Output: { \"bytes\" :[], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 }","title":"Examples"},{"location":"api/byte_container_with_subtype/byte_container_with_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/clear_subtype/","text":"nlohmann::byte_container_with_subtype:: clear_subtype \u00b6 void clear_subtype () noexcept ; 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. Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how clear_subtype can remove subtypes. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container with subtype auto c1 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"before calling clear_subtype(): \" << json ( c1 ) << '\\n' ; c1 . clear_subtype (); std :: cout << \"after calling clear_subtype(): \" << json ( c1 ) << '\\n' ; } Output: be f ore calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } a fter calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } Version history \u00b6 Since version 3.8.0.","title":"clear_subtype"},{"location":"api/byte_container_with_subtype/clear_subtype/#nlohmannbyte_container_with_subtypeclear_subtype","text":"void clear_subtype () noexcept ; 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.","title":"nlohmann::byte_container_with_subtype::clear_subtype"},{"location":"api/byte_container_with_subtype/clear_subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/clear_subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/clear_subtype/#examples","text":"Example The example below demonstrates how clear_subtype can remove subtypes. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container with subtype auto c1 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"before calling clear_subtype(): \" << json ( c1 ) << '\\n' ; c1 . clear_subtype (); std :: cout << \"after calling clear_subtype(): \" << json ( c1 ) << '\\n' ; } Output: be f ore calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } a fter calli n g clear_sub t ype() : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null }","title":"Examples"},{"location":"api/byte_container_with_subtype/clear_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/has_subtype/","text":"nlohmann::byte_container_with_subtype:: has_subtype \u00b6 constexpr bool has_subtype () const noexcept ; Returns whether the value has a subtype. Return value \u00b6 whether the value has a subtype Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how has_subtype can check whether a subtype was set. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << std :: boolalpha << \"c1.has_subtype() = \" << c1 . has_subtype () << \" \\n c2.has_subtype() = \" << c2 . has_subtype () << std :: endl ; } Output: c 1. has_sub t ype() = false c 2. has_sub t ype() = true Version history \u00b6 Since version 3.8.0.","title":"has_subtype"},{"location":"api/byte_container_with_subtype/has_subtype/#nlohmannbyte_container_with_subtypehas_subtype","text":"constexpr bool has_subtype () const noexcept ; Returns whether the value has a subtype.","title":"nlohmann::byte_container_with_subtype::has_subtype"},{"location":"api/byte_container_with_subtype/has_subtype/#return-value","text":"whether the value has a subtype","title":"Return value"},{"location":"api/byte_container_with_subtype/has_subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/has_subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/has_subtype/#examples","text":"Example The example below demonstrates how has_subtype can check whether a subtype was set. #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << std :: boolalpha << \"c1.has_subtype() = \" << c1 . has_subtype () << \" \\n c2.has_subtype() = \" << c2 . has_subtype () << std :: endl ; } Output: c 1. has_sub t ype() = false c 2. has_sub t ype() = true","title":"Examples"},{"location":"api/byte_container_with_subtype/has_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/set_subtype/","text":"nlohmann::byte_container_with_subtype:: set_subtype \u00b6 void set_subtype ( subtype_type subtype ) noexcept ; Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization. Parameters \u00b6 subtype (in) subtype to set Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how a subtype can be set with set_subtype . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container without subtype auto c = byte_container_with_subtype ( bytes ); std :: cout << \"before calling set_subtype(42): \" << json ( c ) << '\\n' ; // set the subtype c . set_subtype ( 42 ); std :: cout << \"after calling set_subtype(42): \" << json ( c ) << '\\n' ; } Output: be f ore calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } a fter calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } Version history \u00b6 Since version 3.8.0.","title":"set_subtype"},{"location":"api/byte_container_with_subtype/set_subtype/#nlohmannbyte_container_with_subtypeset_subtype","text":"void set_subtype ( subtype_type subtype ) noexcept ; Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization.","title":"nlohmann::byte_container_with_subtype::set_subtype"},{"location":"api/byte_container_with_subtype/set_subtype/#parameters","text":"subtype (in) subtype to set","title":"Parameters"},{"location":"api/byte_container_with_subtype/set_subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/set_subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/set_subtype/#examples","text":"Example The example below demonstrates how a subtype can be set with set_subtype . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; using json = nlohmann :: json ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container without subtype auto c = byte_container_with_subtype ( bytes ); std :: cout << \"before calling set_subtype(42): \" << json ( c ) << '\\n' ; // set the subtype c . set_subtype ( 42 ); std :: cout << \"after calling set_subtype(42): \" << json ( c ) << '\\n' ; } Output: be f ore calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : null } a fter calli n g se t _sub t ype( 42 ) : { \"bytes\" :[ 202 , 254 , 186 , 190 ], \"subtype\" : 42 }","title":"Examples"},{"location":"api/byte_container_with_subtype/set_subtype/#version-history","text":"Since version 3.8.0.","title":"Version history"},{"location":"api/byte_container_with_subtype/subtype/","text":"nlohmann::byte_container_with_subtype:: subtype \u00b6 constexpr subtype_type subtype () const noexcept ; 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. Return value \u00b6 the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example below demonstrates how the subtype can be retrieved with subtype . Note how subtype_type(-1) is returned for container c1 . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"c1.subtype() = \" << c1 . subtype () << \" \\n c2.subtype() = \" << c2 . subtype () << std :: endl ; // in case no subtype is set, return special value assert ( c1 . subtype () == static_cast < byte_container_with_subtype :: subtype_type > ( -1 )); } Output: c 1. sub t ype() = 18446744073709551615 c 2. sub t ype() = 42 Version history \u00b6 Added in version 3.8.0 Fixed return value to properly return subtype_type(-1) as documented in version 3.10.0.","title":"subtype"},{"location":"api/byte_container_with_subtype/subtype/#nlohmannbyte_container_with_subtypesubtype","text":"constexpr subtype_type subtype () const noexcept ; 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.","title":"nlohmann::byte_container_with_subtype::subtype"},{"location":"api/byte_container_with_subtype/subtype/#return-value","text":"the numerical subtype of the binary value, or subtype_type(-1) if no subtype is set","title":"Return value"},{"location":"api/byte_container_with_subtype/subtype/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/byte_container_with_subtype/subtype/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/byte_container_with_subtype/subtype/#examples","text":"Example The example below demonstrates how the subtype can be retrieved with subtype . Note how subtype_type(-1) is returned for container c1 . #include #include // define a byte container based on std::vector using byte_container_with_subtype = nlohmann :: byte_container_with_subtype < std :: vector < std :: uint8_t >> ; int main () { std :: vector < std :: uint8_t > bytes = {{ 0xca , 0xfe , 0xba , 0xbe }}; // create container auto c1 = byte_container_with_subtype ( bytes ); // create container with subtype auto c2 = byte_container_with_subtype ( bytes , 42 ); std :: cout << \"c1.subtype() = \" << c1 . subtype () << \" \\n c2.subtype() = \" << c2 . subtype () << std :: endl ; // in case no subtype is set, return special value assert ( c1 . subtype () == static_cast < byte_container_with_subtype :: subtype_type > ( -1 )); } Output: c 1. sub t ype() = 18446744073709551615 c 2. sub t ype() = 42","title":"Examples"},{"location":"api/byte_container_with_subtype/subtype/#version-history","text":"Added in version 3.8.0 Fixed return value to properly return subtype_type(-1) as documented in version 3.10.0.","title":"Version history"},{"location":"api/json_pointer/","text":"nlohmann:: json_pointer \u00b6 template < typename RefStringType > class json_pointer ; 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. Template parameters \u00b6 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. Member types \u00b6 string_t - the string type used for the reference tokens Member functions \u00b6 (constructor) to_string - return a string representation of the JSON pointer operator string_t - return a string representation of the JSON pointer operator== - compare: equal operator!= - compare: not equal operator/= - append to the end of the JSON pointer operator/ - create JSON Pointer by appending parent_pointer - returns the parent of this JSON pointer pop_back - remove last reference token back - return last reference token push_back - append an unescaped token at the end of the pointer empty - return whether pointer points to the root document Literals \u00b6 operator\"\"_json_pointer - user-defined string literal for JSON pointers See also \u00b6 RFC 6901 Version history \u00b6 Added in version 2.0.0. Changed template parameter from basic_json to string type in version 3.11.0.","title":"Overview"},{"location":"api/json_pointer/#nlohmannjson_pointer","text":"template < typename RefStringType > class json_pointer ; 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.","title":"nlohmann::json_pointer"},{"location":"api/json_pointer/#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.","title":"Template parameters"},{"location":"api/json_pointer/#member-types","text":"string_t - the string type used for the reference tokens","title":"Member types"},{"location":"api/json_pointer/#member-functions","text":"(constructor) to_string - return a string representation of the JSON pointer operator string_t - return a string representation of the JSON pointer operator== - compare: equal operator!= - compare: not equal operator/= - append to the end of the JSON pointer operator/ - create JSON Pointer by appending parent_pointer - returns the parent of this JSON pointer pop_back - remove last reference token back - return last reference token push_back - append an unescaped token at the end of the pointer empty - return whether pointer points to the root document","title":"Member functions"},{"location":"api/json_pointer/#literals","text":"operator\"\"_json_pointer - user-defined string literal for JSON pointers","title":"Literals"},{"location":"api/json_pointer/#see-also","text":"RFC 6901","title":"See also"},{"location":"api/json_pointer/#version-history","text":"Added in version 2.0.0. Changed template parameter from basic_json to string type in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/back/","text":"nlohmann::json_pointer:: back \u00b6 const string_t & back () const ; Return last reference token. Return value \u00b6 Last reference token. Exceptions \u00b6 Throws out_of_range.405 if JSON pointer has no parent. Complexity \u00b6 Constant. Examples \u00b6 Example The example shows the usage of back . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo\" ); json :: json_pointer ptr2 ( \"/foo/0\" ); // call empty() std :: cout << \"last reference token of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . back () << \" \\\"\\n \" << \"last reference token of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . back () << \" \\\" \" << std :: endl ; } Output: las t re feren ce t oke n o f \"/foo\" is \"foo\" las t re feren ce t oke n o f \"/foo/0\" is \"0\" Version history \u00b6 Added in version 3.6.0. Changed return type to string_t in version 3.11.0.","title":"back"},{"location":"api/json_pointer/back/#nlohmannjson_pointerback","text":"const string_t & back () const ; Return last reference token.","title":"nlohmann::json_pointer::back"},{"location":"api/json_pointer/back/#return-value","text":"Last reference token.","title":"Return value"},{"location":"api/json_pointer/back/#exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.","title":"Exceptions"},{"location":"api/json_pointer/back/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/json_pointer/back/#examples","text":"Example The example shows the usage of back . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo\" ); json :: json_pointer ptr2 ( \"/foo/0\" ); // call empty() std :: cout << \"last reference token of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . back () << \" \\\"\\n \" << \"last reference token of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . back () << \" \\\" \" << std :: endl ; } Output: las t re feren ce t oke n o f \"/foo\" is \"foo\" las t re feren ce t oke n o f \"/foo/0\" is \"0\"","title":"Examples"},{"location":"api/json_pointer/back/#version-history","text":"Added in version 3.6.0. Changed return type to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/empty/","text":"nlohmann::json_pointer:: empty \u00b6 bool empty () const noexcept ; Return whether pointer points to the root document. Return value \u00b6 true iff the JSON pointer points to the root document. Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Complexity \u00b6 Constant. Examples \u00b6 Example The example shows the result of empty for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call empty() std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" : \" << ptr0 . empty () << '\\n' << \" \\\" \" << ptr1 << \" \\\" : \" << ptr1 . empty () << '\\n' << \" \\\" \" << ptr2 << \" \\\" : \" << ptr2 . empty () << '\\n' << \" \\\" \" << ptr3 << \" \\\" : \" << ptr3 . empty () << std :: endl ; } Output: \"\" : true \"\" : true \"/foo\" : false \"/foo/0\" : false Version history \u00b6 Added in version 3.6.0.","title":"empty"},{"location":"api/json_pointer/empty/#nlohmannjson_pointerempty","text":"bool empty () const noexcept ; Return whether pointer points to the root document.","title":"nlohmann::json_pointer::empty"},{"location":"api/json_pointer/empty/#return-value","text":"true iff the JSON pointer points to the root document.","title":"Return value"},{"location":"api/json_pointer/empty/#exception-safety","text":"No-throw guarantee: this function never throws exceptions.","title":"Exception safety"},{"location":"api/json_pointer/empty/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/json_pointer/empty/#examples","text":"Example The example shows the result of empty for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call empty() std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" : \" << ptr0 . empty () << '\\n' << \" \\\" \" << ptr1 << \" \\\" : \" << ptr1 . empty () << '\\n' << \" \\\" \" << ptr2 << \" \\\" : \" << ptr2 . empty () << '\\n' << \" \\\" \" << ptr3 << \" \\\" : \" << ptr3 . empty () << std :: endl ; } Output: \"\" : true \"\" : true \"/foo\" : false \"/foo/0\" : false","title":"Examples"},{"location":"api/json_pointer/empty/#version-history","text":"Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/json_pointer/","text":"nlohmann::json_pointer:: json_pointer \u00b6 explicit json_pointer ( const string_t & s = \"\" ); Create a JSON pointer according to the syntax described in Section 3 of RFC6901 . Parameters \u00b6 s (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value Exceptions \u00b6 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. Examples \u00b6 Example The example shows the construction several valid JSON pointers as well as the exceptional behavior. #include #include using json = nlohmann :: json ; int main () { // correct JSON pointers json :: json_pointer p1 ; json :: json_pointer p2 ( \"\" ); json :: json_pointer p3 ( \"/\" ); json :: json_pointer p4 ( \"//\" ); json :: json_pointer p5 ( \"/foo/bar\" ); json :: json_pointer p6 ( \"/foo/bar/-\" ); json :: json_pointer p7 ( \"/foo/~0\" ); json :: json_pointer p8 ( \"/foo/~1\" ); // error: JSON pointer does not begin with a slash try { json :: json_pointer p9 ( \"foo\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p10 ( \"/foo/~\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p11 ( \"/foo/~3\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ jso n .excep t io n .parse_error. 107 ] parse error a t by te 1 : JSON poi nter mus t be emp t y or begi n wi t h '/' - was : ' f oo' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 ' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 ' Version history \u00b6 Added in version 2.0.0. Changed type of s to string_t in version 3.11.0.","title":"(Constructor)"},{"location":"api/json_pointer/json_pointer/#nlohmannjson_pointerjson_pointer","text":"explicit json_pointer ( const string_t & s = \"\" ); Create a JSON pointer according to the syntax described in Section 3 of RFC6901 .","title":"nlohmann::json_pointer::json_pointer"},{"location":"api/json_pointer/json_pointer/#parameters","text":"s (in) string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value","title":"Parameters"},{"location":"api/json_pointer/json_pointer/#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.","title":"Exceptions"},{"location":"api/json_pointer/json_pointer/#examples","text":"Example The example shows the construction several valid JSON pointers as well as the exceptional behavior. #include #include using json = nlohmann :: json ; int main () { // correct JSON pointers json :: json_pointer p1 ; json :: json_pointer p2 ( \"\" ); json :: json_pointer p3 ( \"/\" ); json :: json_pointer p4 ( \"//\" ); json :: json_pointer p5 ( \"/foo/bar\" ); json :: json_pointer p6 ( \"/foo/bar/-\" ); json :: json_pointer p7 ( \"/foo/~0\" ); json :: json_pointer p8 ( \"/foo/~1\" ); // error: JSON pointer does not begin with a slash try { json :: json_pointer p9 ( \"foo\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p10 ( \"/foo/~\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } // error: JSON pointer uses escape symbol ~ not followed by 0 or 1 try { json :: json_pointer p11 ( \"/foo/~3\" ); } catch ( const json :: parse_error & e ) { std :: cout << e . what () << '\\n' ; } } Output: [ jso n .excep t io n .parse_error. 107 ] parse error a t by te 1 : JSON poi nter mus t be emp t y or begi n wi t h '/' - was : ' f oo' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 ' [ jso n .excep t io n .parse_error. 108 ] parse error : escape charac ter '~' mus t be f ollowed wi t h ' 0 ' or ' 1 '","title":"Examples"},{"location":"api/json_pointer/json_pointer/#version-history","text":"Added in version 2.0.0. Changed type of s to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/operator_eq/","text":"nlohmann::json_pointer:: operator== \u00b6 // until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator == ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) // since C++20 class json_pointer { template < typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeRhs >& rhs ) const noexcept ; // (1) bool operator == ( const string_t & rhs ) const ; // (2) }; 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. Template parameters \u00b6 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 ) Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 (none) The function can throw the following exceptions: 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. Complexity \u00b6 Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens. Notes \u00b6 Deprecation Overload 2 is deprecated and will be removed in a future major version release. Examples \u00b6 Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 == ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 == ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 == ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 == ptr2 ) << std :: endl ; } Output: \"\" == \"\": true \"\" == \"\": true \"\" == \"/foo\": false \"/foo\" == \"/foo\": true Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << str0 << \" \\\" : \" << ( ptr0 == str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( str0 == ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << str1 << \" \\\" : \" << ( ptr2 == str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( str2 == ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" == \"\": true \"\" == \"\": true \"/foo\" == \"/foo\": true \"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar' Version history \u00b6 Added in version 2.1.0. Added C++20 member functions in version 3.11.2. Added for backward compatibility and deprecated in version 3.11.2.","title":"operator=="},{"location":"api/json_pointer/operator_eq/#nlohmannjson_pointeroperator","text":"// until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator == ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator == ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) // since C++20 class json_pointer { template < typename RefStringTypeRhs > bool operator == ( const json_pointer < RefStringTypeRhs >& rhs ) const noexcept ; // (1) bool operator == ( const string_t & rhs ) const ; // (2) }; 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.","title":"nlohmann::json_pointer::operator=="},{"location":"api/json_pointer/operator_eq/#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 )","title":"Template parameters"},{"location":"api/json_pointer/operator_eq/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/json_pointer/operator_eq/#return-value","text":"whether the values lhs / *this and rhs are equal","title":"Return value"},{"location":"api/json_pointer/operator_eq/#exception-safety","text":"No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/json_pointer/operator_eq/#exceptions","text":"(none) The function can throw the following exceptions: 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.","title":"Exceptions"},{"location":"api/json_pointer/operator_eq/#complexity","text":"Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.","title":"Complexity"},{"location":"api/json_pointer/operator_eq/#notes","text":"Deprecation Overload 2 is deprecated and will be removed in a future major version release.","title":"Notes"},{"location":"api/json_pointer/operator_eq/#examples","text":"Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 == ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 == ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 == ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 == ptr2 ) << std :: endl ; } Output: \"\" == \"\": true \"\" == \"\": true \"\" == \"/foo\": false \"/foo\" == \"/foo\": true Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" == \\\" \" << str0 << \" \\\" : \" << ( ptr0 == str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" == \\\" \" << ptr1 << \" \\\" : \" << ( str0 == ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" == \\\" \" << str1 << \" \\\" : \" << ( ptr2 == str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" == \\\" \" << ptr2 << \" \\\" : \" << ( str2 == ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" == \"\": true \"\" == \"\": true \"/foo\" == \"/foo\": true \"bar\" == \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'","title":"Examples"},{"location":"api/json_pointer/operator_eq/#version-history","text":"Added in version 2.1.0. Added C++20 member functions in version 3.11.2. Added for backward compatibility and deprecated in version 3.11.2.","title":"Version history"},{"location":"api/json_pointer/operator_ne/","text":"nlohmann::json_pointer:: operator!= \u00b6 // until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator != ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) 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. Template parameters \u00b6 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 ) Parameters \u00b6 lhs (in) first value to consider rhs (in) second value to consider Return value \u00b6 whether the values lhs / *this and rhs are not equal Exception safety \u00b6 No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact. Exceptions \u00b6 (none) The function can throw the following exceptions: 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. Complexity \u00b6 Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens. Notes \u00b6 Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator== . Deprecation Overload 2 is deprecated and will be removed in a future major version release. Examples \u00b6 Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 != ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 != ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 != ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 != ptr2 ) << std :: endl ; } Output: \"\" != \"\": false \"\" != \"\": false \"\" != \"/foo\": true \"/foo\" != \"/foo\": false Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << str0 << \" \\\" : \" << ( ptr0 != str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( str0 != ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << str1 << \" \\\" : \" << ( ptr2 != str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( str2 != ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" != \"\": false \"\" != \"\": false \"/foo\" != \"/foo\": false \"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar' Version history \u00b6 Added in version 2.1.0. Added for backward compatibility and deprecated in version 3.11.2.","title":"operator!="},{"location":"api/json_pointer/operator_ne/#nlohmannjson_pointeroperator","text":"// until C++20 template < typename RefStringTypeLhs , typename RefStringTypeRhs > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const json_pointer < RefStringTypeRhs >& rhs ) noexcept ; // (1) template < typename RefStringTypeLhs , typename StringType > bool operator != ( const json_pointer < RefStringTypeLhs >& lhs , const StringType & rhs ); // (2) template < typename RefStringTypeRhs , typename StringType > bool operator != ( const StringType & lhs , const json_pointer < RefStringTypeRhs >& rhs ); // (2) 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.","title":"nlohmann::json_pointer::operator!="},{"location":"api/json_pointer/operator_ne/#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 )","title":"Template parameters"},{"location":"api/json_pointer/operator_ne/#parameters","text":"lhs (in) first value to consider rhs (in) second value to consider","title":"Parameters"},{"location":"api/json_pointer/operator_ne/#return-value","text":"whether the values lhs / *this and rhs are not equal","title":"Return value"},{"location":"api/json_pointer/operator_ne/#exception-safety","text":"No-throw guarantee: this function never throws exceptions. Strong exception safety: if an exception occurs, the original value stays intact.","title":"Exception safety"},{"location":"api/json_pointer/operator_ne/#exceptions","text":"(none) The function can throw the following exceptions: 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.","title":"Exceptions"},{"location":"api/json_pointer/operator_ne/#complexity","text":"Constant if lhs and rhs differ in the number of reference tokens, otherwise linear in the number of reference tokens.","title":"Complexity"},{"location":"api/json_pointer/operator_ne/#notes","text":"Operator overload resolution Since C++20 overload resolution will consider the rewritten candidate generated from operator== . Deprecation Overload 2 is deprecated and will be removed in a future major version release.","title":"Notes"},{"location":"api/json_pointer/operator_ne/#examples","text":"Example: (1) Comparing JSON pointers The example demonstrates comparing JSON pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // compare JSON pointers std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr0 << \" \\\" : \" << ( ptr0 != ptr0 ) << '\\n' << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( ptr0 != ptr1 ) << '\\n' << \" \\\" \" << ptr1 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr1 != ptr2 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( ptr2 != ptr2 ) << std :: endl ; } Output: \"\" != \"\": false \"\" != \"\": false \"\" != \"/foo\": true \"/foo\" != \"/foo\": false Example: (2) Comparing JSON pointers and strings The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception. #include #include using json = nlohmann :: json ; int main () { // different JSON pointers json :: json_pointer ptr0 ; json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); // different strings std :: string str0 ( \"\" ); std :: string str1 ( \"/foo\" ); std :: string str2 ( \"bar\" ); // compare JSON pointers and strings std :: cout << std :: boolalpha << \" \\\" \" << ptr0 << \" \\\" != \\\" \" << str0 << \" \\\" : \" << ( ptr0 != str0 ) << '\\n' << \" \\\" \" << str0 << \" \\\" != \\\" \" << ptr1 << \" \\\" : \" << ( str0 != ptr1 ) << '\\n' << \" \\\" \" << ptr2 << \" \\\" != \\\" \" << str1 << \" \\\" : \" << ( ptr2 != str1 ) << std :: endl ; try { std :: cout << \" \\\" \" << str2 << \" \\\" != \\\" \" << ptr2 << \" \\\" : \" << ( str2 != ptr2 ) << std :: endl ; } catch ( const json :: parse_error & ex ) { std :: cout << ex . what () << std :: endl ; } } Output: \"\" != \"\": false \"\" != \"\": false \"/foo\" != \"/foo\": false \"bar\" != \"/foo\": [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'bar'","title":"Examples"},{"location":"api/json_pointer/operator_ne/#version-history","text":"Added in version 2.1.0. Added for backward compatibility and deprecated in version 3.11.2.","title":"Version history"},{"location":"api/json_pointer/operator_slash/","text":"nlohmann::json_pointer:: operator/ \u00b6 // (1) json_pointer operator / ( const json_pointer & lhs , const json_pointer & rhs ); // (2) json_pointer operator / ( const json_pointer & lhs , string_t token ); // (3) json_pointer operator / ( const json_pointer & lhs , std :: size_t array_idx ); create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer create a new JSON pointer by appending the unescaped token at the end of the JSON pointer create a new JSON pointer by appending the array-index-token at the end of the JSON pointer Parameters \u00b6 lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append Return value \u00b6 a new JSON pointer with rhs appended to lhs a new JSON pointer with unescaped token appended to lhs a new JSON pointer with array_idx appended to lhs Complexity \u00b6 Linear in the length of lhs and rhs . Linear in the length of lhs . Linear in the length of lhs . Examples \u00b6 Example The example shows the usage of operator/ . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); // append a JSON Pointer std :: cout << \" \\\" \" << ptr / json :: json_pointer ( \"/bar/baz\" ) << \" \\\"\\n \" ; // append a string std :: cout << \" \\\" \" << ptr / \"fob\" << \" \\\"\\n \" ; // append an array index std :: cout << \" \\\" \" << ptr / 42 << \" \\\" \" << std :: endl ; } Output: \"/foo/bar/baz\" \"/foo/fob\" \"/foo/42\" Version history \u00b6 Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"operator/"},{"location":"api/json_pointer/operator_slash/#nlohmannjson_pointeroperator","text":"// (1) json_pointer operator / ( const json_pointer & lhs , const json_pointer & rhs ); // (2) json_pointer operator / ( const json_pointer & lhs , string_t token ); // (3) json_pointer operator / ( const json_pointer & lhs , std :: size_t array_idx ); create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer create a new JSON pointer by appending the unescaped token at the end of the JSON pointer create a new JSON pointer by appending the array-index-token at the end of the JSON pointer","title":"nlohmann::json_pointer::operator/"},{"location":"api/json_pointer/operator_slash/#parameters","text":"lhs (in) JSON pointer rhs (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append","title":"Parameters"},{"location":"api/json_pointer/operator_slash/#return-value","text":"a new JSON pointer with rhs appended to lhs a new JSON pointer with unescaped token appended to lhs a new JSON pointer with array_idx appended to lhs","title":"Return value"},{"location":"api/json_pointer/operator_slash/#complexity","text":"Linear in the length of lhs and rhs . Linear in the length of lhs . Linear in the length of lhs .","title":"Complexity"},{"location":"api/json_pointer/operator_slash/#examples","text":"Example The example shows the usage of operator/ . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); // append a JSON Pointer std :: cout << \" \\\" \" << ptr / json :: json_pointer ( \"/bar/baz\" ) << \" \\\"\\n \" ; // append a string std :: cout << \" \\\" \" << ptr / \"fob\" << \" \\\"\\n \" ; // append an array index std :: cout << \" \\\" \" << ptr / 42 << \" \\\" \" << std :: endl ; } Output: \"/foo/bar/baz\" \"/foo/fob\" \"/foo/42\"","title":"Examples"},{"location":"api/json_pointer/operator_slash/#version-history","text":"Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/operator_slasheq/","text":"nlohmann::json_pointer:: operator/= \u00b6 // (1) json_pointer & operator /= ( const json_pointer & ptr ); // (2) json_pointer & operator /= ( string_t token ); // (3) json_pointer & operator /= ( std :: size_t array_idx ) 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 Parameters \u00b6 ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append Return value \u00b6 JSON pointer with ptr appended JSON pointer with token appended without escaping token JSON pointer with array_idx appended Complexity \u00b6 Linear in the length of ptr . Amortized constant. Amortized constant. Examples \u00b6 Example The example shows the usage of operator/= . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a JSON Pointer ptr /= json :: json_pointer ( \"/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a string ptr /= \"fob\" ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append an array index ptr /= 42 ; std :: cout << \" \\\" \" << ptr << \" \\\" \" << std :: endl ; } Output: \"/foo\" \"/foo/bar/baz\" \"/foo/bar/baz/fob\" \"/foo/bar/baz/fob/42\" Version history \u00b6 Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"operator/="},{"location":"api/json_pointer/operator_slasheq/#nlohmannjson_pointeroperator","text":"// (1) json_pointer & operator /= ( const json_pointer & ptr ); // (2) json_pointer & operator /= ( string_t token ); // (3) json_pointer & operator /= ( std :: size_t array_idx ) 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","title":"nlohmann::json_pointer::operator/="},{"location":"api/json_pointer/operator_slasheq/#parameters","text":"ptr (in) JSON pointer to append token (in) reference token to append array_idx (in) array index to append","title":"Parameters"},{"location":"api/json_pointer/operator_slasheq/#return-value","text":"JSON pointer with ptr appended JSON pointer with token appended without escaping token JSON pointer with array_idx appended","title":"Return value"},{"location":"api/json_pointer/operator_slasheq/#complexity","text":"Linear in the length of ptr . Amortized constant. Amortized constant.","title":"Complexity"},{"location":"api/json_pointer/operator_slasheq/#examples","text":"Example The example shows the usage of operator/= . #include #include using json = nlohmann :: json ; int main () { // create a JSON pointer json :: json_pointer ptr ( \"/foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a JSON Pointer ptr /= json :: json_pointer ( \"/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append a string ptr /= \"fob\" ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // append an array index ptr /= 42 ; std :: cout << \" \\\" \" << ptr << \" \\\" \" << std :: endl ; } Output: \"/foo\" \"/foo/bar/baz\" \"/foo/bar/baz/fob\" \"/foo/bar/baz/fob/42\"","title":"Examples"},{"location":"api/json_pointer/operator_slasheq/#version-history","text":"Added in version 3.6.0. Added in version 3.6.0. Changed type of token to string_t in version 3.11.0. Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/operator_string_t/","text":"nlohmann::json_pointer:: operator string_t \u00b6 operator string_t () const Return a string representation of the JSON pointer. Return value \u00b6 A string representation of the JSON pointer Possible implementation \u00b6 operator string_t () const { return to_string (); } Notes \u00b6 Deprecation This function is deprecated in favor of to_string and will be removed in a future major version release. Examples \u00b6 Example The example shows how JSON Pointers can be implicitly converted to strings. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo/0\" ); json :: json_pointer ptr2 ( \"/a~1b\" ); // implicit conversion to string std :: string s ; s += ptr1 ; s += \" \\n \" ; s += ptr2 ; std :: cout << s << std :: endl ; } Output: / f oo/ 0 /a~ 1 b Version history \u00b6 Since version 2.0.0. Changed type to string_t and deprecated in version 3.11.0.","title":"operator string_t"},{"location":"api/json_pointer/operator_string_t/#nlohmannjson_pointeroperator-string_t","text":"operator string_t () const Return a string representation of the JSON pointer.","title":"nlohmann::json_pointer::operator string_t"},{"location":"api/json_pointer/operator_string_t/#return-value","text":"A string representation of the JSON pointer","title":"Return value"},{"location":"api/json_pointer/operator_string_t/#possible-implementation","text":"operator string_t () const { return to_string (); }","title":"Possible implementation"},{"location":"api/json_pointer/operator_string_t/#notes","text":"Deprecation This function is deprecated in favor of to_string and will be removed in a future major version release.","title":"Notes"},{"location":"api/json_pointer/operator_string_t/#examples","text":"Example The example shows how JSON Pointers can be implicitly converted to strings. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"/foo/0\" ); json :: json_pointer ptr2 ( \"/a~1b\" ); // implicit conversion to string std :: string s ; s += ptr1 ; s += \" \\n \" ; s += ptr2 ; std :: cout << s << std :: endl ; } Output: / f oo/ 0 /a~ 1 b","title":"Examples"},{"location":"api/json_pointer/operator_string_t/#version-history","text":"Since version 2.0.0. Changed type to string_t and deprecated in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/parent_pointer/","text":"nlohmann::json_pointer:: parent_pointer \u00b6 json_pointer parent_pointer () const ; Returns the parent of this JSON pointer. Return value \u00b6 Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned. Complexity \u00b6 Linear in the length of the JSON pointer. Examples \u00b6 Example The example shows the result of parent_pointer for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call parent_pointer() std :: cout << std :: boolalpha << \"parent of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr3 << \" \\\" is \\\" \" << ptr3 . parent_pointer () << \" \\\" \" << std :: endl ; } Output: pare nt o f \"\" is \"\" pare nt o f \"/foo\" is \"\" pare nt o f \"/foo/0\" is \"/foo\" Version history \u00b6 Added in version 3.6.0.","title":"parent_pointer"},{"location":"api/json_pointer/parent_pointer/#nlohmannjson_pointerparent_pointer","text":"json_pointer parent_pointer () const ; Returns the parent of this JSON pointer.","title":"nlohmann::json_pointer::parent_pointer"},{"location":"api/json_pointer/parent_pointer/#return-value","text":"Parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned.","title":"Return value"},{"location":"api/json_pointer/parent_pointer/#complexity","text":"Linear in the length of the JSON pointer.","title":"Complexity"},{"location":"api/json_pointer/parent_pointer/#examples","text":"Example The example shows the result of parent_pointer for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); // call parent_pointer() std :: cout << std :: boolalpha << \"parent of \\\" \" << ptr1 << \" \\\" is \\\" \" << ptr1 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr2 << \" \\\" is \\\" \" << ptr2 . parent_pointer () << \" \\\"\\n \" << \"parent of \\\" \" << ptr3 << \" \\\" is \\\" \" << ptr3 . parent_pointer () << \" \\\" \" << std :: endl ; } Output: pare nt o f \"\" is \"\" pare nt o f \"/foo\" is \"\" pare nt o f \"/foo/0\" is \"/foo\"","title":"Examples"},{"location":"api/json_pointer/parent_pointer/#version-history","text":"Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/pop_back/","text":"nlohmann::json_pointer:: pop_back \u00b6 void pop_back (); Remove last reference token. Exceptions \u00b6 Throws out_of_range.405 if JSON pointer has no parent. Complexity \u00b6 Constant. Examples \u00b6 Example The example shows the usage of pop_back . #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ( \"/foo/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call pop_back() ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"/foo/bar/baz\" \"/foo/bar\" \"/foo\" \"\" Version history \u00b6 Added in version 3.6.0.","title":"pop_back"},{"location":"api/json_pointer/pop_back/#nlohmannjson_pointerpop_back","text":"void pop_back (); Remove last reference token.","title":"nlohmann::json_pointer::pop_back"},{"location":"api/json_pointer/pop_back/#exceptions","text":"Throws out_of_range.405 if JSON pointer has no parent.","title":"Exceptions"},{"location":"api/json_pointer/pop_back/#complexity","text":"Constant.","title":"Complexity"},{"location":"api/json_pointer/pop_back/#examples","text":"Example The example shows the usage of pop_back . #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ( \"/foo/bar/baz\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call pop_back() ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . pop_back (); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"/foo/bar/baz\" \"/foo/bar\" \"/foo\" \"\"","title":"Examples"},{"location":"api/json_pointer/pop_back/#version-history","text":"Added in version 3.6.0.","title":"Version history"},{"location":"api/json_pointer/push_back/","text":"nlohmann::json_pointer:: push_back \u00b6 void push_back ( const string_t & token ); void push_back ( string_t && token ); Append an unescaped token at the end of the reference pointer. Parameters \u00b6 token (in) token to add Complexity \u00b6 Amortized constant. Examples \u00b6 Example The example shows the result of push_back for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call push_back() ptr . push_back ( \"foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"0\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"bar\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"\" \"/foo\" \"/foo/0\" \"/foo/0/bar\" Version history \u00b6 Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.","title":"push_back"},{"location":"api/json_pointer/push_back/#nlohmannjson_pointerpush_back","text":"void push_back ( const string_t & token ); void push_back ( string_t && token ); Append an unescaped token at the end of the reference pointer.","title":"nlohmann::json_pointer::push_back"},{"location":"api/json_pointer/push_back/#parameters","text":"token (in) token to add","title":"Parameters"},{"location":"api/json_pointer/push_back/#complexity","text":"Amortized constant.","title":"Complexity"},{"location":"api/json_pointer/push_back/#examples","text":"Example The example shows the result of push_back for different JSON Pointers. #include #include using json = nlohmann :: json ; int main () { // create empty JSON Pointer json :: json_pointer ptr ; std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; // call push_back() ptr . push_back ( \"foo\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"0\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; ptr . push_back ( \"bar\" ); std :: cout << \" \\\" \" << ptr << \" \\\"\\n \" ; } Output: \"\" \"/foo\" \"/foo/0\" \"/foo/0/bar\"","title":"Examples"},{"location":"api/json_pointer/push_back/#version-history","text":"Added in version 3.6.0. Changed type of token to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/string_t/","text":"nlohmann::json_pointer:: string_t \u00b6 using string_t = RefStringType ; The string type used for the reference tokens making up the JSON pointer. See basic_json::string_t for more information. Examples \u00b6 Example The example shows the type string_t and its relation to basic_json::string_t . #include #include using json = nlohmann :: json ; int main () { json :: json_pointer :: string_t s = \"This is a string.\" ; std :: cout << s << std :: endl ; std :: cout << std :: boolalpha << std :: is_same < json :: json_pointer :: string_t , json :: string_t >:: value << std :: endl ; } Output: This is a s tr i n g. true Version history \u00b6 Added in version 3.11.0.","title":"string_t"},{"location":"api/json_pointer/string_t/#nlohmannjson_pointerstring_t","text":"using string_t = RefStringType ; The string type used for the reference tokens making up the JSON pointer. See basic_json::string_t for more information.","title":"nlohmann::json_pointer::string_t"},{"location":"api/json_pointer/string_t/#examples","text":"Example The example shows the type string_t and its relation to basic_json::string_t . #include #include using json = nlohmann :: json ; int main () { json :: json_pointer :: string_t s = \"This is a string.\" ; std :: cout << s << std :: endl ; std :: cout << std :: boolalpha << std :: is_same < json :: json_pointer :: string_t , json :: string_t >:: value << std :: endl ; } Output: This is a s tr i n g. true","title":"Examples"},{"location":"api/json_pointer/string_t/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/json_pointer/to_string/","text":"nlohmann::json_pointer:: to_string \u00b6 string_t to_string () const ; Return a string representation of the JSON pointer. Return value \u00b6 A string representation of the JSON pointer Notes \u00b6 For each JSON pointer ptr , it holds: ptr == json_pointer ( ptr . to_string ()); Examples \u00b6 Example The example shows the result of to_string . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); json :: json_pointer ptr4 ( \"/\" ); json :: json_pointer ptr5 ( \"/a~1b\" ); json :: json_pointer ptr6 ( \"/c%d\" ); json :: json_pointer ptr7 ( \"/e^f\" ); json :: json_pointer ptr8 ( \"/g|h\" ); json :: json_pointer ptr9 ( \"/i \\\\ j\" ); json :: json_pointer ptr10 ( \"/k \\\" l\" ); json :: json_pointer ptr11 ( \"/ \" ); json :: json_pointer ptr12 ( \"/m~0n\" ); std :: cout << \" \\\" \" << ptr1 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr2 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr3 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr4 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr5 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr6 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr7 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr8 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr9 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr10 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr11 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr12 . to_string () << \" \\\" \" << std :: endl ; } Output: \"\" \"/foo\" \"/foo/0\" \"/\" \"/a~1b\" \"/c%d\" \"/e^f\" \"/g|h\" \"/i\\j\" \"/k\" l \" \" / \" \" /m~ 0 n \" Version history \u00b6 Since version 2.0.0. Changed return type to string_t in version 3.11.0.","title":"to_string"},{"location":"api/json_pointer/to_string/#nlohmannjson_pointerto_string","text":"string_t to_string () const ; Return a string representation of the JSON pointer.","title":"nlohmann::json_pointer::to_string"},{"location":"api/json_pointer/to_string/#return-value","text":"A string representation of the JSON pointer","title":"Return value"},{"location":"api/json_pointer/to_string/#notes","text":"For each JSON pointer ptr , it holds: ptr == json_pointer ( ptr . to_string ());","title":"Notes"},{"location":"api/json_pointer/to_string/#examples","text":"Example The example shows the result of to_string . #include #include using json = nlohmann :: json ; int main () { // different JSON Pointers json :: json_pointer ptr1 ( \"\" ); json :: json_pointer ptr2 ( \"/foo\" ); json :: json_pointer ptr3 ( \"/foo/0\" ); json :: json_pointer ptr4 ( \"/\" ); json :: json_pointer ptr5 ( \"/a~1b\" ); json :: json_pointer ptr6 ( \"/c%d\" ); json :: json_pointer ptr7 ( \"/e^f\" ); json :: json_pointer ptr8 ( \"/g|h\" ); json :: json_pointer ptr9 ( \"/i \\\\ j\" ); json :: json_pointer ptr10 ( \"/k \\\" l\" ); json :: json_pointer ptr11 ( \"/ \" ); json :: json_pointer ptr12 ( \"/m~0n\" ); std :: cout << \" \\\" \" << ptr1 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr2 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr3 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr4 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr5 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr6 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr7 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr8 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr9 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr10 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr11 . to_string () << \" \\\"\\n \" << \" \\\" \" << ptr12 . to_string () << \" \\\" \" << std :: endl ; } Output: \"\" \"/foo\" \"/foo/0\" \"/\" \"/a~1b\" \"/c%d\" \"/e^f\" \"/g|h\" \"/i\\j\" \"/k\" l \" \" / \" \" /m~ 0 n \"","title":"Examples"},{"location":"api/json_pointer/to_string/#version-history","text":"Since version 2.0.0. Changed return type to string_t in version 3.11.0.","title":"Version history"},{"location":"api/json_sax/","text":"nlohmann:: json_sax \u00b6 template < typename BasicJsonType > struct json_sax ; 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. Template parameters \u00b6 BasicJsonType a specialization of basic_json Member types \u00b6 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) string_t - BasicJsonType 's type for strings binary_t - BasicJsonType 's type for binary arrays Member functions \u00b6 binary ( virtual ) - a binary value was read boolean ( virtual ) - a boolean value was read end_array ( virtual ) - the end of an array was read end_object ( virtual ) - the end of an object was read key ( virtual ) - an object key was read null ( virtual ) - a null value was read number_float ( virtual ) - a floating-point number was read number_integer ( virtual ) - an integer number was read number_unsigned ( virtual ) - an unsigned integer number was read parse_error ( virtual ) - a parse error occurred start_array ( virtual ) - the beginning of an array was read start_object ( virtual ) - the beginning of an object was read string ( virtual ) - a string value was read Version history \u00b6 Added in version 3.2.0. Support for binary values ( binary_t , binary ) added in version 3.8.0.","title":"Overview"},{"location":"api/json_sax/#nlohmannjson_sax","text":"template < typename BasicJsonType > struct json_sax ; 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.","title":"nlohmann::json_sax"},{"location":"api/json_sax/#template-parameters","text":"BasicJsonType a specialization of basic_json","title":"Template parameters"},{"location":"api/json_sax/#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) string_t - BasicJsonType 's type for strings binary_t - BasicJsonType 's type for binary arrays","title":"Member types"},{"location":"api/json_sax/#member-functions","text":"binary ( virtual ) - a binary value was read boolean ( virtual ) - a boolean value was read end_array ( virtual ) - the end of an array was read end_object ( virtual ) - the end of an object was read key ( virtual ) - an object key was read null ( virtual ) - a null value was read number_float ( virtual ) - a floating-point number was read number_integer ( virtual ) - an integer number was read number_unsigned ( virtual ) - an unsigned integer number was read parse_error ( virtual ) - a parse error occurred start_array ( virtual ) - the beginning of an array was read start_object ( virtual ) - the beginning of an object was read string ( virtual ) - a string value was read","title":"Member functions"},{"location":"api/json_sax/#version-history","text":"Added in version 3.2.0. Support for binary values ( binary_t , binary ) added in version 3.8.0.","title":"Version history"},{"location":"api/json_sax/binary/","text":"nlohmann::json_sax:: binary \u00b6 virtual bool binary ( binary_t & val ) = 0 ; A binary value was read. Parameters \u00b6 val (in) binary value Return value \u00b6 Whether parsing should proceed. Notes \u00b6 It is safe to move the passed binary value. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true Version history \u00b6 Added in version 3.8.0.","title":"binary"},{"location":"api/json_sax/binary/#nlohmannjson_saxbinary","text":"virtual bool binary ( binary_t & val ) = 0 ; A binary value was read.","title":"nlohmann::json_sax::binary"},{"location":"api/json_sax/binary/#parameters","text":"val (in) binary value","title":"Parameters"},{"location":"api/json_sax/binary/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/binary/#notes","text":"It is safe to move the passed binary value.","title":"Notes"},{"location":"api/json_sax/binary/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // CBOR byte string std :: vector < std :: uint8_t > vec = {{ 0x44 , 0xcA , 0xfe , 0xba , 0xbe }}; // create a SAX event consumer object sax_event_consumer sec ; // parse CBOR bool result = json :: sax_parse ( vec , & sec , json :: input_format_t :: cbor ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: bi nar y(val= [ ... ] ) resul t : true","title":"Examples"},{"location":"api/json_sax/binary/#version-history","text":"Added in version 3.8.0.","title":"Version history"},{"location":"api/json_sax/boolean/","text":"nlohmann::json_sax:: boolean \u00b6 virtual bool boolean ( bool val ) = 0 ; A boolean value was read. Parameters \u00b6 val (in) boolean value Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"boolean"},{"location":"api/json_sax/boolean/#nlohmannjson_saxboolean","text":"virtual bool boolean ( bool val ) = 0 ; A boolean value was read.","title":"nlohmann::json_sax::boolean"},{"location":"api/json_sax/boolean/#parameters","text":"val (in) boolean value","title":"Parameters"},{"location":"api/json_sax/boolean/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/boolean/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/boolean/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/end_array/","text":"nlohmann::json_sax:: end_array \u00b6 virtual bool end_array () = 0 ; The end of an array was read. Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"end_array"},{"location":"api/json_sax/end_array/#nlohmannjson_saxend_array","text":"virtual bool end_array () = 0 ; The end of an array was read.","title":"nlohmann::json_sax::end_array"},{"location":"api/json_sax/end_array/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/end_array/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/end_array/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/end_object/","text":"nlohmann::json_sax:: end_object \u00b6 virtual bool end_object () = 0 ; The end of an object was read. Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"end_object"},{"location":"api/json_sax/end_object/#nlohmannjson_saxend_object","text":"virtual bool end_object () = 0 ; The end of an object was read.","title":"nlohmann::json_sax::end_object"},{"location":"api/json_sax/end_object/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/end_object/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/end_object/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/key/","text":"nlohmann::json_sax:: key \u00b6 virtual bool key ( string_t & val ) = 0 ; An object key was read. Parameters \u00b6 val (in) object key Return value \u00b6 Whether parsing should proceed. Notes \u00b6 It is safe to move the passed object key value. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"key"},{"location":"api/json_sax/key/#nlohmannjson_saxkey","text":"virtual bool key ( string_t & val ) = 0 ; An object key was read.","title":"nlohmann::json_sax::key"},{"location":"api/json_sax/key/#parameters","text":"val (in) object key","title":"Parameters"},{"location":"api/json_sax/key/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/key/#notes","text":"It is safe to move the passed object key value.","title":"Notes"},{"location":"api/json_sax/key/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/key/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/null/","text":"nlohmann::json_sax:: null \u00b6 virtual bool null () = 0 ; A null value was read. Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"null"},{"location":"api/json_sax/null/#nlohmannjson_saxnull","text":"virtual bool null () = 0 ; A null value was read.","title":"nlohmann::json_sax::null"},{"location":"api/json_sax/null/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/null/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/null/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/number_float/","text":"nlohmann::json_sax:: number_float \u00b6 virtual bool number_float ( number_float_t val , const string_t & s ) = 0 ; A floating-point number was read. Parameters \u00b6 val (in) floating-point value s (in) string representation of the original input Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"number_float"},{"location":"api/json_sax/number_float/#nlohmannjson_saxnumber_float","text":"virtual bool number_float ( number_float_t val , const string_t & s ) = 0 ; A floating-point number was read.","title":"nlohmann::json_sax::number_float"},{"location":"api/json_sax/number_float/#parameters","text":"val (in) floating-point value s (in) string representation of the original input","title":"Parameters"},{"location":"api/json_sax/number_float/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/number_float/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/number_float/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/number_integer/","text":"nlohmann::json_sax:: number_integer \u00b6 virtual bool number_integer ( number_integer_t val ) = 0 ; An integer number was read. Parameters \u00b6 val (in) integer value Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"number_integer"},{"location":"api/json_sax/number_integer/#nlohmannjson_saxnumber_integer","text":"virtual bool number_integer ( number_integer_t val ) = 0 ; An integer number was read.","title":"nlohmann::json_sax::number_integer"},{"location":"api/json_sax/number_integer/#parameters","text":"val (in) integer value","title":"Parameters"},{"location":"api/json_sax/number_integer/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/number_integer/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/number_integer/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/number_unsigned/","text":"nlohmann::json_sax:: number_unsigned \u00b6 virtual bool number_unsigned ( number_unsigned_t val ) = 0 ; An unsigned integer number was read. Parameters \u00b6 val (in) unsigned integer value Return value \u00b6 Whether parsing should proceed. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"number_unsigned"},{"location":"api/json_sax/number_unsigned/#nlohmannjson_saxnumber_unsigned","text":"virtual bool number_unsigned ( number_unsigned_t val ) = 0 ; An unsigned integer number was read.","title":"nlohmann::json_sax::number_unsigned"},{"location":"api/json_sax/number_unsigned/#parameters","text":"val (in) unsigned integer value","title":"Parameters"},{"location":"api/json_sax/number_unsigned/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/number_unsigned/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/number_unsigned/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/parse_error/","text":"nlohmann::json_sax:: parse_error \u00b6 virtual bool parse_error ( std :: size_t position , const std :: string & last_token , const detail :: exception & ex ) = 0 ; A parse error occurred. Parameters \u00b6 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 Return value \u00b6 Whether parsing should proceed ( must return false ). Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"parse_error"},{"location":"api/json_sax/parse_error/#nlohmannjson_saxparse_error","text":"virtual bool parse_error ( std :: size_t position , const std :: string & last_token , const detail :: exception & ex ) = 0 ; A parse error occurred.","title":"nlohmann::json_sax::parse_error"},{"location":"api/json_sax/parse_error/#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","title":"Parameters"},{"location":"api/json_sax/parse_error/#return-value","text":"Whether parsing should proceed ( must return false ).","title":"Return value"},{"location":"api/json_sax/parse_error/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/parse_error/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/start_array/","text":"nlohmann::json_sax:: start_array \u00b6 virtual bool start_array ( std :: size_t elements ) = 0 ; The beginning of an array was read. Parameters \u00b6 elements (in) number of object elements or -1 if unknown Return value \u00b6 Whether parsing should proceed. Notes \u00b6 Binary formats may report the number of elements. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"start_array"},{"location":"api/json_sax/start_array/#nlohmannjson_saxstart_array","text":"virtual bool start_array ( std :: size_t elements ) = 0 ; The beginning of an array was read.","title":"nlohmann::json_sax::start_array"},{"location":"api/json_sax/start_array/#parameters","text":"elements (in) number of object elements or -1 if unknown","title":"Parameters"},{"location":"api/json_sax/start_array/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/start_array/#notes","text":"Binary formats may report the number of elements.","title":"Notes"},{"location":"api/json_sax/start_array/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/start_array/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/start_object/","text":"nlohmann::json_sax:: start_object \u00b6 virtual bool start_object ( std :: size_t elements ) = 0 ; The beginning of an object was read. Parameters \u00b6 elements (in) number of object elements or -1 if unknown Return value \u00b6 Whether parsing should proceed. Notes \u00b6 Binary formats may report the number of elements. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"start_object"},{"location":"api/json_sax/start_object/#nlohmannjson_saxstart_object","text":"virtual bool start_object ( std :: size_t elements ) = 0 ; The beginning of an object was read.","title":"nlohmann::json_sax::start_object"},{"location":"api/json_sax/start_object/#parameters","text":"elements (in) number of object elements or -1 if unknown","title":"Parameters"},{"location":"api/json_sax/start_object/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/start_object/#notes","text":"Binary formats may report the number of elements.","title":"Notes"},{"location":"api/json_sax/start_object/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/start_object/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/json_sax/string/","text":"nlohmann::json_sax:: string \u00b6 virtual bool string ( string_t & val ) = 0 ; A string value was read. Parameters \u00b6 val (in) string value Return value \u00b6 Whether parsing should proceed. Notes \u00b6 It is safe to move the passed string value. Examples \u00b6 Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false Version history \u00b6 Added in version 3.2.0.","title":"string"},{"location":"api/json_sax/string/#nlohmannjson_saxstring","text":"virtual bool string ( string_t & val ) = 0 ; A string value was read.","title":"nlohmann::json_sax::string"},{"location":"api/json_sax/string/#parameters","text":"val (in) string value","title":"Parameters"},{"location":"api/json_sax/string/#return-value","text":"Whether parsing should proceed.","title":"Return value"},{"location":"api/json_sax/string/#notes","text":"It is safe to move the passed string value.","title":"Notes"},{"location":"api/json_sax/string/#examples","text":"Example The example below shows how the SAX interface is used. #include #include #include #include using json = nlohmann :: json ; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json :: json_sax_t { public : std :: vector < std :: string > events ; bool null () override { events . push_back ( \"null()\" ); return true ; } bool boolean ( bool val ) override { events . push_back ( \"boolean(val=\" + std :: string ( val ? \"true\" : \"false\" ) + \")\" ); return true ; } bool number_integer ( number_integer_t val ) override { events . push_back ( \"number_integer(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_unsigned ( number_unsigned_t val ) override { events . push_back ( \"number_unsigned(val=\" + std :: to_string ( val ) + \")\" ); return true ; } bool number_float ( number_float_t val , const string_t & s ) override { events . push_back ( \"number_float(val=\" + std :: to_string ( val ) + \", s=\" + s + \")\" ); return true ; } bool string ( string_t & val ) override { events . push_back ( \"string(val=\" + val + \")\" ); return true ; } bool start_object ( std :: size_t elements ) override { events . push_back ( \"start_object(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_object () override { events . push_back ( \"end_object()\" ); return true ; } bool start_array ( std :: size_t elements ) override { events . push_back ( \"start_array(elements=\" + std :: to_string ( elements ) + \")\" ); return true ; } bool end_array () override { events . push_back ( \"end_array()\" ); return true ; } bool key ( string_t & val ) override { events . push_back ( \"key(val=\" + val + \")\" ); return true ; } bool binary ( json :: binary_t & val ) override { events . push_back ( \"binary(val=[...])\" ); return true ; } bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) override { events . push_back ( \"parse_error(position=\" + std :: to_string ( position ) + \", last_token=\" + last_token + \", \\n ex=\" + std :: string ( ex . what ()) + \")\" ); return false ; } }; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, -38793], \"DeletionDate\": null, \"Distance\": 12.723374634 } }] ) \" ; // create a SAX event consumer object sax_event_consumer sec ; // parse JSON bool result = json :: sax_parse ( text , & sec ); // output the recorded events for ( auto & event : sec . events ) { std :: cout << event << \" \\n \" ; } // output the result of sax_parse std :: cout << \" \\n result: \" << std :: boolalpha << result << std :: endl ; } Output: s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Image) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 800 ) key(val=Heigh t ) nu mber_u ns ig ne d(val= 600 ) key(val=Ti tle ) s tr i n g(val=View fr om 15 t h Floor) key(val=Thumb na il) s tart _objec t (eleme nts = 18446744073709551615 ) key(val=Url) s tr i n g(val=h tt p : //www.example.com/image/481989943) key(val=Heigh t ) nu mber_u ns ig ne d(val= 125 ) key(val=Wid t h) nu mber_u ns ig ne d(val= 100 ) e n d_objec t () key(val=A n ima te d) boolea n (val= false ) key(val=IDs) s tart _array(eleme nts = 18446744073709551615 ) nu mber_u ns ig ne d(val= 116 ) nu mber_u ns ig ne d(val= 943 ) nu mber_u ns ig ne d(val= 234 ) nu mber_i nte ger(val= -38793 ) e n d_array() key(val=Dele t io n Da te ) null () key(val=Dis tan ce) nu mber_ fl oa t (val= 12.723375 , s= 12.723374634 ) e n d_objec t () e n d_objec t () parse_error(posi t io n = 460 , las t _ t oke n = 12.723374634 } }], ex= [ jso n .excep t io n .parse_error. 101 ] parse error a t li ne 17 , colum n 6 : sy nta x error while parsi n g value - u ne xpec te d ' ] '; expec te d e n d o f i n pu t ) resul t : false","title":"Examples"},{"location":"api/json_sax/string/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/macros/","text":"Macros \u00b6 Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page . Runtime assertions \u00b6 JSON_ASSERT(x) - control behavior of runtime assertions Exceptions \u00b6 JSON_CATCH_USER(exception) JSON_THROW_USER(exception) JSON_TRY_USER - control exceptions JSON_DIAGNOSTICS - control extended diagnostics JSON_NOEXCEPTION - switch off exceptions Language support \u00b6 JSON_HAS_CPP_11 JSON_HAS_CPP_14 JSON_HAS_CPP_17 JSON_HAS_CPP_20 - set supported C++ standard JSON_HAS_FILESYSTEM JSON_HAS_EXPERIMENTAL_FILESYSTEM - control std::filesystem support JSON_HAS_RANGES - control std::ranges support JSON_HAS_THREE_WAY_COMPARISON - control 3-way comparison support JSON_NO_IO - switch off functions relying on certain C++ I/O headers JSON_SKIP_UNSUPPORTED_COMPILER_CHECK - do not warn about unsupported compilers JSON_USE_GLOBAL_UDLS - place user-defined string literals (UDLs) into the global namespace Library version \u00b6 JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check NLOHMANN_JSON_VERSION_MAJOR NLOHMANN_JSON_VERSION_MINOR NLOHMANN_JSON_VERSION_PATCH - library version information Library namespace \u00b6 NLOHMANN_JSON_NAMESPACE - full name of the nlohmann namespace NLOHMANN_JSON_NAMESPACE_BEGIN NLOHMANN_JSON_NAMESPACE_END - open and close the library namespace NLOHMANN_JSON_NAMESPACE_NO_VERSION - disable the version component of the inline namespace Type conversions \u00b6 JSON_DISABLE_ENUM_SERIALIZATION - switch off default serialization/deserialization functions for enums JSON_USE_IMPLICIT_CONVERSIONS - control implicit conversions Comparison behavior \u00b6 JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - control comparison of discarded values Serialization/deserialization macros \u00b6 NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types with access to private variables NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types without access to private variables NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) - serialization/deserialization of enum types","title":"Overview"},{"location":"api/macros/#macros","text":"Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the macro overview page .","title":"Macros"},{"location":"api/macros/#runtime-assertions","text":"JSON_ASSERT(x) - control behavior of runtime assertions","title":"Runtime assertions"},{"location":"api/macros/#exceptions","text":"JSON_CATCH_USER(exception) JSON_THROW_USER(exception) JSON_TRY_USER - control exceptions JSON_DIAGNOSTICS - control extended diagnostics JSON_NOEXCEPTION - switch off exceptions","title":"Exceptions"},{"location":"api/macros/#language-support","text":"JSON_HAS_CPP_11 JSON_HAS_CPP_14 JSON_HAS_CPP_17 JSON_HAS_CPP_20 - set supported C++ standard JSON_HAS_FILESYSTEM JSON_HAS_EXPERIMENTAL_FILESYSTEM - control std::filesystem support JSON_HAS_RANGES - control std::ranges support JSON_HAS_THREE_WAY_COMPARISON - control 3-way comparison support JSON_NO_IO - switch off functions relying on certain C++ I/O headers JSON_SKIP_UNSUPPORTED_COMPILER_CHECK - do not warn about unsupported compilers JSON_USE_GLOBAL_UDLS - place user-defined string literals (UDLs) into the global namespace","title":"Language support"},{"location":"api/macros/#library-version","text":"JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check NLOHMANN_JSON_VERSION_MAJOR NLOHMANN_JSON_VERSION_MINOR NLOHMANN_JSON_VERSION_PATCH - library version information","title":"Library version"},{"location":"api/macros/#library-namespace","text":"NLOHMANN_JSON_NAMESPACE - full name of the nlohmann namespace NLOHMANN_JSON_NAMESPACE_BEGIN NLOHMANN_JSON_NAMESPACE_END - open and close the library namespace NLOHMANN_JSON_NAMESPACE_NO_VERSION - disable the version component of the inline namespace","title":"Library namespace"},{"location":"api/macros/#type-conversions","text":"JSON_DISABLE_ENUM_SERIALIZATION - switch off default serialization/deserialization functions for enums JSON_USE_IMPLICIT_CONVERSIONS - control implicit conversions","title":"Type conversions"},{"location":"api/macros/#comparison-behavior","text":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - control comparison of discarded values","title":"Comparison behavior"},{"location":"api/macros/#serializationdeserialization-macros","text":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types with access to private variables NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) - serialization/deserialization of types without access to private variables NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) - serialization/deserialization of enum types","title":"Serialization/deserialization macros"},{"location":"api/macros/json_assert/","text":"JSON_ASSERT \u00b6 #define JSON_ASSERT(x) /* value */ This macro controls which code is executed for runtime assertions of the library. Parameters \u00b6 x (in) expression of scalar type Default definition \u00b6 The default value is assert ( x ) . #define JSON_ASSERT(x) assert(x) Therefore, assertions can be switched off by defining NDEBUG . Notes \u00b6 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. The macro is undefined outside the library. Examples \u00b6 Example 1: default behavior The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. Example 2: user-defined behavior The assertion reporting can be changed by defining JSON_ASSERT(x) differently. #include #include #define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();} #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: assertion error in operator[] Version history \u00b6 Added in version 3.9.0.","title":"JSON_ASSERT"},{"location":"api/macros/json_assert/#json_assert","text":"#define JSON_ASSERT(x) /* value */ This macro controls which code is executed for runtime assertions of the library.","title":"JSON_ASSERT"},{"location":"api/macros/json_assert/#parameters","text":"x (in) expression of scalar type","title":"Parameters"},{"location":"api/macros/json_assert/#default-definition","text":"The default value is assert ( x ) . #define JSON_ASSERT(x) assert(x) Therefore, assertions can be switched off by defining NDEBUG .","title":"Default definition"},{"location":"api/macros/json_assert/#notes","text":"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. The macro is undefined outside the library.","title":"Notes"},{"location":"api/macros/json_assert/#examples","text":"Example 1: default behavior The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. Example 2: user-defined behavior The assertion reporting can be changed by defining JSON_ASSERT(x) differently. #include #include #define JSON_ASSERT(x) if(!(x)){fprintf(stderr, \"assertion error in %s\\n\", __FUNCTION__); std::abort();} #include using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: assertion error in operator[]","title":"Examples"},{"location":"api/macros/json_assert/#version-history","text":"Added in version 3.9.0.","title":"Version history"},{"location":"api/macros/json_diagnostics/","text":"JSON_DIAGNOSTICS \u00b6 #define JSON_DIAGNOSTICS /* value */ 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. Default definition \u00b6 The default value is 0 (extended diagnostics are switched off). #define JSON_DIAGNOSTICS 0 When the macro is not defined, the library will define it to its default value. Notes \u00b6 ABI compatibility As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names. This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior. Where possible, it is still recommended that all code define this the same way for maximum interoperability. CMake option Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which defines JSON_DIAGNOSTICS accordingly. Examples \u00b6 Example 1: default behavior #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. Example 2: extended diagnostic messages #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type. Version history \u00b6 Added in version 3.10.0. As of version 3.11.0 the definition is allowed to vary between translation units.","title":"JSON_DIAGNOSTICS"},{"location":"api/macros/json_diagnostics/#json_diagnostics","text":"#define JSON_DIAGNOSTICS /* value */ 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.","title":"JSON_DIAGNOSTICS"},{"location":"api/macros/json_diagnostics/#default-definition","text":"The default value is 0 (extended diagnostics are switched off). #define JSON_DIAGNOSTICS 0 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_diagnostics/#notes","text":"ABI compatibility As of version 3.11.0, this macro is no longer required to be defined consistently throughout a codebase to avoid One Definition Rule (ODR) violations, as the value of this macro is encoded in the namespace, resulting in distinct symbol names. This allows different parts of a codebase to use different versions or configurations of this library without causing improper behavior. Where possible, it is still recommended that all code define this the same way for maximum interoperability. CMake option Diagnostic messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which defines JSON_DIAGNOSTICS accordingly.","title":"Notes"},{"location":"api/macros/json_diagnostics/#examples","text":"Example 1: default behavior #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. Example 2: extended diagnostic messages #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.","title":"Examples"},{"location":"api/macros/json_diagnostics/#version-history","text":"Added in version 3.10.0. As of version 3.11.0 the definition is allowed to vary between translation units.","title":"Version history"},{"location":"api/macros/json_disable_enum_serialization/","text":"JSON_DISABLE_ENUM_SERIALIZATION \u00b6 #define JSON_DISABLE_ENUM_SERIALIZATION /* value */ When defined to 1 , default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details). Parsing or serializing an enum will result in a compiler error. This works for both unscoped and scoped enums. Default definition \u00b6 The default value is 0 . #define JSON_DISABLE_ENUM_SERIALIZATION 0 Notes \u00b6 CMake option Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization ( OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly. Examples \u00b6 Example 1: Disabled behavior The code below forces the library not to create default serialization/deserialization functions from_json and to_json , meaning the code below does not compile. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; int main () { // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not const json j = Choice :: first ; // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not Choice ch = j . template get < Choice > (); } 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 #include using json = nlohmann :: json ; enum class Choice { first , second , }; NLOHMANN_JSON_SERIALIZE_ENUM ( Choice , { { Choice :: first , \"first\" }, { Choice :: second , \"second\" }, }) int main () { // uses user-defined to_json function defined by macro const json j = Choice :: first ; // uses user-defined from_json function defined by macro Choice ch = j . template get < Choice > (); } Example 3: User-defined serialization/deserialization functions The code below forces the library not to create default serialization/deserialization functions from_json and to_json , but uses user-defined functions to parse and serialize the enum. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; void from_json ( const json & j , Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } void to_json ( json & j , const Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } int main () { // uses user-defined to_json function const json j = Choice :: first ; // uses user-defined from_json function Choice ch = j . template get < Choice > (); } See also \u00b6 NLOHMANN_JSON_SERIALIZE_ENUM Version history \u00b6 Added in version 3.11.0.","title":"JSON_DISABLE_ENUM_SERIALIZATION"},{"location":"api/macros/json_disable_enum_serialization/#json_disable_enum_serialization","text":"#define JSON_DISABLE_ENUM_SERIALIZATION /* value */ When defined to 1 , default serialization and deserialization functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM (see arbitrary type conversions for more details). Parsing or serializing an enum will result in a compiler error. This works for both unscoped and scoped enums.","title":"JSON_DISABLE_ENUM_SERIALIZATION"},{"location":"api/macros/json_disable_enum_serialization/#default-definition","text":"The default value is 0 . #define JSON_DISABLE_ENUM_SERIALIZATION 0","title":"Default definition"},{"location":"api/macros/json_disable_enum_serialization/#notes","text":"CMake option Enum serialization can also be controlled with the CMake option JSON_DisableEnumSerialization ( OFF by default) which defines JSON_DISABLE_ENUM_SERIALIZATION accordingly.","title":"Notes"},{"location":"api/macros/json_disable_enum_serialization/#examples","text":"Example 1: Disabled behavior The code below forces the library not to create default serialization/deserialization functions from_json and to_json , meaning the code below does not compile. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; int main () { // normally invokes to_json serialization function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not const json j = Choice :: first ; // normally invokes from_json parse function but with JSON_DISABLE_ENUM_SERIALIZATION defined, it does not Choice ch = j . template get < Choice > (); } 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 #include using json = nlohmann :: json ; enum class Choice { first , second , }; NLOHMANN_JSON_SERIALIZE_ENUM ( Choice , { { Choice :: first , \"first\" }, { Choice :: second , \"second\" }, }) int main () { // uses user-defined to_json function defined by macro const json j = Choice :: first ; // uses user-defined from_json function defined by macro Choice ch = j . template get < Choice > (); } Example 3: User-defined serialization/deserialization functions The code below forces the library not to create default serialization/deserialization functions from_json and to_json , but uses user-defined functions to parse and serialize the enum. #define JSON_DISABLE_ENUM_SERIALIZATION 1 #include using json = nlohmann :: json ; enum class Choice { first , second , }; void from_json ( const json & j , Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } void to_json ( json & j , const Choice & ch ) { auto value = j . template get < std :: string > (); if ( value == \"first\" ) { ch = Choice :: first ; } else if ( value == \"second\" ) { ch = Choice :: second ; } } int main () { // uses user-defined to_json function const json j = Choice :: first ; // uses user-defined from_json function Choice ch = j . template get < Choice > (); }","title":"Examples"},{"location":"api/macros/json_disable_enum_serialization/#see-also","text":"NLOHMANN_JSON_SERIALIZE_ENUM","title":"See also"},{"location":"api/macros/json_disable_enum_serialization/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_has_cpp_11/","text":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20 \u00b6 #define JSON_HAS_CPP_11 #define JSON_HAS_CPP_14 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_20 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. Default definition \u00b6 The default value is detected based on preprocessor macros such as __cplusplus , _HAS_CXX17 , or _MSVC_LANG . Notes \u00b6 JSON_HAS_CPP_11 is always defined. All macros are undefined outside the library. Examples \u00b6 Example The code below forces the library to use the C++14 standard: #define JSON_HAS_CPP_14 1 #include ... Version history \u00b6 Added in version 3.10.5.","title":"JSON_HAS_CPP_20"},{"location":"api/macros/json_has_cpp_11/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","text":"#define JSON_HAS_CPP_11 #define JSON_HAS_CPP_14 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_20 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.","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20"},{"location":"api/macros/json_has_cpp_11/#default-definition","text":"The default value is detected based on preprocessor macros such as __cplusplus , _HAS_CXX17 , or _MSVC_LANG .","title":"Default definition"},{"location":"api/macros/json_has_cpp_11/#notes","text":"JSON_HAS_CPP_11 is always defined. All macros are undefined outside the library.","title":"Notes"},{"location":"api/macros/json_has_cpp_11/#examples","text":"Example The code below forces the library to use the C++14 standard: #define JSON_HAS_CPP_14 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_cpp_11/#version-history","text":"Added in version 3.10.5.","title":"Version history"},{"location":"api/macros/json_has_filesystem/","text":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM \u00b6 #define JSON_HAS_FILESYSTEM /* value */ #define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */ 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 / std::filesystem ( JSON_HAS_FILESYSTEM ) or / 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 . Default definition \u00b6 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 > ) . Notes \u00b6 Note that older compilers or older versions of libstd++ also require the library stdc++fs to be linked to for filesystem support. Both macros are undefined outside the library. Examples \u00b6 Example The code below forces the library to use the header . #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #include ... Version history \u00b6 Added in version 3.10.5.","title":"JSON_HAS_FILESYSTEM"},{"location":"api/macros/json_has_filesystem/#json_has_filesystem-json_has_experimental_filesystem","text":"#define JSON_HAS_FILESYSTEM /* value */ #define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */ 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 / std::filesystem ( JSON_HAS_FILESYSTEM ) or / 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 .","title":"JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM"},{"location":"api/macros/json_has_filesystem/#default-definition","text":"The default value is detected based on the preprocessor macros __cpp_lib_filesystem , __cpp_lib_experimental_filesystem , __has_include ( < filesystem > ) , or __has_include ( < experimental / filesystem > ) .","title":"Default definition"},{"location":"api/macros/json_has_filesystem/#notes","text":"Note that older compilers or older versions of libstd++ also require the library stdc++fs to be linked to for filesystem support. Both macros are undefined outside the library.","title":"Notes"},{"location":"api/macros/json_has_filesystem/#examples","text":"Example The code below forces the library to use the header . #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_filesystem/#version-history","text":"Added in version 3.10.5.","title":"Version history"},{"location":"api/macros/json_has_ranges/","text":"JSON_HAS_RANGES \u00b6 #define JSON_HAS_RANGES /* value */ 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. Default definition \u00b6 The default value is detected based on the preprocessor macro __cpp_lib_ranges . When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The code below forces the library to enable support for ranges: #define JSON_HAS_RANGES 1 #include ... Version history \u00b6 Added in version 3.11.0.","title":"JSON_HAS_RANGES"},{"location":"api/macros/json_has_ranges/#json_has_ranges","text":"#define JSON_HAS_RANGES /* value */ 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.","title":"JSON_HAS_RANGES"},{"location":"api/macros/json_has_ranges/#default-definition","text":"The default value is detected based on the preprocessor macro __cpp_lib_ranges . When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_has_ranges/#examples","text":"Example The code below forces the library to enable support for ranges: #define JSON_HAS_RANGES 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_ranges/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_has_static_rtti/","text":"JSON_HAS_STATIC_RTTI \u00b6 #define JSON_HAS_STATIC_RTTI /* value */ 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. Default definition \u00b6 The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI . When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The code below forces the library to enable support for libraries with RTTI dependence: #define JSON_HAS_STATIC_RTTI 1 #include ... Version history \u00b6 Added in version ?.","title":"JSON_HAS_STATIC_RTTI"},{"location":"api/macros/json_has_static_rtti/#json_has_static_rtti","text":"#define JSON_HAS_STATIC_RTTI /* value */ 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.","title":"JSON_HAS_STATIC_RTTI"},{"location":"api/macros/json_has_static_rtti/#default-definition","text":"The default value is detected based on the preprocessor macro _HAS_STATIC_RTTI . When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_has_static_rtti/#examples","text":"Example The code below forces the library to enable support for libraries with RTTI dependence: #define JSON_HAS_STATIC_RTTI 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_static_rtti/#version-history","text":"Added in version ?.","title":"Version history"},{"location":"api/macros/json_has_three_way_comparison/","text":"JSON_HAS_THREE_WAY_COMPARISON \u00b6 #define JSON_HAS_THREE_WAY_COMPARISON /* value */ This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported. Default definition \u00b6 The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison . When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The code below forces the library to use 3-way comparison: #define JSON_HAS_THREE_WAY_COMPARISON 1 #include ... Version history \u00b6 Added in version 3.11.0.","title":"JSON_HAS_THREE_WAY_COMPARISON"},{"location":"api/macros/json_has_three_way_comparison/#json_has_three_way_comparison","text":"#define JSON_HAS_THREE_WAY_COMPARISON /* value */ This macro indicates whether the compiler and standard library support 3-way comparison. Possible values are 1 when supported or 0 when unsupported.","title":"JSON_HAS_THREE_WAY_COMPARISON"},{"location":"api/macros/json_has_three_way_comparison/#default-definition","text":"The default value is detected based on the preprocessor macros __cpp_impl_three_way_comparison and __cpp_lib_three_way_comparison . When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_has_three_way_comparison/#examples","text":"Example The code below forces the library to use 3-way comparison: #define JSON_HAS_THREE_WAY_COMPARISON 1 #include ...","title":"Examples"},{"location":"api/macros/json_has_three_way_comparison/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_no_io/","text":"JSON_NO_IO \u00b6 #define JSON_NO_IO When defined, headers , , , , and 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)). Default definition \u00b6 By default, JSON_NO_IO is not defined. #undef JSON_NO_IO Examples \u00b6 Example The code below forces the library not to use the headers , , , , and . #define JSON_NO_IO 1 #include ... Version history \u00b6 Added in version 3.10.0.","title":"JSON_NO_IO"},{"location":"api/macros/json_no_io/#json_no_io","text":"#define JSON_NO_IO When defined, headers , , , , and 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)).","title":"JSON_NO_IO"},{"location":"api/macros/json_no_io/#default-definition","text":"By default, JSON_NO_IO is not defined. #undef JSON_NO_IO","title":"Default definition"},{"location":"api/macros/json_no_io/#examples","text":"Example The code below forces the library not to use the headers , , , , and . #define JSON_NO_IO 1 #include ...","title":"Examples"},{"location":"api/macros/json_no_io/#version-history","text":"Added in version 3.10.0.","title":"Version history"},{"location":"api/macros/json_noexception/","text":"JSON_NOEXCEPTION \u00b6 #define JSON_NOEXCEPTION 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 . Default definition \u00b6 By default, the macro is not defined. #undef JSON_NOEXCEPTION Notes \u00b6 The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 . Examples \u00b6 Example The code below switches off exceptions in the library. #define JSON_NOEXCEPTION 1 #include ... See also \u00b6 Switch off exceptions for more information how to switch off exceptions Version history \u00b6 Added in version 2.1.0.","title":"JSON_NOEXCEPTION"},{"location":"api/macros/json_noexception/#json_noexception","text":"#define JSON_NOEXCEPTION 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 .","title":"JSON_NOEXCEPTION"},{"location":"api/macros/json_noexception/#default-definition","text":"By default, the macro is not defined. #undef JSON_NOEXCEPTION","title":"Default definition"},{"location":"api/macros/json_noexception/#notes","text":"The explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 .","title":"Notes"},{"location":"api/macros/json_noexception/#examples","text":"Example The code below switches off exceptions in the library. #define JSON_NOEXCEPTION 1 #include ...","title":"Examples"},{"location":"api/macros/json_noexception/#see-also","text":"Switch off exceptions for more information how to switch off exceptions","title":"See also"},{"location":"api/macros/json_noexception/#version-history","text":"Added in version 2.1.0.","title":"Version history"},{"location":"api/macros/json_skip_library_version_check/","text":"JSON_SKIP_LIBRARY_VERSION_CHECK \u00b6 #define JSON_SKIP_LIBRARY_VERSION_CHECK When defined, the library will not create a compiler warning when a different version of the library was already included. Default definition \u00b6 By default, the macro is not defined. #undef JSON_SKIP_LIBRARY_VERSION_CHECK Notes \u00b6 ABI compatibility Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible. Examples \u00b6 Example The following warning will be shown in case a different version of the library was already included: Already included a different version of the library! Version history \u00b6 Added in version 3.11.0.","title":"JSON_SKIP_LIBRARY_VERSION_CHECK"},{"location":"api/macros/json_skip_library_version_check/#json_skip_library_version_check","text":"#define JSON_SKIP_LIBRARY_VERSION_CHECK When defined, the library will not create a compiler warning when a different version of the library was already included.","title":"JSON_SKIP_LIBRARY_VERSION_CHECK"},{"location":"api/macros/json_skip_library_version_check/#default-definition","text":"By default, the macro is not defined. #undef JSON_SKIP_LIBRARY_VERSION_CHECK","title":"Default definition"},{"location":"api/macros/json_skip_library_version_check/#notes","text":"ABI compatibility Mixing different library versions in the same code can be a problem as the different versions may not be ABI compatible.","title":"Notes"},{"location":"api/macros/json_skip_library_version_check/#examples","text":"Example The following warning will be shown in case a different version of the library was already included: Already included a different version of the library!","title":"Examples"},{"location":"api/macros/json_skip_library_version_check/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_skip_unsupported_compiler_check/","text":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK \u00b6 #define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 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. Default definition \u00b6 By default, the macro is not defined. #undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK Examples \u00b6 Example The code below switches off the check whether the compiler is supported. #define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1 #include ... Version history \u00b6 Added in version 3.2.0.","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK"},{"location":"api/macros/json_skip_unsupported_compiler_check/#json_skip_unsupported_compiler_check","text":"#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 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.","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK"},{"location":"api/macros/json_skip_unsupported_compiler_check/#default-definition","text":"By default, the macro is not defined. #undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK","title":"Default definition"},{"location":"api/macros/json_skip_unsupported_compiler_check/#examples","text":"Example The code below switches off the check whether the compiler is supported. #define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1 #include ...","title":"Examples"},{"location":"api/macros/json_skip_unsupported_compiler_check/#version-history","text":"Added in version 3.2.0.","title":"Version history"},{"location":"api/macros/json_throw_user/","text":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER \u00b6 // (1) #define JSON_CATCH_USER(exception) /* value */ // (2) #define JSON_THROW_USER(exception) /* value */ // (3) #define JSON_TRY_USER /* value */ 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. Parameters \u00b6 exception (in) an exception type Default definition \u00b6 By default, the macros map to their respective C++ keywords: #define JSON_CATCH_USER(exception) catch(exception) #define JSON_THROW_USER(exception) throw exception #define JSON_TRY_USER try 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() #define JSON_TRY_USER if (true) #define JSON_CATCH_USER(exception) if (false) Examples \u00b6 Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include See also \u00b6 Switch off exceptions for more information how to switch off exceptions JSON_NOEXCEPTION - switch off exceptions Version history \u00b6 Added in version 3.1.0.","title":"JSON_TRY_USER"},{"location":"api/macros/json_throw_user/#json_catch_user-json_throw_user-json_try_user","text":"// (1) #define JSON_CATCH_USER(exception) /* value */ // (2) #define JSON_THROW_USER(exception) /* value */ // (3) #define JSON_TRY_USER /* value */ 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.","title":"JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER"},{"location":"api/macros/json_throw_user/#parameters","text":"exception (in) an exception type","title":"Parameters"},{"location":"api/macros/json_throw_user/#default-definition","text":"By default, the macros map to their respective C++ keywords: #define JSON_CATCH_USER(exception) catch(exception) #define JSON_THROW_USER(exception) throw exception #define JSON_TRY_USER try 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() #define JSON_TRY_USER if (true) #define JSON_CATCH_USER(exception) if (false)","title":"Default definition"},{"location":"api/macros/json_throw_user/#examples","text":"Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include ","title":"Examples"},{"location":"api/macros/json_throw_user/#see-also","text":"Switch off exceptions for more information how to switch off exceptions JSON_NOEXCEPTION - switch off exceptions","title":"See also"},{"location":"api/macros/json_throw_user/#version-history","text":"Added in version 3.1.0.","title":"Version history"},{"location":"api/macros/json_use_global_udls/","text":"JSON_USE_GLOBAL_UDLS \u00b6 #define JSON_USE_GLOBAL_UDLS /* value */ When defined to 1 , the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals . Default definition \u00b6 The default value is 1 . #define JSON_USE_GLOBAL_UDLS 1 When the macro is not defined, the library will define it to its default value. Notes \u00b6 Future behavior change The user-defined string literals will be removed from the global namespace in the next major release of the library. To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details. CMake option The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs ( ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly. Examples \u00b6 Example 1: Default behavior The code below shows the default behavior using the _json UDL. #include #include int main () { auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42 Example 2: Namespaced UDLs The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0 . #define JSON_USE_GLOBAL_UDLS 0 #include #include int main () { // auto j = \"42\"_json; // This line would fail to compile, // because the UDLs are not in the global namespace // Bring the UDLs into scope using namespace nlohmann :: json_literals ; auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42 See also \u00b6 operator\"\"_json operator\"\"_json_pointer Version history \u00b6 Added in version 3.11.0.","title":"JSON_USE_GLOBAL_UDLS"},{"location":"api/macros/json_use_global_udls/#json_use_global_udls","text":"#define JSON_USE_GLOBAL_UDLS /* value */ When defined to 1 , the user-defined string literals (UDLs) are placed into the global namespace instead of nlohmann::literals::json_literals .","title":"JSON_USE_GLOBAL_UDLS"},{"location":"api/macros/json_use_global_udls/#default-definition","text":"The default value is 1 . #define JSON_USE_GLOBAL_UDLS 1 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_use_global_udls/#notes","text":"Future behavior change The user-defined string literals will be removed from the global namespace in the next major release of the library. To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Refer to any of the string literals for details. CMake option The placement of user-defined string literals can also be controlled with the CMake option JSON_GlobalUDLs ( ON by default) which defines JSON_USE_GLOBAL_UDLS accordingly.","title":"Notes"},{"location":"api/macros/json_use_global_udls/#examples","text":"Example 1: Default behavior The code below shows the default behavior using the _json UDL. #include #include int main () { auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42 Example 2: Namespaced UDLs The code below shows how UDLs need to be brought into scope before using _json when JSON_USE_GLOBAL_UDLS is defined to 0 . #define JSON_USE_GLOBAL_UDLS 0 #include #include int main () { // auto j = \"42\"_json; // This line would fail to compile, // because the UDLs are not in the global namespace // Bring the UDLs into scope using namespace nlohmann :: json_literals ; auto j = \"42\" _json ; std :: cout << j << std :: endl ; } Output: 42","title":"Examples"},{"location":"api/macros/json_use_global_udls/#see-also","text":"operator\"\"_json operator\"\"_json_pointer","title":"See also"},{"location":"api/macros/json_use_global_udls/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/json_use_implicit_conversions/","text":"JSON_USE_IMPLICIT_CONVERSIONS \u00b6 #define JSON_USE_IMPLICIT_CONVERSIONS /* value */ When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType . Default definition \u00b6 By default, implicit conversions are enabled. #define JSON_USE_IMPLICIT_CONVERSIONS 1 Notes \u00b6 Future behavior change Implicit conversions will be switched off by default in the next major release of the library. You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get . CMake option Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions ( ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly. Examples \u00b6 Example This is an example for an implicit conversion: json j = \"Hello, world!\" ; std :: string s = j ; When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0 , the code above does no longer compile. Instead, it must be written like this: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > (); See also \u00b6 operator ValueType - get a value (implicit) get - get a value (explicit) Version history \u00b6 Added in version 3.9.0.","title":"JSON_USE_IMPLICIT_CONVERSIONS"},{"location":"api/macros/json_use_implicit_conversions/#json_use_implicit_conversions","text":"#define JSON_USE_IMPLICIT_CONVERSIONS /* value */ When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. The value directly affects operator ValueType .","title":"JSON_USE_IMPLICIT_CONVERSIONS"},{"location":"api/macros/json_use_implicit_conversions/#default-definition","text":"By default, implicit conversions are enabled. #define JSON_USE_IMPLICIT_CONVERSIONS 1","title":"Default definition"},{"location":"api/macros/json_use_implicit_conversions/#notes","text":"Future behavior change Implicit conversions will be switched off by default in the next major release of the library. You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get . CMake option Implicit conversions can also be controlled with the CMake option JSON_ImplicitConversions ( ON by default) which defines JSON_USE_IMPLICIT_CONVERSIONS accordingly.","title":"Notes"},{"location":"api/macros/json_use_implicit_conversions/#examples","text":"Example This is an example for an implicit conversion: json j = \"Hello, world!\" ; std :: string s = j ; When JSON_USE_IMPLICIT_CONVERSIONS is defined to 0 , the code above does no longer compile. Instead, it must be written like this: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > ();","title":"Examples"},{"location":"api/macros/json_use_implicit_conversions/#see-also","text":"operator ValueType - get a value (implicit) get - get a value (explicit)","title":"See also"},{"location":"api/macros/json_use_implicit_conversions/#version-history","text":"Added in version 3.9.0.","title":"Version history"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/","text":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON \u00b6 #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */ This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default). When enabled, comparisons involving at least one discarded JSON value yield results as follows: Operator Result == false != true < false <= true >= true > false Otherwise, comparisons involving at least one discarded JSON value always yield false . Default definition \u00b6 The default value is 0 . #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 When the macro is not defined, the library will define it to its default value. Notes \u00b6 Inconsistent behavior in C++20 and beyond 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. Examples \u00b6 Example The code below switches on the legacy discarded value comparison behavior in the library. #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include ... Version history \u00b6 Added in version 3.11.0.","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#json_use_legacy_discarded_value_comparison","text":"#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */ This macro enables the (incorrect) legacy comparison behavior of discarded JSON values. Possible values are 1 to enable or 0 to disable (default). When enabled, comparisons involving at least one discarded JSON value yield results as follows: Operator Result == false != true < false <= true >= true > false Otherwise, comparisons involving at least one discarded JSON value always yield false .","title":"JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#default-definition","text":"The default value is 0 . #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#notes","text":"Inconsistent behavior in C++20 and beyond 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.","title":"Notes"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#examples","text":"Example The code below switches on the legacy discarded value comparison behavior in the library. #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include ...","title":"Examples"},{"location":"api/macros/json_use_legacy_discarded_value_comparison/#version-history","text":"Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/nlohmann_define_type_intrusive/","text":"NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT \u00b6 #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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. Parameters \u00b6 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 Default definition \u00b6 The macros add two friend functions to the class which take care of the serialization and deserialization: friend void to_json ( nlohmann :: json & , const type & ); friend void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code. Notes \u00b6 Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Examples \u00b6 Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values. See also \u00b6 NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined outside the type. Arbitrary Type Conversions for an overview. Version history \u00b6 Added in version 3.9.0. Added in version 3.11.0.","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_intrusive/#nlohmann_define_type_intrusive-nlohmann_define_type_intrusive_with_default","text":"#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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.","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_intrusive/#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","title":"Parameters"},{"location":"api/macros/nlohmann_define_type_intrusive/#default-definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization: friend void to_json ( nlohmann :: json & , const type & ); friend void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code.","title":"Default definition"},{"location":"api/macros/nlohmann_define_type_intrusive/#notes","text":"Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.","title":"Notes"},{"location":"api/macros/nlohmann_define_type_intrusive/#examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has private member variables. This makes NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT applicable, but not NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT . 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { class person { private : std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; public : person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} friend void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } friend void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } }; } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values.","title":"Examples"},{"location":"api/macros/nlohmann_define_type_intrusive/#see-also","text":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined outside the type. Arbitrary Type Conversions for an overview.","title":"See also"},{"location":"api/macros/nlohmann_define_type_intrusive/#version-history","text":"Added in version 3.9.0. Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/nlohmann_define_type_non_intrusive/","text":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT \u00b6 #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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. Parameters \u00b6 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 Default definition \u00b6 The macros add two functions to the namespace which take care of the serialization and deserialization: void to_json ( nlohmann :: json & , const type & ); void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code. Notes \u00b6 Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Examples \u00b6 Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable. 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable. The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns . A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value -1 is used. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values. See also \u00b6 NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined inside the type. Arbitrary Type Conversions for an overview. Version history \u00b6 Added in version 3.9.0. Added in version 3.11.0.","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#nlohmann_define_type_non_intrusive-nlohmann_define_type_non_intrusive_with_default","text":"#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1) #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2) 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.","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#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","title":"Parameters"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#default-definition","text":"The macros add two functions to the namespace which take care of the serialization and deserialization: void to_json ( nlohmann :: json & , const type & ); void from_json ( const nlohmann :: json & , type & ); See examples below for the concrete generated code.","title":"Default definition"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#notes","text":"Prerequisites The type type must be default constructible. 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported.","title":"Notes"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#examples","text":"Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } deserializa t io n fa iled : [ jso n .excep t io n .ou t _o f _ra n ge. 403 ] key 'age' n o t f ou n d Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE applicable. 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. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name ; std :: string address ; int age ; }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { nlohmann_json_t . name = nlohmann_json_j . at ( \"name\" ); nlohmann_json_t . address = nlohmann_json_j . at ( \"address\" ); nlohmann_json_t . age = nlohmann_json_j . at ( \"age\" ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; try { auto p3 = j3 . template get < ns :: person > (); } catch ( const json :: exception & e ) { std :: cout << \"deserialization failed: \" << e . what () << std :: endl ; } } Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT Consider the following complete example: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT ( person , name , address , age ) } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Output: serializa t io n : { \"address\" : \"744 Evergreen Terrace\" , \"age\" : 60 , \"name\" : \"Ned Flanders\" } rou n d tr ip : { \"address\" : \"742 Evergreen Terrace\" , \"age\" : -1 , \"name\" : \"Maggie Simpson\" } Notes: ns::person is default-constructible. This is a requirement for using the macro. ns::person has only public member variables. This makes NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT applicable. The macro NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT is used outside the class, but inside its namespace ns . A missing key \"age\" in the deserialization does not yield an exception. Instead, the default value -1 is used. The macro is equivalent to: #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; namespace ns { struct person { std :: string name = \"John Doe\" ; std :: string address = \"123 Fake St\" ; int age = -1 ; person () = default ; person ( std :: string name_ , std :: string address_ , int age_ ) : name ( std :: move ( name_ )), address ( std :: move ( address_ )), age ( age_ ) {} }; void to_json ( nlohmann :: json & nlohmann_json_j , const person & nlohmann_json_t ) { nlohmann_json_j [ \"name\" ] = nlohmann_json_t . name ; nlohmann_json_j [ \"address\" ] = nlohmann_json_t . address ; nlohmann_json_j [ \"age\" ] = nlohmann_json_t . age ; } void from_json ( const nlohmann :: json & nlohmann_json_j , person & nlohmann_json_t ) { person nlohmann_json_default_obj ; nlohmann_json_t . name = nlohmann_json_j . value ( \"name\" , nlohmann_json_default_obj . name ); nlohmann_json_t . address = nlohmann_json_j . value ( \"address\" , nlohmann_json_default_obj . address ); nlohmann_json_t . age = nlohmann_json_j . value ( \"age\" , nlohmann_json_default_obj . age ); } } // namespace ns int main () { ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // serialization: person -> json json j = p ; std :: cout << \"serialization: \" << j << std :: endl ; // deserialization: json -> person json j2 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"age\": 40, \"name\": \"Homer Simpson\"} ) \" _json ; auto p2 = j2 . template get < ns :: person > (); // incomplete deserialization: json j3 = R \" ( {\"address\": \"742 Evergreen Terrace\", \"name\": \"Maggie Simpson\"} ) \" _json ; auto p3 = j3 . template get < ns :: person > (); std :: cout << \"roundtrip: \" << json ( p3 ) << std :: endl ; } Note how a default-initialized person object is used in the from_json to fill missing values.","title":"Examples"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#see-also","text":"NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT for a similar macro that can be defined inside the type. Arbitrary Type Conversions for an overview.","title":"See also"},{"location":"api/macros/nlohmann_define_type_non_intrusive/#version-history","text":"Added in version 3.9.0. Added in version 3.11.0.","title":"Version history"},{"location":"api/macros/nlohmann_json_namespace/","text":"NLOHMANN_JSON_NAMESPACE \u00b6 #define NLOHMANN_JSON_NAMESPACE /* value */ This macro evaluates to the full name of the nlohmann namespace. Default definition \u00b6 The default value consists of the root namespace ( nlohmann ) and an inline ABI namespace. See nlohmann Namespace for details. When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library. Examples \u00b6 Example The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann , as well as how to output the value of NLOHMANN_JSON_NAMESPACE . #include #include // possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann using json = NLOHMANN_JSON_NAMESPACE :: json ; // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi_v 3 _ 11 _ 2 See also \u00b6 NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END NLOHMANN_JSON_NAMESPACE_NO_VERSION Version history \u00b6 Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"NLOHMANN_JSON_NAMESPACE"},{"location":"api/macros/nlohmann_json_namespace/#nlohmann_json_namespace","text":"#define NLOHMANN_JSON_NAMESPACE /* value */ This macro evaluates to the full name of the nlohmann namespace.","title":"NLOHMANN_JSON_NAMESPACE"},{"location":"api/macros/nlohmann_json_namespace/#default-definition","text":"The default value consists of the root namespace ( nlohmann ) and an inline ABI namespace. See nlohmann Namespace for details. When the macro is not defined, the library will define it to its default value. Overriding this value has no effect on the library.","title":"Default definition"},{"location":"api/macros/nlohmann_json_namespace/#examples","text":"Example The example shows how to use NLOHMANN_JSON_NAMESPACE instead of just nlohmann , as well as how to output the value of NLOHMANN_JSON_NAMESPACE . #include #include // possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann using json = NLOHMANN_JSON_NAMESPACE :: json ; // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi_v 3 _ 11 _ 2","title":"Examples"},{"location":"api/macros/nlohmann_json_namespace/#see-also","text":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END NLOHMANN_JSON_NAMESPACE_NO_VERSION","title":"See also"},{"location":"api/macros/nlohmann_json_namespace/#version-history","text":"Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"Version history"},{"location":"api/macros/nlohmann_json_namespace_begin/","text":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END \u00b6 #define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1) #define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2) These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details. Opens the namespace. Closes the namespace. Default definition \u00b6 The default definitions open and close the nlohmann namespace. The precise definition of [ NLOHMANN_JSON_NAMESPACE_BEGIN ] varies as described here . Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN : namespace nlohmann { inline namespace json_abi_v3_11_2 { Default definition of NLOHMANN_JSON_NAMESPACE_END : } // namespace json_abi_v3_11_2 } // namespace nlohmann When these macros are not defined, the library will define them to their default definitions. Examples \u00b6 Example The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN / NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page. #include #include #include // partial specialization (see https://json.nlohmann.me/features/arbitrary_types/) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < std :: optional < T >> { static void to_json ( json & j , const std :: optional < T >& opt ) { if ( opt == std :: nullopt ) { j = nullptr ; } else { j = * opt ; } } }; NLOHMANN_JSON_NAMESPACE_END int main () { std :: optional < int > o1 = 1 ; std :: optional < int > o2 = std :: nullopt ; NLOHMANN_JSON_NAMESPACE :: json j ; j . push_back ( o1 ); j . push_back ( o2 ); std :: cout << j << std :: endl ; } Output: [ 1 , null ] See also \u00b6 nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_NO_VERSION Version history \u00b6 Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"NLOHMANN_JSON_NAMESPACE_END"},{"location":"api/macros/nlohmann_json_namespace_begin/#nlohmann_json_namespace_begin-nlohmann_json_namespace_end","text":"#define NLOHMANN_JSON_NAMESPACE_BEGIN /* value */ // (1) #define NLOHMANN_JSON_NAMESPACE_END /* value */ // (2) These macros can be used to open and close the nlohmann namespace. See nlohmann Namespace for details. Opens the namespace. Closes the namespace.","title":"NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END"},{"location":"api/macros/nlohmann_json_namespace_begin/#default-definition","text":"The default definitions open and close the nlohmann namespace. The precise definition of [ NLOHMANN_JSON_NAMESPACE_BEGIN ] varies as described here . Default definition of NLOHMANN_JSON_NAMESPACE_BEGIN : namespace nlohmann { inline namespace json_abi_v3_11_2 { Default definition of NLOHMANN_JSON_NAMESPACE_END : } // namespace json_abi_v3_11_2 } // namespace nlohmann When these macros are not defined, the library will define them to their default definitions.","title":"Default definition"},{"location":"api/macros/nlohmann_json_namespace_begin/#examples","text":"Example The example shows how to use NLOHMANN_JSON_NAMESPACE_BEGIN / NLOHMANN_JSON_NAMESPACE_END from the How do I convert third-party types? page. #include #include #include // partial specialization (see https://json.nlohmann.me/features/arbitrary_types/) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < std :: optional < T >> { static void to_json ( json & j , const std :: optional < T >& opt ) { if ( opt == std :: nullopt ) { j = nullptr ; } else { j = * opt ; } } }; NLOHMANN_JSON_NAMESPACE_END int main () { std :: optional < int > o1 = 1 ; std :: optional < int > o2 = std :: nullopt ; NLOHMANN_JSON_NAMESPACE :: json j ; j . push_back ( o1 ); j . push_back ( o2 ); std :: cout << j << std :: endl ; } Output: [ 1 , null ]","title":"Examples"},{"location":"api/macros/nlohmann_json_namespace_begin/#see-also","text":"nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_NO_VERSION","title":"See also"},{"location":"api/macros/nlohmann_json_namespace_begin/#version-history","text":"Added in version 3.11.0. Changed inline namespace name in version 3.11.2.","title":"Version history"},{"location":"api/macros/nlohmann_json_namespace_no_version/","text":"NLOHMANN_JSON_NAMESPACE_NO_VERSION \u00b6 #define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */ If defined to 1 , the version component is omitted from the inline namespace. See nlohmann Namespace for details. Default definition \u00b6 The default value is 0 . #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 When the macro is not defined, the library will define it to its default value. Examples \u00b6 Example The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace. #include #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1 #include // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi See also \u00b6 nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END Version history \u00b6 Added in version 3.11.2.","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION"},{"location":"api/macros/nlohmann_json_namespace_no_version/#nlohmann_json_namespace_no_version","text":"#define NLOHMANN_JSON_NAMESPACE_NO_VERSION /* value */ If defined to 1 , the version component is omitted from the inline namespace. See nlohmann Namespace for details.","title":"NLOHMANN_JSON_NAMESPACE_NO_VERSION"},{"location":"api/macros/nlohmann_json_namespace_no_version/#default-definition","text":"The default value is 0 . #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 When the macro is not defined, the library will define it to its default value.","title":"Default definition"},{"location":"api/macros/nlohmann_json_namespace_no_version/#examples","text":"Example The example shows how to use NLOHMANN_JSON_NAMESPACE_NO_VERSION to disable the version component of the inline namespace. #include #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1 #include // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main () { std :: cout << QUOTE ( NLOHMANN_JSON_NAMESPACE ) << std :: endl ; } Output: nl ohma nn :: jso n _abi","title":"Examples"},{"location":"api/macros/nlohmann_json_namespace_no_version/#see-also","text":"nlohmann Namespace NLOHMANN_JSON_NAMESPACE NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END","title":"See also"},{"location":"api/macros/nlohmann_json_namespace_no_version/#version-history","text":"Added in version 3.11.2.","title":"Version history"},{"location":"api/macros/nlohmann_json_serialize_enum/","text":"NLOHMANN_JSON_SERIALIZE_ENUM \u00b6 #define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...) 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. Parameters \u00b6 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 Default definition \u00b6 The macros add two friend functions to the class which take care of the serialization and deserialization: template < typename BasicJsonType > inline void to_json ( BasicJsonType & j , const type & e ); template < typename BasicJsonType > inline void from_json ( const BasicJsonType & j , type & e ); Notes \u00b6 Prerequisites The macro must be used inside the namespace of the enum. Important notes When using template get() , 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. Examples \u00b6 Example 1: Basic usage The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes: #include #include using json = nlohmann :: json ; namespace ns { enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 }; NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" } }) enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" } }) } // namespace ns int main () { // serialization json j_stopped = ns :: TS_STOPPED ; json j_red = ns :: Color :: red ; std :: cout << \"ns::TS_STOPPED -> \" << j_stopped << \", ns::Color::red -> \" << j_red << std :: endl ; // deserialization json j_running = \"running\" ; json j_blue = \"blue\" ; auto running = j_running . template get < ns :: TaskState > (); auto blue = j_blue . template get < ns :: Color > (); std :: cout << j_running << \" -> \" << running << \", \" << j_blue << \" -> \" << static_cast < int > ( blue ) << std :: endl ; // deserializing undefined JSON value to enum // (where the first map entry above is the default) json j_pi = 3.14 ; auto invalid = j_pi . template get < ns :: TaskState > (); auto unknown = j_pi . template get < ns :: Color > (); std :: cout << j_pi << \" -> \" << invalid << \", \" << j_pi << \" -> \" << static_cast < int > ( unknown ) << std :: endl ; } Output: ns :: TS_STOPPED - > \"stopped\" , ns :: Color :: red - > \"red\" \"running\" - > 1 , \"blue\" - > 2 3.14 - > -1 , 3.14 - > 3 Example 2: Multiple conversions for one enumerator The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\" , because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red . #include #include using json = nlohmann :: json ; namespace ns { enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" }, { Color :: red , \"rot\" } // a second conversion for Color::red }) } int main () { // serialization json j_red = ns :: Color :: red ; std :: cout << static_cast < int > ( ns :: Color :: red ) << \" -> \" << j_red << std :: endl ; // deserialization json j_rot = \"rot\" ; auto rot = j_rot . template get < ns :: Color > (); auto red = j_red . template get < ns :: Color > (); std :: cout << j_rot << \" -> \" << static_cast < int > ( rot ) << std :: endl ; std :: cout << j_red << \" -> \" << static_cast < int > ( red ) << std :: endl ; } Output: 0 - > \"red\" \"rot\" - > 0 \"red\" - > 0 See also \u00b6 Specializing enum conversion JSON_DISABLE_ENUM_SERIALIZATION Version history \u00b6 Added in version 3.4.0.","title":"NLOHMANN_JSON_SERIALIZE_ENUM"},{"location":"api/macros/nlohmann_json_serialize_enum/#nlohmann_json_serialize_enum","text":"#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...) 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.","title":"NLOHMANN_JSON_SERIALIZE_ENUM"},{"location":"api/macros/nlohmann_json_serialize_enum/#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","title":"Parameters"},{"location":"api/macros/nlohmann_json_serialize_enum/#default-definition","text":"The macros add two friend functions to the class which take care of the serialization and deserialization: template < typename BasicJsonType > inline void to_json ( BasicJsonType & j , const type & e ); template < typename BasicJsonType > inline void from_json ( const BasicJsonType & j , type & e );","title":"Default definition"},{"location":"api/macros/nlohmann_json_serialize_enum/#notes","text":"Prerequisites The macro must be used inside the namespace of the enum. Important notes When using template get() , 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.","title":"Notes"},{"location":"api/macros/nlohmann_json_serialize_enum/#examples","text":"Example 1: Basic usage The example shows how NLOHMANN_JSON_SERIALIZE_ENUM can be used to serialize/deserialize both classical enums and C++11 enum classes: #include #include using json = nlohmann :: json ; namespace ns { enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 }; NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" } }) enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" } }) } // namespace ns int main () { // serialization json j_stopped = ns :: TS_STOPPED ; json j_red = ns :: Color :: red ; std :: cout << \"ns::TS_STOPPED -> \" << j_stopped << \", ns::Color::red -> \" << j_red << std :: endl ; // deserialization json j_running = \"running\" ; json j_blue = \"blue\" ; auto running = j_running . template get < ns :: TaskState > (); auto blue = j_blue . template get < ns :: Color > (); std :: cout << j_running << \" -> \" << running << \", \" << j_blue << \" -> \" << static_cast < int > ( blue ) << std :: endl ; // deserializing undefined JSON value to enum // (where the first map entry above is the default) json j_pi = 3.14 ; auto invalid = j_pi . template get < ns :: TaskState > (); auto unknown = j_pi . template get < ns :: Color > (); std :: cout << j_pi << \" -> \" << invalid << \", \" << j_pi << \" -> \" << static_cast < int > ( unknown ) << std :: endl ; } Output: ns :: TS_STOPPED - > \"stopped\" , ns :: Color :: red - > \"red\" \"running\" - > 1 , \"blue\" - > 2 3.14 - > -1 , 3.14 - > 3 Example 2: Multiple conversions for one enumerator The example shows how to use multiple conversions for a single enumerator. In the example, Color::red will always be serialized to \"red\" , because the first occurring conversion. The second conversion, however, offers an alternative deserialization from \"rot\" to Color::red . #include #include using json = nlohmann :: json ; namespace ns { enum class Color { red , green , blue , unknown }; NLOHMANN_JSON_SERIALIZE_ENUM ( Color , { { Color :: unknown , \"unknown\" }, { Color :: red , \"red\" }, { Color :: green , \"green\" }, { Color :: blue , \"blue\" }, { Color :: red , \"rot\" } // a second conversion for Color::red }) } int main () { // serialization json j_red = ns :: Color :: red ; std :: cout << static_cast < int > ( ns :: Color :: red ) << \" -> \" << j_red << std :: endl ; // deserialization json j_rot = \"rot\" ; auto rot = j_rot . template get < ns :: Color > (); auto red = j_red . template get < ns :: Color > (); std :: cout << j_rot << \" -> \" << static_cast < int > ( rot ) << std :: endl ; std :: cout << j_red << \" -> \" << static_cast < int > ( red ) << std :: endl ; } Output: 0 - > \"red\" \"rot\" - > 0 \"red\" - > 0","title":"Examples"},{"location":"api/macros/nlohmann_json_serialize_enum/#see-also","text":"Specializing enum conversion JSON_DISABLE_ENUM_SERIALIZATION","title":"See also"},{"location":"api/macros/nlohmann_json_serialize_enum/#version-history","text":"Added in version 3.4.0.","title":"Version history"},{"location":"api/macros/nlohmann_json_version_major/","text":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH \u00b6 #define NLOHMANN_JSON_VERSION_MAJOR /* value */ #define NLOHMANN_JSON_VERSION_MINOR /* value */ #define NLOHMANN_JSON_VERSION_PATCH /* value */ These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 . Default definition \u00b6 The macros are defined according to the current library version. Examples \u00b6 Example The example below shows how NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH are defined by the library. #include #include using json = nlohmann :: json ; int main () { std :: cout << \"JSON for Modern C++ version \" << NLOHMANN_JSON_VERSION_MAJOR << \".\" << NLOHMANN_JSON_VERSION_MINOR << \".\" << NLOHMANN_JSON_VERSION_PATCH << std :: endl ; } Output: JSON f or Moder n C++ versio n 3.11.2 See also \u00b6 meta - returns version information on the library JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check Version history \u00b6 Added in version 3.1.0.","title":"NLOHMANN_JSON_VERSION_PATCH"},{"location":"api/macros/nlohmann_json_version_major/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","text":"#define NLOHMANN_JSON_VERSION_MAJOR /* value */ #define NLOHMANN_JSON_VERSION_MINOR /* value */ #define NLOHMANN_JSON_VERSION_PATCH /* value */ These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 .","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH"},{"location":"api/macros/nlohmann_json_version_major/#default-definition","text":"The macros are defined according to the current library version.","title":"Default definition"},{"location":"api/macros/nlohmann_json_version_major/#examples","text":"Example The example below shows how NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH are defined by the library. #include #include using json = nlohmann :: json ; int main () { std :: cout << \"JSON for Modern C++ version \" << NLOHMANN_JSON_VERSION_MAJOR << \".\" << NLOHMANN_JSON_VERSION_MINOR << \".\" << NLOHMANN_JSON_VERSION_PATCH << std :: endl ; } Output: JSON f or Moder n C++ versio n 3.11.2","title":"Examples"},{"location":"api/macros/nlohmann_json_version_major/#see-also","text":"meta - returns version information on the library JSON_SKIP_LIBRARY_VERSION_CHECK - skip library version check","title":"See also"},{"location":"api/macros/nlohmann_json_version_major/#version-history","text":"Added in version 3.1.0.","title":"Version history"},{"location":"features/arbitrary_types/","text":"Arbitrary Type Conversions \u00b6 Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines: namespace ns { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // convert to JSON: copy each value into the JSON object json j ; j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; // ... // convert from JSON: copy each value from the JSON object ns :: person p { j [ \"name\" ]. template get < std :: string > (), j [ \"address\" ]. template get < std :: string > (), j [ \"age\" ]. template get < int > () }; It works, but that's quite a lot of boilerplate... Fortunately, there's a better way: // create a person ns :: person p { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // conversion: person -> json json j = p ; std :: cout << j << std :: endl ; // {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"} // conversion: json -> person auto p2 = j . template get < ns :: person > (); // that's it assert ( p == p2 ); Basic usage \u00b6 To make this work with one of your types, you only need to provide two functions: using json = nlohmann :: json ; namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns 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() 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 issue 1108 for errors that may occur otherwise. When using template get() , 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. Simplify your life with macros \u00b6 If you just want to serialize/deserialize some structs, the to_json / from_json functions can be a lot of boilerplate. There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object: NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here . Implementation limits 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Example The to_json / from_json functions for the person struct above can be created with: namespace ns { NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed: namespace ns { class address { private : std :: string street ; int housenumber ; int postcode ; public : NLOHMANN_DEFINE_TYPE_INTRUSIVE ( address , street , housenumber , postcode ) }; } How do I convert third-party types? \u00b6 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 > struct adl_serializer { static void to_json ( json & j , const T & value ) { // calls the \"to_json\" method in T's namespace } static void from_json ( const json & j , T & value ) { // same thing, but with the \"from_json\" method } }; 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) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < boost :: optional < T >> { static void to_json ( json & j , const boost :: optional < T >& opt ) { if ( opt == boost :: none ) { j = nullptr ; } else { j = * opt ; // this will call adl_serializer::to_json which will // find the free function to_json in T's namespace! } } static void from_json ( const json & j , boost :: optional < T >& opt ) { if ( j . is_null ()) { opt = boost :: none ; } else { opt = j . template get < T > (); // same as above, but with // adl_serializer::from_json } } }; NLOHMANN_JSON_NAMESPACE_END 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. How can I use get() for non-default constructible/non-copyable types? \u00b6 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 { move_only_type () = delete ; move_only_type ( int ii ) : i ( ii ) {} move_only_type ( const move_only_type & ) = delete ; move_only_type ( move_only_type && ) = default ; int i ; }; namespace nlohmann { template <> struct adl_serializer < move_only_type > { // note: the return type is no longer 'void', and the method only takes // one argument static move_only_type from_json ( const json & j ) { return { j . template get < int > ()}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert move_only_type to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , move_only_type t ) { j = t . i ; } }; } Can I write my own serializer? (Advanced use) \u00b6 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 // if you don't need compile-time checks on T template < typename T , typename SFINAE = typename std :: enable_if < sizeof ( T ) <= 32 >:: type > struct less_than_32_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , T value ) { // we want to use ADL, and call the correct to_json overload using nlohmann :: to_json ; // this method is called by adl_serializer, // this is where the magic happens to_json ( j , value ); } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing here using nlohmann :: from_json ; from_json ( j , value ); } }; Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention: template < typename T , void > struct bad_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // this calls BasicJsonType::json_serializer::to_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! j = value ; } template < typename BasicJsonType > static void to_json ( const BasicJsonType & j , T & value ) { // this calls BasicJsonType::json_serializer::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j . template template get < T > (); // oops! } };","title":"Arbitrary Type Conversions"},{"location":"features/arbitrary_types/#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 { // a simple struct to model a person struct person { std :: string name ; std :: string address ; int age ; }; } // namespace ns ns :: person p = { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // convert to JSON: copy each value into the JSON object json j ; j [ \"name\" ] = p . name ; j [ \"address\" ] = p . address ; j [ \"age\" ] = p . age ; // ... // convert from JSON: copy each value from the JSON object ns :: person p { j [ \"name\" ]. template get < std :: string > (), j [ \"address\" ]. template get < std :: string > (), j [ \"age\" ]. template get < int > () }; It works, but that's quite a lot of boilerplate... Fortunately, there's a better way: // create a person ns :: person p { \"Ned Flanders\" , \"744 Evergreen Terrace\" , 60 }; // conversion: person -> json json j = p ; std :: cout << j << std :: endl ; // {\"address\":\"744 Evergreen Terrace\",\"age\":60,\"name\":\"Ned Flanders\"} // conversion: json -> person auto p2 = j . template get < ns :: person > (); // that's it assert ( p == p2 );","title":"Arbitrary Type Conversions"},{"location":"features/arbitrary_types/#basic-usage","text":"To make this work with one of your types, you only need to provide two functions: using json = nlohmann :: json ; namespace ns { void to_json ( json & j , const person & p ) { j = json { { \"name\" , p . name }, { \"address\" , p . address }, { \"age\" , p . age } }; } void from_json ( const json & j , person & p ) { j . at ( \"name\" ). get_to ( p . name ); j . at ( \"address\" ). get_to ( p . address ); j . at ( \"age\" ). get_to ( p . age ); } } // namespace ns 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() 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 issue 1108 for errors that may occur otherwise. When using template get() , 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.","title":"Basic usage"},{"location":"features/arbitrary_types/#simplify-your-life-with-macros","text":"If you just want to serialize/deserialize some structs, the to_json / from_json functions can be a lot of boilerplate. There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object: NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in from_json() due to a missing value in the JSON object. NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in from_json() due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from here . Implementation limits 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. The macros only work for the nlohmann::json type; other specializations such as nlohmann::ordered_json are currently unsupported. Example The to_json / from_json functions for the person struct above can be created with: namespace ns { NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE ( person , name , address , age ) } Here is an example with private members, where NLOHMANN_DEFINE_TYPE_INTRUSIVE is needed: namespace ns { class address { private : std :: string street ; int housenumber ; int postcode ; public : NLOHMANN_DEFINE_TYPE_INTRUSIVE ( address , street , housenumber , postcode ) }; }","title":"Simplify your life with macros"},{"location":"features/arbitrary_types/#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 > struct adl_serializer { static void to_json ( json & j , const T & value ) { // calls the \"to_json\" method in T's namespace } static void from_json ( const json & j , T & value ) { // same thing, but with the \"from_json\" method } }; 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) NLOHMANN_JSON_NAMESPACE_BEGIN template < typename T > struct adl_serializer < boost :: optional < T >> { static void to_json ( json & j , const boost :: optional < T >& opt ) { if ( opt == boost :: none ) { j = nullptr ; } else { j = * opt ; // this will call adl_serializer::to_json which will // find the free function to_json in T's namespace! } } static void from_json ( const json & j , boost :: optional < T >& opt ) { if ( j . is_null ()) { opt = boost :: none ; } else { opt = j . template get < T > (); // same as above, but with // adl_serializer::from_json } } }; NLOHMANN_JSON_NAMESPACE_END 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.","title":"How do I convert third-party types?"},{"location":"features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-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 { move_only_type () = delete ; move_only_type ( int ii ) : i ( ii ) {} move_only_type ( const move_only_type & ) = delete ; move_only_type ( move_only_type && ) = default ; int i ; }; namespace nlohmann { template <> struct adl_serializer < move_only_type > { // note: the return type is no longer 'void', and the method only takes // one argument static move_only_type from_json ( const json & j ) { return { j . template get < int > ()}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert move_only_type to json, since you fully // specialized adl_serializer on that type static void to_json ( json & j , move_only_type t ) { j = t . i ; } }; }","title":"How can I use get() for non-default constructible/non-copyable types?"},{"location":"features/arbitrary_types/#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 // if you don't need compile-time checks on T template < typename T , typename SFINAE = typename std :: enable_if < sizeof ( T ) <= 32 >:: type > struct less_than_32_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , T value ) { // we want to use ADL, and call the correct to_json overload using nlohmann :: to_json ; // this method is called by adl_serializer, // this is where the magic happens to_json ( j , value ); } template < typename BasicJsonType > static void from_json ( const BasicJsonType & j , T & value ) { // same thing here using nlohmann :: from_json ; from_json ( j , value ); } }; Be very careful when reimplementing your serializer, you can stack overflow if you don't pay attention: template < typename T , void > struct bad_serializer { template < typename BasicJsonType > static void to_json ( BasicJsonType & j , const T & value ) { // this calls BasicJsonType::json_serializer::to_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! j = value ; } template < typename BasicJsonType > static void to_json ( const BasicJsonType & j , T & value ) { // this calls BasicJsonType::json_serializer::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j . template template get < T > (); // oops! } };","title":"Can I write my own serializer? (Advanced use)"},{"location":"features/assertions/","text":"Runtime Assertions \u00b6 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. Switch off runtime assertions \u00b6 Runtime assertions can be switched off by defining the preprocessor macro NDEBUG (see the documentation of assert ) which is the default for release builds. Change assertion behavior \u00b6 The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header. Function with runtime assertions \u00b6 Unchecked object access to a const value \u00b6 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 using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. Constructing from an uninitialized iterator range \u00b6 Constructing a JSON value from an iterator range (see constructor ) with an uninitialized iterator is undefined behavior and yields a runtime assertion. Example 2: Uninitialized iterator range The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it1 , it2 ; json j ( it1 , it2 ); } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368. Operations on uninitialized iterators \u00b6 Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion. Example 3: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it ; ++ it ; } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368. Reading from a null FILE pointer \u00b6 Reading from a null FILE pointer is undefined behavior and yields a runtime assertion. This can happen when calling std :: fopen on a nonexistent file. Example 4: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { std :: FILE * f = std :: fopen ( \"nonexistent_file.json\" , \"r\" ); json j = json :: parse ( f ); } Output: Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.","title":"Runtime Assertions"},{"location":"features/assertions/#runtime-assertions","text":"The code contains numerous debug assertions to ensure class invariants are valid or to detect undefined behavior. Whereas the former class invariants are nothing to be concerned of, the latter checks for undefined behavior are to detect bugs in client code.","title":"Runtime Assertions"},{"location":"features/assertions/#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.","title":"Switch off runtime assertions"},{"location":"features/assertions/#change-assertion-behavior","text":"The behavior of runtime assertions can be changes by defining macro JSON_ASSERT(x) before including the json.hpp header.","title":"Change assertion behavior"},{"location":"features/assertions/#function-with-runtime-assertions","text":"","title":"Function with runtime assertions"},{"location":"features/assertions/#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 using json = nlohmann :: json ; int main () { const json j = {{ \"key\" , \"value\" }}; auto v = j [ \"missing\" ]; } Output: Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.","title":"Unchecked object access to a const value"},{"location":"features/assertions/#constructing-from-an-uninitialized-iterator-range","text":"Constructing a JSON value from an iterator range (see constructor ) with an uninitialized iterator is undefined behavior and yields a runtime assertion. Example 2: Uninitialized iterator range The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it1 , it2 ; json j ( it1 , it2 ); } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.","title":"Constructing from an uninitialized iterator range"},{"location":"features/assertions/#operations-on-uninitialized-iterators","text":"Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion. Example 3: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { json :: iterator it ; ++ it ; } Output: Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368.","title":"Operations on uninitialized iterators"},{"location":"features/assertions/#reading-from-a-null-file-pointer","text":"Reading from a null FILE pointer is undefined behavior and yields a runtime assertion. This can happen when calling std :: fopen on a nonexistent file. Example 4: Uninitialized iterator The following code will trigger an assertion at runtime: #include using json = nlohmann :: json ; int main () { std :: FILE * f = std :: fopen ( \"nonexistent_file.json\" , \"r\" ); json j = json :: parse ( f ); } Output: Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55.","title":"Reading from a null FILE pointer"},{"location":"features/binary_values/","text":"Binary Values \u00b6 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. API for binary values \u00b6 By default, binary values are stored as std::vector . This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t : auto binary = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }); auto binary_with_subtype = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); There are several convenience functions to check and set the subtype: binary . has_subtype (); // returns false binary_with_subtype . has_subtype (); // returns true binary_with_subtype . clear_subtype (); binary_with_subtype . has_subtype (); // returns true binary_with_subtype . set_subtype ( 42 ); binary . set_subtype ( 23 ); binary . subtype (); // returns 23 As json::binary_t is subclassing std::vector , all member functions are available: binary . size (); // returns 4 binary [ 1 ]; // returns 0xFE JSON values can be constructed from json::binary_t : json j = binary ; Binary values are primitive values just like numbers or strings: j . is_binary (); // returns true j . is_primitive (); // returns true Given a binary JSON value, the binary_t can be accessed by reference as via get_binary() : j . get_binary (). has_subtype (); // returns true j . get_binary (). size (); // returns 4 For convenience, binary JSON values can be constructed via json::binary : auto j2 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 23 ); auto j3 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }); j2 == j ; // returns true j3 . get_binary (). has_subtype (); // returns false j3 . get_binary (). subtype (); // returns std::uint64_t(-1) as j3 has no subtype Serialization \u00b6 Binary values are serialized differently according to the formats. JSON \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // serialize to standard output std :: cout << j . dump ( 2 ) << std :: endl ; Output: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } No roundtrip for binary values The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes. BJData \u00b6 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) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BJData auto v = json :: to_bjdata ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_bjdata ( j , true , true ); The resulting vector has 22 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' array 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] } BSON \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BSON auto v = json :: to_bson ( j ); v is a std::vector with the following 22 elements: 0x16 0x00 0x00 0x00 // number of bytes in the document 0x05 // binary value 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte 0x04 0x00 0x00 0x00 // number of bytes 0x2a // subtype 0xCA 0xFE 0xBA 0xBE // content 0x00 // end of the document Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } CBOR \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to CBOR auto v = json :: to_cbor ( j ); v is a std::vector with the following 15 elements: 0xA1 // map(1) 0x66 // text(6) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD8 0x2A // tag(42) 0x44 // bytes(4) 0xCA 0xFE 0xBA 0xBE // content 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 . { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : null } } MessagePack \u00b6 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 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to MessagePack auto v = json :: to_msgpack ( j ); v is a std::vector with the following 14 elements: 0x81 // fixmap1 0xA6 // fixstr6 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD6 // fixext4 0x2A // subtype 0xCA 0xFE 0xBA 0xBE // content Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } UBJSON \u00b6 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) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to UBJSON auto v = json :: to_ubjson ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_ubjson ( j , true , true ); The resulting vector has 23 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x24 // '$' type of the object elements 0x5B // '[' array 0x23 0x69 0x01 // '#' i 1 number of object elements 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] }","title":"Binary Values"},{"location":"features/binary_values/#binary-values","text":"The library implements several binary formats that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored. JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.","title":"Binary Values"},{"location":"features/binary_values/#api-for-binary-values","text":"By default, binary values are stored as std::vector . This type can be changed by providing a template parameter to the basic_json type. To store binary subtypes, the storage type is extended and exposed as json::binary_t : auto binary = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }); auto binary_with_subtype = json :: binary_t ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); There are several convenience functions to check and set the subtype: binary . has_subtype (); // returns false binary_with_subtype . has_subtype (); // returns true binary_with_subtype . clear_subtype (); binary_with_subtype . has_subtype (); // returns true binary_with_subtype . set_subtype ( 42 ); binary . set_subtype ( 23 ); binary . subtype (); // returns 23 As json::binary_t is subclassing std::vector , all member functions are available: binary . size (); // returns 4 binary [ 1 ]; // returns 0xFE JSON values can be constructed from json::binary_t : json j = binary ; Binary values are primitive values just like numbers or strings: j . is_binary (); // returns true j . is_primitive (); // returns true Given a binary JSON value, the binary_t can be accessed by reference as via get_binary() : j . get_binary (). has_subtype (); // returns true j . get_binary (). size (); // returns 4 For convenience, binary JSON values can be constructed via json::binary : auto j2 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 23 ); auto j3 = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }); j2 == j ; // returns true j3 . get_binary (). has_subtype (); // returns false j3 . get_binary (). subtype (); // returns std::uint64_t(-1) as j3 has no subtype","title":"API for binary values"},{"location":"features/binary_values/#serialization","text":"Binary values are serialized differently according to the formats.","title":"Serialization"},{"location":"features/binary_values/#json","text":"JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: bytes holds an array of integers, and subtype is an integer or null . Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // serialize to standard output std :: cout << j . dump ( 2 ) << std :: endl ; Output: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } } No roundtrip for binary values The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes.","title":"JSON"},{"location":"features/binary_values/#bjdata","text":"BJData neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library. Example Code: // create a binary value of subtype 42 (will be ignored in BJData) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BJData auto v = json :: to_bjdata ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_bjdata ( j , true , true ); The resulting vector has 22 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' array 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] }","title":"BJData"},{"location":"features/binary_values/#bson","text":"BSON supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used. Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to BSON auto v = json :: to_bson ( j ); v is a std::vector with the following 22 elements: 0x16 0x00 0x00 0x00 // number of bytes in the document 0x05 // binary value 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key \"binary\" + null byte 0x04 0x00 0x00 0x00 // number of bytes 0x2a // subtype 0xCA 0xFE 0xBA 0xBE // content 0x00 // end of the document Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } }","title":"BSON"},{"location":"features/binary_values/#cbor","text":"CBOR supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array. Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to CBOR auto v = json :: to_cbor ( j ); v is a std::vector with the following 15 elements: 0xA1 // map(1) 0x66 // text(6) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD8 0x2A // tag(42) 0x44 // bytes(4) 0xCA 0xFE 0xBA 0xBE // content 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 . { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : null } }","title":"CBOR"},{"location":"features/binary_values/#messagepack","text":"MessagePack supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer. If no subtype is given, the bin family (bin8, bin16, bin32) is used. Example Code: // create a binary value of subtype 42 json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to MessagePack auto v = json :: to_msgpack ( j ); v is a std::vector with the following 14 elements: 0x81 // fixmap1 0xA6 // fixstr6 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0xD6 // fixext4 0x2A // subtype 0xCA 0xFE 0xBA 0xBE // content Note that the serialization preserves the subtype, and deserializing v would yield the following value: { \"binary\" : { \"bytes\" : [ 202 , 254 , 186 , 190 ], \"subtype\" : 42 } }","title":"MessagePack"},{"location":"features/binary_values/#ubjson","text":"UBJSON neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library. Example Code: // create a binary value of subtype 42 (will be ignored in UBJSON) json j ; j [ \"binary\" ] = json :: binary ({ 0xCA , 0xFE , 0xBA , 0xBE }, 42 ); // convert to UBJSON auto v = json :: to_ubjson ( j ); v is a std::vector with the following 20 elements: 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for UBJSON: // convert to UBJSON using the size and type optimization auto v = json :: to_ubjson ( j , true , true ); The resulting vector has 23 elements; the optimization is not effective for examples with few values: 0x7B // '{' 0x24 // '$' type of the object elements 0x5B // '[' array 0x23 0x69 0x01 // '#' i 1 number of object elements 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // \"binary\" 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content Note that subtype (42) is not serialized and that UBJSON has no binary type , and deserializing v would yield the following value: { \"binary\" : [ 202 , 254 , 186 , 190 ] }","title":"UBJSON"},{"location":"features/comments/","text":"Comments \u00b6 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. Example Consider the following JSON with comments. { // update in 2006: removed Pluto \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" /*, \"Pluto\" */ ] } When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true , the comments are ignored during parsing: #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { std :: string s = R \" ( { // update in 2006: removed Pluto \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */] } ) \" ; try { json j = json :: parse ( s ); } catch ( json :: exception & e ) { std :: cout << e . what () << std :: endl ; } json j = json :: parse ( s , /* callback */ nullptr , /* allow exceptions */ true , /* ignore_comments */ true ); std :: cout << j . dump ( 2 ) << '\\n' ; } Output: [json.exception.parse_error.101] parse error at line 3, column 9: syntax error while parsing object key - invalid literal; last read: ' { /'; expected string literal { \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" ] }","title":"Comments"},{"location":"features/comments/#comments","text":"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. Example Consider the following JSON with comments. { // update in 2006: removed Pluto \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" /*, \"Pluto\" */ ] } When calling parse without additional argument, a parse error exception is thrown. If ignore_comments is set to true , the comments are ignored during parsing: #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { std :: string s = R \" ( { // update in 2006: removed Pluto \"planets\": [\"Mercury\", \"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Uranus\", \"Neptune\" /*, \"Pluto\" */] } ) \" ; try { json j = json :: parse ( s ); } catch ( json :: exception & e ) { std :: cout << e . what () << std :: endl ; } json j = json :: parse ( s , /* callback */ nullptr , /* allow exceptions */ true , /* ignore_comments */ true ); std :: cout << j . dump ( 2 ) << '\\n' ; } Output: [json.exception.parse_error.101] parse error at line 3, column 9: syntax error while parsing object key - invalid literal; last read: ' { /'; expected string literal { \"planets\" : [ \"Mercury\" , \"Venus\" , \"Earth\" , \"Mars\" , \"Jupiter\" , \"Uranus\" , \"Neptune\" ] }","title":"Comments"},{"location":"features/enum_conversion/","text":"Specializing enum conversion \u00b6 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 enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 , }; // map TaskState values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" }, }) 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. Usage \u00b6 // enum to JSON as string json j = TS_STOPPED ; assert ( j == \"stopped\" ); // json string to enum json j3 = \"running\" ; assert ( j3 . template get < TaskState > () == TS_RUNNING ); // undefined json value to enum (where the first map entry above is the default) json jPi = 3.14 ; assert ( jPi . template get < TaskState > () == TS_INVALID ); Notes \u00b6 Just as in Arbitrary Type Conversions above, NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization. It MUST be available (e.g., proper headers must be included) everywhere you use the conversions. Other Important points: When using template get() , 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 .","title":"Specializing enum conversion"},{"location":"features/enum_conversion/#specializing-enum-conversion","text":"By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended. It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below: // example enum type declaration enum TaskState { TS_STOPPED , TS_RUNNING , TS_COMPLETED , TS_INVALID = -1 , }; // map TaskState values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM ( TaskState , { { TS_INVALID , nullptr }, { TS_STOPPED , \"stopped\" }, { TS_RUNNING , \"running\" }, { TS_COMPLETED , \"completed\" }, }) 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.","title":"Specializing enum conversion"},{"location":"features/enum_conversion/#usage","text":"// enum to JSON as string json j = TS_STOPPED ; assert ( j == \"stopped\" ); // json string to enum json j3 = \"running\" ; assert ( j3 . template get < TaskState > () == TS_RUNNING ); // undefined json value to enum (where the first map entry above is the default) json jPi = 3.14 ; assert ( jPi . template get < TaskState > () == TS_INVALID );","title":"Usage"},{"location":"features/enum_conversion/#notes","text":"Just as in Arbitrary Type Conversions above, NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization. It MUST be available (e.g., proper headers must be included) everywhere you use the conversions. Other Important points: When using template get() , 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 .","title":"Notes"},{"location":"features/iterators/","text":"Iterators \u00b6 Overview \u00b6 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() . Iteration order for objects \u00b6 When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less . See the types documentation for more information. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 1 3 2 The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\". Access object key during iteration \u00b6 The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << it . key () << \" : \" << it . value () << std :: endl ; } Output: o ne : 1 t hree : 3 t wo : 2 Range-based for loops \u00b6 C++11 allows using range-based for loops to iterate over a container. for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\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 ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; } Note When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string. Warning Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information. Reverse iteration order \u00b6 rbegin() and rend() return iterators in the reverse sequence. Example json j = { 1 , 2 , 3 , 4 }; for ( auto it = j . rbegin (); it != j . rend (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 4 3 2 1 Iterating strings and binary values \u00b6 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\" ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: \"Hello, world\" Iterator invalidation \u00b6 Operations invalidated iterators clear all","title":"Iterators"},{"location":"features/iterators/#iterators","text":"","title":"Iterators"},{"location":"features/iterators/#overview","text":"A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values. As for other containers, begin() returns an iterator to the first value and end() returns an iterator to the value following the last value. The latter iterator is a placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, begin() will return end() .","title":"Overview"},{"location":"features/iterators/#iteration-order-for-objects","text":"When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less . See the types documentation for more information. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 1 3 2 The reason for the order is the lexicographic ordering of the object keys \"one\", \"three\", \"two\".","title":"Iteration order for objects"},{"location":"features/iterators/#access-object-key-during-iteration","text":"The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown. Example // create JSON object {\"one\": 1, \"two\": 2, \"three\": 3} json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << it . key () << \" : \" << it . value () << std :: endl ; } Output: o ne : 1 t hree : 3 t wo : 2","title":"Access object key during iteration"},{"location":"features/iterators/#range-based-for-loops","text":"C++11 allows using range-based for loops to iterate over a container. for ( auto it : j_object ) { // \"it\" is of type json::reference and has no key() member std :: cout << \"value: \" << it << '\\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 ()) { std :: cout << \"key: \" << el . key () << \", value:\" << el . value () << '\\n' ; } The items() function also allows using structured bindings (C++17): for ( auto & [ key , val ] : j_object . items ()) { std :: cout << \"key: \" << key << \", value:\" << val << '\\n' ; } Note When iterating over an array, key() will return the index of the element as string. For primitive types (e.g., numbers), key() returns an empty string. Warning Using items() on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See https://github.com/nlohmann/json/issues/2040 for more information.","title":"Range-based for loops"},{"location":"features/iterators/#reverse-iteration-order","text":"rbegin() and rend() return iterators in the reverse sequence. Example json j = { 1 , 2 , 3 , 4 }; for ( auto it = j . rbegin (); it != j . rend (); ++ it ) { std :: cout << * it << std :: endl ; } Output: 4 3 2 1","title":"Reverse iteration order"},{"location":"features/iterators/#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\" ; for ( auto it = j . begin (); it != j . end (); ++ it ) { std :: cout << * it << std :: endl ; } Output: \"Hello, world\"","title":"Iterating strings and binary values"},{"location":"features/iterators/#iterator-invalidation","text":"Operations invalidated iterators clear all","title":"Iterator invalidation"},{"location":"features/json_patch/","text":"JSON Patch and Diff \u00b6 Patches \u00b6 JSON Patch ( RFC 6902 ) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] } Diff \u00b6 The library can also calculate a JSON patch (i.e., a diff ) given two JSON values. Invariant For two JSON values source and target , the following code yields always true: source.patch(diff(source, target)) == target; Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"JSON Patch and Diff"},{"location":"features/json_patch/#json-patch-and-diff","text":"","title":"JSON Patch and Diff"},{"location":"features/json_patch/#patches","text":"JSON Patch ( RFC 6902 ) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the patch function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. Example The following code shows how a JSON patch is applied to a value. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json doc = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the patch json patch = R \" ( [ { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }, { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] }, { \"op\": \"remove\", \"path\": \"/foo\"} ] ) \" _json ; // apply the patch json patched_doc = doc . patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << doc << \" \\n\\n \" << std :: setw ( 4 ) << patched_doc << std :: endl ; } Output: { \"baz\" : \"qux\" , \"foo\" : \"bar\" } { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Patches"},{"location":"features/json_patch/#diff","text":"The library can also calculate a JSON patch (i.e., a diff ) given two JSON values. Invariant For two JSON values source and target , the following code yields always true: source.patch(diff(source, target)) == target; Example The following code shows how a JSON patch is created as a diff for two JSON values. #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the source document json source = R \" ( { \"baz\": \"qux\", \"foo\": \"bar\" } ) \" _json ; // the target document json target = R \" ( { \"baz\": \"boo\", \"hello\": [ \"world\" ] } ) \" _json ; // create the patch json patch = json :: diff ( source , target ); // roundtrip json patched_source = source . patch ( patch ); // output patch and roundtrip result std :: cout << std :: setw ( 4 ) << patch << \" \\n\\n \" << std :: setw ( 4 ) << patched_source << std :: endl ; } Output: [ { \"op\" : \"replace\" , \"path\" : \"/baz\" , \"value\" : \"boo\" }, { \"op\" : \"remove\" , \"path\" : \"/foo\" }, { \"op\" : \"add\" , \"path\" : \"/hello\" , \"value\" : [ \"world\" ] } ] { \"baz\" : \"boo\" , \"hello\" : [ \"world\" ] }","title":"Diff"},{"location":"features/json_pointer/","text":"JSON Pointer \u00b6 Introduction \u00b6 The library supports JSON Pointer ( RFC 6901 ) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document. Consider the following JSON document { \"array\" : [ \"A\" , \"B\" , \"C\" ], \"nested\" : { \"one\" : 1 , \"two\" : 2 , \"three\" : [ true , false ] } } Then every value inside the JSON document can be identified as follows: JSON Pointer JSON value `` { \"array\" :[ \"A\" , \"B\" , \"C\" ], \"nested\" :{ \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]}} /array [ \"A\" , \"B\" , \"C\" ] /array/0 A /array/1 B /array/2 C /nested { \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]} /nested/one 1 /nested/two 2 /nested/three [ true , false ] /nested/three/0 true /nested/three/1 false Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\" . See RFC 6901 for more information. JSON Pointer creation \u00b6 JSON Pointers can be created from a string: json :: json_pointer p = \"/nested/one\" ; Furthermore, a user-defined string literal can be used to achieve the same result: auto p = \"/nested/one\" _json_pointer ; The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information. Value access \u00b6 JSON Pointers can be used in the at , operator[] , and value functions just like object keys or array indices. // the JSON value from above auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // access values auto val = j [ \"/\" _json_pointer ]; // {\"array\":[\"A\",\"B\",\"C\"],...} auto val1 = j [ \"/nested/one\" _json_pointer ]; // 1 auto val2 = j . at [ json :: json_pointer ( \"/nested/three/1\" )]; // false auto val3 = j . value [ json :: json_pointer ( \"/nested/four\" , 0 )]; // 0 Flatten / unflatten \u00b6 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 auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // create flattened value auto j_flat = j . flatten (); The resulting value j_flat is: { \"/array/0\" : \"A\" , \"/array/1\" : \"B\" , \"/array/2\" : \"C\" , \"/nested/one\" : 1 , \"/nested/two\" : 2 , \"/nested/three/0\" : true , \"/nested/three/1\" : false } The reverse function, unflatten recreates the original value. auto j_original = j_flat . unflatten (); See also \u00b6 Class json_pointer Function flatten Function unflatten JSON Patch","title":"JSON Pointer"},{"location":"features/json_pointer/#json-pointer","text":"","title":"JSON Pointer"},{"location":"features/json_pointer/#introduction","text":"The library supports JSON Pointer ( RFC 6901 ) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document. Consider the following JSON document { \"array\" : [ \"A\" , \"B\" , \"C\" ], \"nested\" : { \"one\" : 1 , \"two\" : 2 , \"three\" : [ true , false ] } } Then every value inside the JSON document can be identified as follows: JSON Pointer JSON value `` { \"array\" :[ \"A\" , \"B\" , \"C\" ], \"nested\" :{ \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]}} /array [ \"A\" , \"B\" , \"C\" ] /array/0 A /array/1 B /array/2 C /nested { \"one\" : 1 , \"two\" : 2 , \"three\" :[ true , false ]} /nested/one 1 /nested/two 2 /nested/three [ true , false ] /nested/three/0 true /nested/three/1 false Note / does not identify the root (i.e., the whole document), but an object entry with empty key \"\" . See RFC 6901 for more information.","title":"Introduction"},{"location":"features/json_pointer/#json-pointer-creation","text":"JSON Pointers can be created from a string: json :: json_pointer p = \"/nested/one\" ; Furthermore, a user-defined string literal can be used to achieve the same result: auto p = \"/nested/one\" _json_pointer ; The escaping rules of RFC 6901 are implemented. See the constructor documentation for more information.","title":"JSON Pointer creation"},{"location":"features/json_pointer/#value-access","text":"JSON Pointers can be used in the at , operator[] , and value functions just like object keys or array indices. // the JSON value from above auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // access values auto val = j [ \"/\" _json_pointer ]; // {\"array\":[\"A\",\"B\",\"C\"],...} auto val1 = j [ \"/nested/one\" _json_pointer ]; // 1 auto val2 = j . at [ json :: json_pointer ( \"/nested/three/1\" )]; // false auto val3 = j . value [ json :: json_pointer ( \"/nested/four\" , 0 )]; // 0","title":"Value access"},{"location":"features/json_pointer/#flatten-unflatten","text":"The library implements a function flatten to convert any JSON document into a JSON object where each key is a JSON Pointer and each value is a primitive JSON value (i.e., a string, boolean, number, or null). // the JSON value from above auto j = json :: parse ( R \" ( { \"array\": [\"A\", \"B\", \"C\"], \"nested\": { \"one\": 1, \"two\": 2, \"three\": [true, false] } } ) \" ); // create flattened value auto j_flat = j . flatten (); The resulting value j_flat is: { \"/array/0\" : \"A\" , \"/array/1\" : \"B\" , \"/array/2\" : \"C\" , \"/nested/one\" : 1 , \"/nested/two\" : 2 , \"/nested/three/0\" : true , \"/nested/three/1\" : false } The reverse function, unflatten recreates the original value. auto j_original = j_flat . unflatten ();","title":"Flatten / unflatten"},{"location":"features/json_pointer/#see-also","text":"Class json_pointer Function flatten Function unflatten JSON Patch","title":"See also"},{"location":"features/macros/","text":"Supported Macros \u00b6 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. JSON_ASSERT(x) \u00b6 This macro controls which code is executed for runtime assertions of the library. See full documentation of JSON_ASSERT(x) . JSON_CATCH_USER(exception) \u00b6 This macro overrides catch calls inside the library. See full documentation of JSON_CATCH_USER(exception) . JSON_DIAGNOSTICS \u00b6 This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default). When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead. The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which sets JSON_DIAGNOSTICS accordingly. See full documentation of JSON_DIAGNOSTICS . JSON_HAS_CPP_11 , JSON_HAS_CPP_14 , JSON_HAS_CPP_17 , JSON_HAS_CPP_20 \u00b6 The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly. See full documentation of JSON_HAS_CPP_11 , JSON_HAS_CPP_14 , JSON_HAS_CPP_17 , and JSON_HAS_CPP_20 . JSON_HAS_FILESYSTEM , JSON_HAS_EXPERIMENTAL_FILESYSTEM \u00b6 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 / std::filesystem ( JSON_HAS_FILESYSTEM ) or / std::experimental::filesystem ( JSON_HAS_EXPERIMENTAL_FILESYSTEM ) should be used. To override the built-in check, define JSON_HAS_FILESYSTEM or JSON_HAS_EXPERIMENTAL_FILESYSTEM to 1 . See full documentation of JSON_HAS_FILESYSTEM and JSON_HAS_EXPERIMENTAL_FILESYSTEM . JSON_NOEXCEPTION \u00b6 Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION . See full documentation of JSON_NOEXCEPTION . JSON_DISABLE_ENUM_SERIALIZATION \u00b6 When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM . See full documentation of JSON_DISABLE_ENUM_SERIALIZATION . JSON_NO_IO \u00b6 When defined, headers , , , , and are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)). See full documentation of JSON_NO_IO . JSON_SKIP_LIBRARY_VERSION_CHECK \u00b6 When defined, the library will not create a compiler warning when a different version of the library was already included. See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK . JSON_SKIP_UNSUPPORTED_COMPILER_CHECK \u00b6 When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used. See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK . JSON_THROW_USER(exception) \u00b6 This macro overrides throw calls inside the library. The argument is the exception to be thrown. See full documentation of JSON_THROW_USER(exception) . JSON_TRY_USER \u00b6 This macro overrides try calls inside the library. See full documentation of JSON_TRY_USER . JSON_USE_IMPLICIT_CONVERSIONS \u00b6 When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. See full documentation of JSON_USE_IMPLICIT_CONVERSIONS . NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) \u00b6 This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE , it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE . NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) \u00b6 This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT . NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) \u00b6 This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) \u00b6 This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT . NLOHMANN_JSON_SERIALIZE_ENUM(type, ...) \u00b6 This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information. See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM . NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , NLOHMANN_JSON_VERSION_PATCH \u00b6 These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 . See full documentation of NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH .","title":"Supported Macros"},{"location":"features/macros/#supported-macros","text":"Some aspects of the library can be configured by defining preprocessor macros before including the json.hpp header. See also the API documentation for macros for examples and more information.","title":"Supported Macros"},{"location":"features/macros/#json_assertx","text":"This macro controls which code is executed for runtime assertions of the library. See full documentation of JSON_ASSERT(x) .","title":"JSON_ASSERT(x)"},{"location":"features/macros/#json_catch_userexception","text":"This macro overrides catch calls inside the library. See full documentation of JSON_CATCH_USER(exception) .","title":"JSON_CATCH_USER(exception)"},{"location":"features/macros/#json_diagnostics","text":"This macro enables extended diagnostics for exception messages. Possible values are 1 to enable or 0 to disable (default). When enabled, exception messages contain a JSON Pointer to the JSON value that triggered the exception, see Extended diagnostic messages for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead. The diagnostics messages can also be controlled with the CMake option JSON_Diagnostics ( OFF by default) which sets JSON_DIAGNOSTICS accordingly. See full documentation of JSON_DIAGNOSTICS .","title":"JSON_DIAGNOSTICS"},{"location":"features/macros/#json_has_cpp_11-json_has_cpp_14-json_has_cpp_17-json_has_cpp_20","text":"The library targets C++11, but also supports some features introduced in later C++ versions (e.g., std::string_view support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly. See full documentation of JSON_HAS_CPP_11 , JSON_HAS_CPP_14 , JSON_HAS_CPP_17 , and JSON_HAS_CPP_20 .","title":"JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20"},{"location":"features/macros/#json_has_filesystem-json_has_experimental_filesystem","text":"When compiling with C++17, the library provides conversions from and to std::filesystem::path . As compiler support for filesystem is limited, the library tries to detect whether / std::filesystem ( JSON_HAS_FILESYSTEM ) or / 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 .","title":"JSON_HAS_FILESYSTEM, JSON_HAS_EXPERIMENTAL_FILESYSTEM"},{"location":"features/macros/#json_noexception","text":"Exceptions can be switched off by defining the symbol JSON_NOEXCEPTION . See full documentation of JSON_NOEXCEPTION .","title":"JSON_NOEXCEPTION"},{"location":"features/macros/#json_disable_enum_serialization","text":"When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using NLOHMANN_JSON_SERIALIZE_ENUM . See full documentation of JSON_DISABLE_ENUM_SERIALIZATION .","title":"JSON_DISABLE_ENUM_SERIALIZATION"},{"location":"features/macros/#json_no_io","text":"When defined, headers , , , , and are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)). See full documentation of JSON_NO_IO .","title":"JSON_NO_IO"},{"location":"features/macros/#json_skip_library_version_check","text":"When defined, the library will not create a compiler warning when a different version of the library was already included. See full documentation of JSON_SKIP_LIBRARY_VERSION_CHECK .","title":"JSON_SKIP_LIBRARY_VERSION_CHECK"},{"location":"features/macros/#json_skip_unsupported_compiler_check","text":"When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used. See full documentation of JSON_SKIP_UNSUPPORTED_COMPILER_CHECK .","title":"JSON_SKIP_UNSUPPORTED_COMPILER_CHECK"},{"location":"features/macros/#json_throw_userexception","text":"This macro overrides throw calls inside the library. The argument is the exception to be thrown. See full documentation of JSON_THROW_USER(exception) .","title":"JSON_THROW_USER(exception)"},{"location":"features/macros/#json_try_user","text":"This macro overrides try calls inside the library. See full documentation of JSON_TRY_USER .","title":"JSON_TRY_USER"},{"location":"features/macros/#json_use_implicit_conversions","text":"When defined to 0 , implicit conversions are switched off. By default, implicit conversions are switched on. See full documentation of JSON_USE_IMPLICIT_CONVERSIONS .","title":"JSON_USE_IMPLICIT_CONVERSIONS"},{"location":"features/macros/#nlohmann_define_type_intrusivetype-member","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE , it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE .","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)"},{"location":"features/macros/#nlohmann_define_type_intrusive_with_defaulttype-member","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT .","title":"NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)"},{"location":"features/macros/#nlohmann_define_type_non_intrusivetype-member","text":"This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use NLOHMANN_DEFINE_TYPE_INTRUSIVE in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE .","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)"},{"location":"features/macros/#nlohmann_define_type_non_intrusive_with_defaulttype-member","text":"This macro is similar to NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE . It will not throw an exception in from_json() due to a missing value in the JSON object, but can throw due to a mismatched type. The from_json() function default constructs an object and uses its values as the defaults when calling the value function. See full documentation of NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT .","title":"NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)"},{"location":"features/macros/#nlohmann_json_serialize_enumtype","text":"This macro simplifies the serialization/deserialization of enum types. See Specializing enum conversion for more information. See full documentation of NLOHMANN_JSON_SERIALIZE_ENUM .","title":"NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)"},{"location":"features/macros/#nlohmann_json_version_major-nlohmann_json_version_minor-nlohmann_json_version_patch","text":"These macros are defined by the library and contain the version numbers according to Semantic Versioning 2.0.0 . See full documentation of NLOHMANN_JSON_VERSION_MAJOR , NLOHMANN_JSON_VERSION_MINOR , and NLOHMANN_JSON_VERSION_PATCH .","title":"NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH"},{"location":"features/merge_patch/","text":"JSON Merge Patch \u00b6 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 #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" }","title":"JSON Merge Patch"},{"location":"features/merge_patch/#json-merge-patch","text":"The library supports JSON Merge Patch ( RFC 7386 ) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value. Instead of using JSON Pointer to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified. Example The following code shows how a JSON Merge Patch is applied to a JSON document. #include #include #include // for std::setw using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // the original document json document = R \" ( { \"title\": \"Goodbye!\", \"author\": { \"givenName\": \"John\", \"familyName\": \"Doe\" }, \"tags\": [ \"example\", \"sample\" ], \"content\": \"This will be unchanged\" } ) \" _json ; // the patch json patch = R \" ( { \"title\": \"Hello!\", \"phoneNumber\": \"+01-123-456-7890\", \"author\": { \"familyName\": null }, \"tags\": [ \"example\" ] } ) \" _json ; // apply the patch document . merge_patch ( patch ); // output original and patched document std :: cout << std :: setw ( 4 ) << document << std :: endl ; } Output: { \"author\" : { \"givenName\" : \"John\" }, \"content\" : \"This will be unchanged\" , \"phoneNumber\" : \"+01-123-456-7890\" , \"tags\" : [ \"example\" ], \"title\" : \"Hello!\" }","title":"JSON Merge Patch"},{"location":"features/namespace/","text":"nlohmann Namespace \u00b6 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. Structure \u00b6 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: nlohmann :: json_abi_diag_v3_11_2 Purpose \u00b6 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. Limitations \u00b6 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. Disabling the version component \u00b6 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! Disabling the inline namespace completely \u00b6 When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows: #define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann { #define NLOHMANN_JSON_NAMESPACE_END } Use at your own risk Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned! Version history \u00b6 Introduced inline namespace ( json_v3_11_0[_abi-tag]* ) in version 3.11.0. Changed structure of inline namespace in version 3.11.2.","title":"nlohmann Namespace"},{"location":"features/namespace/#nlohmann-namespace","text":"The 3.11.0 release introduced an inline namespace to allow different parts of a codebase to safely use different versions of the JSON library as long as they never exchange instances of library types.","title":"nlohmann Namespace"},{"location":"features/namespace/#structure","text":"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: nlohmann :: json_abi_diag_v3_11_2","title":"Structure"},{"location":"features/namespace/#purpose","text":"Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of JSON_DIAGNOSTICS . This is illustrated in the diagram below. In releases prior to 3.11.0, mixing any version of the JSON library with different JSON_DIAGNOSTICS settings would result in a crashing application. If some_library never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names.","title":"Purpose"},{"location":"features/namespace/#limitations","text":"Neither the compiler nor the linker will issue as much as a warning when translation units \u2013 intended to be linked together and that include different versions and/or configurations of the JSON library \u2013 exchange and use library types. There is an exception when forward declarations are used (i.e., when including json_fwd.hpp ) in which case the linker may complain about undefined references.","title":"Limitations"},{"location":"features/namespace/#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!","title":"Disabling the version component"},{"location":"features/namespace/#disabling-the-inline-namespace-completely","text":"When interoperability with code using a pre-3.11.0 version of the library is required, users can, at their own risk restore the old namespace layout by redefining NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END as follows: #define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann { #define NLOHMANN_JSON_NAMESPACE_END } Use at your own risk Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned!","title":"Disabling the inline namespace completely"},{"location":"features/namespace/#version-history","text":"Introduced inline namespace ( json_v3_11_0[_abi-tag]* ) in version 3.11.0. Changed structure of inline namespace in version 3.11.2.","title":"Version history"},{"location":"features/object_order/","text":"Object Order \u00b6 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. Default behavior: sort keys \u00b6 The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically . Example #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 } Alternative behavior: preserve insertion order \u00b6 If you do want to preserve the insertion order , you can try the type nlohmann::ordered_json . Example #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map ( integration ) or nlohmann::fifo_map ( integration ). Notes on parsing \u00b6 Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Right way The following code correctly calls the parse function from nlohmann::ordered_json : std :: ifstream i ( \"input.json\" ); auto j = nlohmann :: ordered_json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Wrong way The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file. std :: ifstream i ( \"input.json\" ); nlohmann :: ordered_json j = nlohmann :: json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"three\" : 3 \"two\" : 2 , }","title":"Object Order"},{"location":"features/object_order/#object-order","text":"The JSON standard defines objects as \"an unordered collection of zero or more name/value pairs\". As such, an implementation does not need to preserve any specific order of object keys.","title":"Object Order"},{"location":"features/object_order/#default-behavior-sort-keys","text":"The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically . Example #include #include \"json.hpp\" using json = nlohmann :: json ; int main () { json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"three\" : 3 , \"two\" : 2 }","title":"Default behavior: sort keys"},{"location":"features/object_order/#alternative-behavior-preserve-insertion-order","text":"If you do want to preserve the insertion order , you can try the type nlohmann::ordered_json . Example #include #include using ordered_json = nlohmann :: ordered_json ; int main () { ordered_json j ; j [ \"one\" ] = 1 ; j [ \"two\" ] = 2 ; j [ \"three\" ] = 3 ; std :: cout << j . dump ( 2 ) << '\\n' ; } Output: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Alternatively, you can use a more sophisticated ordered map like tsl::ordered_map ( integration ) or nlohmann::fifo_map ( integration ).","title":"Alternative behavior: preserve insertion order"},{"location":"features/object_order/#notes-on-parsing","text":"Note that you also need to call the right parse function when reading from a file. Assume file input.json contains the JSON object above: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Right way The following code correctly calls the parse function from nlohmann::ordered_json : std :: ifstream i ( \"input.json\" ); auto j = nlohmann :: ordered_json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"two\" : 2 , \"three\" : 3 } Wrong way The following code incorrectly calls the parse function from nlohmann::json which does not preserve the insertion order, but sorts object keys. Assigning the result to nlohmann::ordered_json compiles, but does not restore the order from the input file. std :: ifstream i ( \"input.json\" ); nlohmann :: ordered_json j = nlohmann :: json :: parse ( i ); std :: cout << j . dump ( 2 ) << std :: endl ; The output will be: { \"one\" : 1 , \"three\" : 3 \"two\" : 2 , }","title":"Notes on parsing"},{"location":"features/binary_formats/","text":"Binary Formats \u00b6 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. Comparison \u00b6 Completeness \u00b6 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 Binary values \u00b6 Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported See binary values for more information. Sizes \u00b6 Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 % Sizes compared to minified JSON value.","title":"Binary Formats"},{"location":"features/binary_formats/#binary-formats","text":"Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports 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.","title":"Binary Formats"},{"location":"features/binary_formats/#comparison","text":"","title":"Comparison"},{"location":"features/binary_formats/#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","title":"Completeness"},{"location":"features/binary_formats/#binary-values","text":"Format Binary values Binary subtypes BJData not supported not supported BSON supported supported CBOR supported supported MessagePack supported supported UBJSON not supported not supported See binary values for more information.","title":"Binary values"},{"location":"features/binary_formats/#sizes","text":"Format canada.json twitter.json citm_catalog.json jeopardy.json BJData 53.2 % 91.1 % 78.1 % 96.6 % BJData (size) 58.6 % 92.1 % 86.7 % 97.4 % BJData (size+tyoe) 58.6 % 92.1 % 86.5 % 97.4 % BSON 85.8 % 95.2 % 95.8 % 106.7 % CBOR 50.5 % 86.3 % 68.4 % 88.0 % MessagePack 50.5 % 86.0 % 68.5 % 87.9 % UBJSON 53.2 % 91.3 % 78.2 % 96.6 % UBJSON (size) 58.6 % 92.3 % 86.8 % 97.4 % UBJSON (size+type) 55.9 % 92.3 % 85.0 % 95.0 % Sizes compared to minified JSON value.","title":"Sizes"},{"location":"features/binary_formats/bjdata/","text":"BJData \u00b6 The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays ( ND-arrays ); it also adds 4 new type markers - [u] - uint16 , [m] - uint32 , [M] - uint64 and [h] - float16 - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms. Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable . This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing. References BJData Specification Serialization \u00b6 The library uses the following mapping from JSON values types to BJData types according to the BJData specification: JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a BJData value. Any BJData output created by to_bjdata can be successfully parsed by from_bjdata . Size constraints The following values can not be converted to a BJData value: strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 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 { \"_ArrayType_\" : \"uint8\" , \"_ArraySize_\" : [ 2 , 3 ], \"_ArrayData_\" : [ 1 , 2 , 3 , 4 , 5 , 6 ] } Likewise, when a JSON object in the above form is serialzed using to_bjdata , it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated. The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array. Restrictions in optimized data types for arrays and objects Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of UiuImlMLhdDC . This also means other variable ( [{SH ) or zero-length types ( TFN ) can not be used in an optimized array or object in BJData. Binary values If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678 Deserialization \u00b6 The library maps BJData types to JSON value types as follows: BJData type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any BJData value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"BJData"},{"location":"features/binary_formats/bjdata/#bjdata","text":"The BJData format was derived from and improved upon Universal Binary JSON(UBJSON) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays ( ND-arrays ); it also adds 4 new type markers - [u] - uint16 , [m] - uint32 , [M] - uint64 and [h] - float16 - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms. Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and quasi-human-readable . This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing. References BJData Specification","title":"BJData"},{"location":"features/binary_formats/bjdata/#serialization","text":"The library uses the following mapping from JSON values types to BJData types according to the BJData specification: JSON value type value/range BJData type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..65535 uint16 u number_integer 65536..2147483647 int32 l number_integer 2147483648..4294967295 uint32 m number_integer 4294967296..9223372036854775807 int64 L number_integer 9223372036854775808..18446744073709551615 uint64 M number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..65535 uint16 u number_unsigned 65536..2147483647 int32 l number_unsigned 2147483648..4294967295 uint32 m number_unsigned 4294967296..9223372036854775807 int64 L number_unsigned 9223372036854775808..18446744073709551615 uint64 M number_float any value float64 D string with shortest length indicator string S array see notes on optimized format/ND-array array [ object see notes on optimized format map { Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a BJData value. Any BJData output created by to_bjdata can be successfully parsed by from_bjdata . Size constraints The following values can not be converted to a BJData value: strings with more than 18446744073709551615 bytes, i.e., 2^{64}-1 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 { \"_ArrayType_\" : \"uint8\" , \"_ArraySize_\" : [ 2 , 3 ], \"_ArrayData_\" : [ 1 , 2 , 3 , 4 , 5 , 6 ] } Likewise, when a JSON object in the above form is serialzed using to_bjdata , it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in \"_ArraySize_\" contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated. The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array. Restrictions in optimized data types for arrays and objects Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the $ marker in an optimized array and object container are restricted to non-zero-fixed-length data types. Therefore, the valid optimized type markers can only be one of UiuImlMLhdDC . This also means other variable ( [{SH ) or zero-length types ( TFN ) can not be used in an optimized array or object in BJData. Binary values If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print BJData's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to BJData std :: vector < std :: uint8_t > v = json :: to_bjdata ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to BJData using default representation std :: vector < std :: uint8_t > v_array = json :: to_bjdata ( array ); // serialize it to BJData using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_bjdata ( array , true ); // serialize it to BJData using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_bjdata ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678","title":"Serialization"},{"location":"features/binary_formats/bjdata/#deserialization","text":"The library maps BJData types to JSON value types as follows: BJData type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float16 number_float h float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i uint16 number_unsigned u int16 number_integer I uint32 number_unsigned m int32 number_integer l uint64 number_unsigned M int64 number_integer L string string S char string C array array (optimized values are supported) [ ND-array object (in JData annotated array format) [$.#[. object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any BJData value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with BJData json j = json :: from_bjdata ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/bson/","text":"BSON \u00b6 BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. References BSON Website - the main source on BSON BSON Specification - the specification Serialization \u00b6 The library uses the following mapping from JSON values types to BSON types: JSON value type value/range BSON type marker null null null 0x0A boolean true , false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 Incomplete mapping The mapping is incomplete , since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00 Deserialization \u00b6 The library maps BSON record types to JSON value types as follows: BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported Incomplete mapping The mapping is incomplete . The unsupported mappings are indicated in the table above. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"BSON"},{"location":"features/binary_formats/bson/#bson","text":"BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. References BSON Website - the main source on BSON BSON Specification - the specification","title":"BSON"},{"location":"features/binary_formats/bson/#serialization","text":"The library uses the following mapping from JSON values types to BSON types: JSON value type value/range BSON type marker null null null 0x0A boolean true , false boolean 0x08 number_integer -9223372036854775808..-2147483649 int64 0x12 number_integer -2147483648..2147483647 int32 0x10 number_integer 2147483648..9223372036854775807 int64 0x12 number_unsigned 0..2147483647 int32 0x10 number_unsigned 2147483648..9223372036854775807 int64 0x12 number_unsigned 9223372036854775808..18446744073709551615 -- -- number_float any value double 0x01 string any value string 0x02 array any value document 0x04 object any value document 0x03 binary any value binary 0x05 Incomplete mapping The mapping is incomplete , since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. Example #include #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to BSON std :: vector < std :: uint8_t > v = json :: to_bson ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x1b 0x00 0x00 0x00 0x08 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0x00 0x01 0x10 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 0x00 0x00 0x00 0x00 0x00","title":"Serialization"},{"location":"features/binary_formats/bson/#deserialization","text":"The library maps BSON record types to JSON value types as follows: BSON type BSON marker byte JSON value type double 0x01 number_float string 0x02 string document 0x03 object array 0x04 array binary 0x05 binary undefined 0x06 unsupported ObjectId 0x07 unsupported boolean 0x08 boolean UTC Date-Time 0x09 unsupported null 0x0A null Regular Expr. 0x0B unsupported DB Pointer 0x0C unsupported JavaScript Code 0x0D unsupported Symbol 0x0E unsupported JavaScript Code 0x0F unsupported int32 0x10 number_integer Timestamp 0x11 unsupported 128-bit decimal float 0x13 unsupported Max Key 0x7F unsupported Min Key 0xFF unsupported Incomplete mapping The mapping is incomplete . The unsupported mappings are indicated in the table above. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x1b , 0x00 , 0x00 , 0x00 , 0x08 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0x00 , 0x01 , 0x10 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; // deserialize it with BSON json j = json :: from_bson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/cbor/","text":"CBOR \u00b6 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 RFC 7049 - the CBOR specification Serialization \u00b6 The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification ( RFC 7049 ): JSON value type value/range CBOR type first byte null null Null 0xF6 boolean true True 0xF5 boolean false False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length : 0..23 UTF-8 string 0x60..0x77 string length : 23..255 UTF-8 string (1 byte follow) 0x78 string length : 256..65535 UTF-8 string (2 bytes follow) 0x79 string length : 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length : 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size : 0..23 array 0x80..0x97 array size : 23..255 array (1 byte follow) 0x98 array size : 256..65535 array (2 bytes follow) 0x99 array size : 65536..4294967295 array (4 bytes follow) 0x9A array size : 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size : 0..23 map 0xA0..0xB7 object size : 23..255 map (1 byte follow) 0xB8 object size : 256..65535 map (2 bytes follow) 0xB9 object size : 65536..4294967295 map (4 bytes follow) 0xBA object size : 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size : 0..23 byte string 0x40..0x57 binary size : 23..255 byte string (1 byte follow) 0x58 binary size : 256..65535 byte string (2 bytes follow) 0x59 binary size : 65536..4294967295 byte string (4 bytes follow) 0x5A binary size : 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above. Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a CBOR value. NaN/infinity handling If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to null . Unused CBOR types The following CBOR types are not used in the conversion: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 Deserialization \u00b6 The library maps CBOR types to JSON value types as follows: CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF False false 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB Incomplete mapping The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors: 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 . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"CBOR"},{"location":"features/binary_formats/cbor/#cbor","text":"The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation. References CBOR Website - the main source on CBOR CBOR Playground - an interactive webpage to translate between JSON and CBOR RFC 7049 - the CBOR specification","title":"CBOR"},{"location":"features/binary_formats/cbor/#serialization","text":"The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification ( RFC 7049 ): JSON value type value/range CBOR type first byte null null Null 0xF6 boolean true True 0xF5 boolean false False 0xF4 number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3B number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3A number_integer -32768..-129 Negative integer (2 bytes follow) 0x39 number_integer -128..-25 Negative integer (1 byte follow) 0x38 number_integer -24..-1 Negative integer 0x20..0x37 number_integer 0..23 Integer 0x00..0x17 number_integer 24..255 Unsigned integer (1 byte follow) 0x18 number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19 number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_unsigned 0..23 Integer 0x00..0x17 number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18 number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19 number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1A number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1B number_float any value representable by a float Single-Precision Float 0xFA number_float any value NOT representable by a float Double-Precision Float 0xFB string length : 0..23 UTF-8 string 0x60..0x77 string length : 23..255 UTF-8 string (1 byte follow) 0x78 string length : 256..65535 UTF-8 string (2 bytes follow) 0x79 string length : 65536..4294967295 UTF-8 string (4 bytes follow) 0x7A string length : 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7B array size : 0..23 array 0x80..0x97 array size : 23..255 array (1 byte follow) 0x98 array size : 256..65535 array (2 bytes follow) 0x99 array size : 65536..4294967295 array (4 bytes follow) 0x9A array size : 4294967296..18446744073709551615 array (8 bytes follow) 0x9B object size : 0..23 map 0xA0..0xB7 object size : 23..255 map (1 byte follow) 0xB8 object size : 256..65535 map (2 bytes follow) 0xB9 object size : 65536..4294967295 map (4 bytes follow) 0xBA object size : 4294967296..18446744073709551615 map (8 bytes follow) 0xBB binary size : 0..23 byte string 0x40..0x57 binary size : 23..255 byte string (1 byte follow) 0x58 binary size : 256..65535 byte string (2 bytes follow) 0x59 binary size : 65536..4294967295 byte string (4 bytes follow) 0x5A binary size : 4294967296..18446744073709551615 byte string (8 bytes follow) 0x5B Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see \"binary\" cells in the table above. Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a CBOR value. NaN/infinity handling If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to null . Unused CBOR types The following CBOR types are not used in the conversion: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to CBOR std :: vector < std :: uint8_t > v = json :: to_cbor ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00","title":"Serialization"},{"location":"features/binary_formats/cbor/#deserialization","text":"The library maps CBOR types to JSON value types as follows: CBOR type JSON value type first byte Integer number_unsigned 0x00..0x17 Unsigned integer number_unsigned 0x18 Unsigned integer number_unsigned 0x19 Unsigned integer number_unsigned 0x1A Unsigned integer number_unsigned 0x1B Negative integer number_integer 0x20..0x37 Negative integer number_integer 0x38 Negative integer number_integer 0x39 Negative integer number_integer 0x3A Negative integer number_integer 0x3B Byte string binary 0x40..0x57 Byte string binary 0x58 Byte string binary 0x59 Byte string binary 0x5A Byte string binary 0x5B UTF-8 string string 0x60..0x77 UTF-8 string string 0x78 UTF-8 string string 0x79 UTF-8 string string 0x7A UTF-8 string string 0x7B UTF-8 string string 0x7F array array 0x80..0x97 array array 0x98 array array 0x99 array array 0x9A array array 0x9B array array 0x9F map object 0xA0..0xB7 map object 0xB8 map object 0xB9 map object 0xBA map object 0xBB map object 0xBF False false 0xF4 True true 0xF5 Null null 0xF6 Half-Precision Float number_float 0xF9 Single-Precision Float number_float 0xFA Double-Precision Float number_float 0xFB Incomplete mapping The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors: 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 . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0xa2 , 0x67 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xf5 , 0x66 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with CBOR json j = json :: from_cbor ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/messagepack/","text":"MessagePack \u00b6 MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. References MessagePack website MessagePack specification Serialization \u00b6 The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type value/range MessagePack type first byte null null nil 0xC0 boolean true true 0xC3 boolean false false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length : 0..31 fixstr 0xA0..0xBF string length : 32..255 str 8 0xD9 string length : 256..65535 str 16 0xDA string length : 65536..4294967295 str 32 0xDB array size : 0..15 fixarray 0x90..0x9F array size : 16..65535 array 16 0xDC array size : 65536..4294967295 array 32 0xDD object size : 0..15 fix map 0x80..0x8F object size : 16..65535 map 16 0xDE object size : 65536..4294967295 map 32 0xDF binary size : 0..255 bin 8 0xC4 binary size : 256..65535 bin 16 0xC5 binary size : 65536..4294967295 bin 32 0xC6 Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value. Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Size constraints The following values can not be converted to a MessagePack value: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 Deserialization \u00b6 The library maps MessagePack types to JSON value types as follows: MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nil null 0xC0 false false 0xC2 true true 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF Info Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"MessagePack"},{"location":"features/binary_formats/messagepack/#messagepack","text":"MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. References MessagePack website MessagePack specification","title":"MessagePack"},{"location":"features/binary_formats/messagepack/#serialization","text":"The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type value/range MessagePack type first byte null null nil 0xC0 boolean true true 0xC3 boolean false false 0xC2 number_integer -9223372036854775808..-2147483649 int64 0xD3 number_integer -2147483648..-32769 int32 0xD2 number_integer -32768..-129 int16 0xD1 number_integer -128..-33 int8 0xD0 number_integer -32..-1 negative fixint 0xE0..0xFF number_integer 0..127 positive fixint 0x00..0x7F number_integer 128..255 uint 8 0xCC number_integer 256..65535 uint 16 0xCD number_integer 65536..4294967295 uint 32 0xCE number_integer 4294967296..18446744073709551615 uint 64 0xCF number_unsigned 0..127 positive fixint 0x00..0x7F number_unsigned 128..255 uint 8 0xCC number_unsigned 256..65535 uint 16 0xCD number_unsigned 65536..4294967295 uint 32 0xCE number_unsigned 4294967296..18446744073709551615 uint 64 0xCF number_float any value representable by a float float 32 0xCA number_float any value NOT representable by a float float 64 0xCB string length : 0..31 fixstr 0xA0..0xBF string length : 32..255 str 8 0xD9 string length : 256..65535 str 16 0xDA string length : 65536..4294967295 str 32 0xDB array size : 0..15 fixarray 0x90..0x9F array size : 16..65535 array 16 0xDC array size : 65536..4294967295 array 32 0xDD object size : 0..15 fix map 0x80..0x8F object size : 16..65535 map 16 0xDE object size : 65536..4294967295 map 32 0xDF binary size : 0..255 bin 8 0xC4 binary size : 256..65535 bin 16 0xC5 binary size : 65536..4294967295 bin 32 0xC6 Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value. Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Size constraints The following values can not be converted to a MessagePack value: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": 0} ) \" _json ; // serialize it to MessagePack std :: vector < std :: uint8_t > v = json :: to_msgpack ( j ); // print the vector content for ( auto & byte : v ) { std :: cout << \"0x\" << std :: hex << std :: setw ( 2 ) << std :: setfill ( '0' ) << ( int ) byte << \" \" ; } std :: cout << std :: endl ; } Output: 0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00","title":"Serialization"},{"location":"features/binary_formats/messagepack/#deserialization","text":"The library maps MessagePack types to JSON value types as follows: MessagePack type JSON value type first byte positive fixint number_unsigned 0x00..0x7F fixmap object 0x80..0x8F fixarray array 0x90..0x9F fixstr string 0xA0..0xBF nil null 0xC0 false false 0xC2 true true 0xC3 float 32 number_float 0xCA float 64 number_float 0xCB uint 8 number_unsigned 0xCC uint 16 number_unsigned 0xCD uint 32 number_unsigned 0xCE uint 64 number_unsigned 0xCF int 8 number_integer 0xD0 int 16 number_integer 0xD1 int 32 number_integer 0xD2 int 64 number_integer 0xD3 str 8 string 0xD9 str 16 string 0xDA str 32 string 0xDB array 16 array 0xDC array 32 array 0xDD map 16 object 0xDE map 32 object 0xDF bin 8 binary 0xC4 bin 16 binary 0xC5 bin 32 binary 0xC6 ext 8 binary 0xC7 ext 16 binary 0xC8 ext 32 binary 0xC9 fixext 1 binary 0xD4 fixext 2 binary 0xD5 fixext 4 binary 0xD6 fixext 8 binary 0xD7 fixext 16 binary 0xD8 negative fixint number_integer 0xE0-0xFF Info Any MessagePack output created by to_msgpack can be successfully parsed by from_msgpack . Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x82 , 0xa7 , 0x63 , 0x6f , 0x6d , 0x70 , 0x61 , 0x63 , 0x74 , 0xc3 , 0xa6 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6d , 0x61 , 0x00 }; // deserialize it with MessagePack json j = json :: from_msgpack ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/binary_formats/ubjson/","text":"UBJSON \u00b6 Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON. References UBJSON Website Serialization \u00b6 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678 Deserialization \u00b6 The library maps UBJSON types to JSON value types as follows: UBJSON type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any UBJSON value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"UBJSON"},{"location":"features/binary_formats/ubjson/#ubjson","text":"Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON. References UBJSON Website","title":"UBJSON"},{"location":"features/binary_formats/ubjson/#serialization","text":"The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification: JSON value type value/range UBJSON type marker null null null Z boolean true true T boolean false false F number_integer -9223372036854775808..-2147483649 int64 L number_integer -2147483648..-32769 int32 l number_integer -32768..-129 int16 I number_integer -128..127 int8 i number_integer 128..255 uint8 U number_integer 256..32767 int16 I number_integer 32768..2147483647 int32 l number_integer 2147483648..9223372036854775807 int64 L number_unsigned 0..127 int8 i number_unsigned 128..255 uint8 U number_unsigned 256..32767 int16 I number_unsigned 32768..2147483647 int32 l number_unsigned 2147483648..9223372036854775807 int64 L number_unsigned 2147483649..18446744073709551615 high-precision H number_float any value float64 D string with shortest length indicator string S array see notes on optimized format array [ object see notes on optimized format map { Complete mapping The mapping is complete in the sense that any JSON value type can be converted to a UBJSON value. Any UBJSON output created by to_ubjson can be successfully parsed by from_ubjson . Size constraints The following values can not be converted to a UBJSON value: 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 #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; // function to print UBJSON's diagnostic format void print_byte ( uint8_t byte ) { if ( 32 < byte and byte < 128 ) { std :: cout << ( char ) byte ; } else { std :: cout << ( int ) byte ; } } int main () { // create a JSON value json j = R \" ( {\"compact\": true, \"schema\": false} ) \" _json ; // serialize it to UBJSON std :: vector < std :: uint8_t > v = json :: to_ubjson ( j ); // print the vector content for ( auto & byte : v ) { print_byte ( byte ); } std :: cout << std :: endl ; // create an array of numbers json array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; // serialize it to UBJSON using default representation std :: vector < std :: uint8_t > v_array = json :: to_ubjson ( array ); // serialize it to UBJSON using size optimization std :: vector < std :: uint8_t > v_array_size = json :: to_ubjson ( array , true ); // serialize it to UBJSON using type optimization std :: vector < std :: uint8_t > v_array_size_and_type = json :: to_ubjson ( array , true , true ); // print the vector contents for ( auto & byte : v_array ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size ) { print_byte ( byte ); } std :: cout << std :: endl ; for ( auto & byte : v_array_size_and_type ) { print_byte ( byte ); } std :: cout << std :: endl ; } Output: { i7compactTi6schemaF } [ i1i2i3i4i5i6i7i8 ] [ # i8i1i2i3i4i5i6i7i8 [ $i # i812345678","title":"Serialization"},{"location":"features/binary_formats/ubjson/#deserialization","text":"The library maps UBJSON types to JSON value types as follows: UBJSON type JSON value type marker no-op no value, next value is read N null null Z false false F true true T float32 number_float d float64 number_float D uint8 number_unsigned U int8 number_integer i int16 number_integer I int32 number_integer l int64 number_integer L string string S char string C array array (optimized values are supported) [ object object (optimized values are supported) { Complete mapping The mapping is complete in the sense that any UBJSON value can be converted to a JSON value. Example #include #include #include using json = nlohmann :: json ; int main () { // create byte vector std :: vector < std :: uint8_t > v = { 0x7B , 0x69 , 0x07 , 0x63 , 0x6F , 0x6D , 0x70 , 0x61 , 0x63 , 0x74 , 0x54 , 0x69 , 0x06 , 0x73 , 0x63 , 0x68 , 0x65 , 0x6D , 0x61 , 0x69 , 0x00 , 0x7D }; // deserialize it with UBJSON json j = json :: from_ubjson ( v ); // print the deserialized JSON value std :: cout << std :: setw ( 2 ) << j << std :: endl ; } Output: { \"compact\" : true , \"schema\" : 0 }","title":"Deserialization"},{"location":"features/element_access/","text":"Element Access \u00b6 There are many ways elements in a JSON value can be accessed: unchecked access via operator[] checked access via at access with default value via value iterators JSON pointers","title":"Element Access"},{"location":"features/element_access/#element-access","text":"There are many ways elements in a JSON value can be accessed: unchecked access via operator[] checked access via at access with default value via value iterators JSON pointers","title":"Element Access"},{"location":"features/element_access/checked_access/","text":"Checked access: at \u00b6 Overview \u00b6 The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j . at ( \"name\" ) \"Mary Smith\" j . at ( \"age\" ) 42 j . at ( \"hobbies\" ) [ \"hiking\" , \"reading\" ] j . at ( \"hobbies\" ). at ( 0 ) \"hiking\" j . at ( \"hobbies\" ). at ( 1 ) \"reading\" The return value is a reference, so it can be modified by the original value. Write access j . at ( \"name\" ) = \"John Smith\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } 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\" ; This code produces the following exception: [json.exception.out_of_range.401] array index 3 is out of range 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 Notes \u00b6 Exceptions at can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown. basic_json::out_of_range exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid. Summary \u00b6 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","title":"Checked access: at"},{"location":"features/element_access/checked_access/#checked-access-at","text":"","title":"Checked access: at"},{"location":"features/element_access/checked_access/#overview","text":"The at member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a basic_json::out_of_range exception otherwise. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j . at ( \"name\" ) \"Mary Smith\" j . at ( \"age\" ) 42 j . at ( \"hobbies\" ) [ \"hiking\" , \"reading\" ] j . at ( \"hobbies\" ). at ( 0 ) \"hiking\" j . at ( \"hobbies\" ). at ( 1 ) \"reading\" The return value is a reference, so it can be modified by the original value. Write access j . at ( \"name\" ) = \"John Smith\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } 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\" ; This code produces the following exception: [json.exception.out_of_range.401] array index 3 is out of range 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","title":"Overview"},{"location":"features/element_access/checked_access/#notes","text":"Exceptions at can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a basic_json::type_error is thrown. basic_json::out_of_range exception exceptions are thrown if the provided key is not found in an object or the provided index is invalid.","title":"Notes"},{"location":"features/element_access/checked_access/#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","title":"Summary"},{"location":"features/element_access/default_value/","text":"Access with default value: value \u00b6 Overview \u00b6 In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. Example Consider the following JSON value: { \"logOutput\" : \"result.log\" , \"append\" : true } Assume the value is parsed to a json variable j . expression value j { \"logOutput\" : \"result.log\" , \"append\" : true } j . value ( \"logOutput\" , \"logfile.log\" ) \"result.log\" j . value ( \"append\" , true ) true j . value ( \"append\" , false ) true j . value ( \"logLevel\" , \"verbose\" ) \"verbose\" Note \u00b6 Exceptions value can only be used with objects. For other types, a basic_json::type_error is thrown.","title":"Access with default value: value"},{"location":"features/element_access/default_value/#access-with-default-value-value","text":"","title":"Access with default value: value"},{"location":"features/element_access/default_value/#overview","text":"In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. Example Consider the following JSON value: { \"logOutput\" : \"result.log\" , \"append\" : true } Assume the value is parsed to a json variable j . expression value j { \"logOutput\" : \"result.log\" , \"append\" : true } j . value ( \"logOutput\" , \"logfile.log\" ) \"result.log\" j . value ( \"append\" , true ) true j . value ( \"append\" , false ) true j . value ( \"logLevel\" , \"verbose\" ) \"verbose\"","title":"Overview"},{"location":"features/element_access/default_value/#note","text":"Exceptions value can only be used with objects. For other types, a basic_json::type_error is thrown.","title":"Note"},{"location":"features/element_access/unchecked_access/","text":"Unchecked access: operator[] \u00b6 Overview \u00b6 Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std :: map and a std :: vector , respectively. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j [ \"name\" ] \"Mary Smith\" j [ \"age\" ] 42 j [ \"hobbies\" ] [ \"hiking\" , \"reading\" ] j [ \"hobbies\" ][ 0 ] \"hiking\" j [ \"hobbies\" ][ 1 ] \"reading\" The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten. Write access j [ \"name\" ] = \"John Smith\" ; j [ \"maidenName\" ] = \"Jones\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with null . Filling up arrays with null values j [ \"hobbies\" ][ 0 ] = \"running\" ; j [ \"hobbies\" ][ 3 ] = \"cooking\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"running\" , \"reading\" , null , \"cooking\" ] } Notes \u00b6 Design rationale The library behaves differently to std :: vector and std :: map : std :: vector :: operator [] never inserts a new element. std :: map :: operator [] is not available for const values. The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects. Info The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown. Danger 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. Summary \u00b6 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","title":"Unchecked access: operator[]"},{"location":"features/element_access/unchecked_access/#unchecked-access-operator","text":"","title":"Unchecked access: operator[]"},{"location":"features/element_access/unchecked_access/#overview","text":"Elements in a JSON object and a JSON array can be accessed via operator[] similar to a std :: map and a std :: vector , respectively. Read access Consider the following JSON value: { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } Assume the value is parsed to a json variable j . expression value j { \"name\" : \"Mary Smith\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ]} j [ \"name\" ] \"Mary Smith\" j [ \"age\" ] 42 j [ \"hobbies\" ] [ \"hiking\" , \"reading\" ] j [ \"hobbies\" ][ 0 ] \"hiking\" j [ \"hobbies\" ][ 1 ] \"reading\" The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a null value is inserted which can be immediately be overwritten. Write access j [ \"name\" ] = \"John Smith\" ; j [ \"maidenName\" ] = \"Jones\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"hiking\" , \"reading\" ] } When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with null . Filling up arrays with null values j [ \"hobbies\" ][ 0 ] = \"running\" ; j [ \"hobbies\" ][ 3 ] = \"cooking\" ; This code produces the following JSON value: { \"name\" : \"John Smith\" , \"maidenName\" : \"Jones\" , \"age\" : 42 , \"hobbies\" : [ \"running\" , \"reading\" , null , \"cooking\" ] }","title":"Overview"},{"location":"features/element_access/unchecked_access/#notes","text":"Design rationale The library behaves differently to std :: vector and std :: map : std :: vector :: operator [] never inserts a new element. std :: map :: operator [] is not available for const values. The type json wraps all JSON value types. It would be impossible to remove operator[] for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward insert calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects. Info The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown. Danger 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.","title":"Notes"},{"location":"features/element_access/unchecked_access/#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","title":"Summary"},{"location":"features/parsing/","text":"Parsing \u00b6 Note This page is under construction. Input \u00b6 SAX vs. DOM parsing \u00b6 Exceptions \u00b6 See parsing and exceptions .","title":"Parsing"},{"location":"features/parsing/#parsing","text":"Note This page is under construction.","title":"Parsing"},{"location":"features/parsing/#input","text":"","title":"Input"},{"location":"features/parsing/#sax-vs-dom-parsing","text":"","title":"SAX vs. DOM parsing"},{"location":"features/parsing/#exceptions","text":"See parsing and exceptions .","title":"Exceptions"},{"location":"features/parsing/json_lines/","text":"JSON Lines \u00b6 The JSON Lines format is a text format of newline-delimited JSON. In particular: The input must be UTF-8 encoded. Every line must be a valid JSON value. The line separator must be \\n . As \\r is silently ignored, \\r\\n is also supported. The final character may be \\n , but is not required to be one. JSON Text example { \"name\" : \"Gilbert\" , \"wins\" : [[ \"straight\" , \"7\u2663\" ], [ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" : [[ \"two pair\" , \"4\u2660\" ], [ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" : []} { \"name\" : \"Deloise\" , \"wins\" : [[ \"three of a kind\" , \"5\u2663\" ]]} JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used: Example: Parse JSON Text input line by line The example below demonstrates how JSON Lines can be processed. #include #include #include using json = nlohmann :: json ; int main () { // JSON Lines (see https://jsonlines.org) std :: stringstream input ; input << R \" ( {\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]} {\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]} {\"name\": \"May\", \"wins\": []} {\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]} ) \" ; std :: string line ; while ( std :: getline ( input , line )) { std :: cout << json :: parse ( line ) << std :: endl ; } } Output: { \"name\" : \"Gilbert\" , \"wins\" :[[ \"straight\" , \"7\u2663\" ],[ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" :[[ \"two pair\" , \"4\u2660\" ],[ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" :[]} { \"name\" : \"Deloise\" , \"wins\" :[[ \"three of a kind\" , \"5\u2663\" ]]} Note Using operator>> like json j ; while ( input >> j ) { std :: cout << j << std :: endl ; } with a JSON Lines input does not work, because the parser will try to parse one value after the last one.","title":"JSON Lines"},{"location":"features/parsing/json_lines/#json-lines","text":"The JSON Lines format is a text format of newline-delimited JSON. In particular: The input must be UTF-8 encoded. Every line must be a valid JSON value. The line separator must be \\n . As \\r is silently ignored, \\r\\n is also supported. The final character may be \\n , but is not required to be one. JSON Text example { \"name\" : \"Gilbert\" , \"wins\" : [[ \"straight\" , \"7\u2663\" ], [ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" : [[ \"two pair\" , \"4\u2660\" ], [ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" : []} { \"name\" : \"Deloise\" , \"wins\" : [[ \"three of a kind\" , \"5\u2663\" ]]} JSON Lines input with more than one value is treated as invalid JSON by the parse or accept functions. To process it line by line, functions like std::getline can be used: Example: Parse JSON Text input line by line The example below demonstrates how JSON Lines can be processed. #include #include #include using json = nlohmann :: json ; int main () { // JSON Lines (see https://jsonlines.org) std :: stringstream input ; input << R \" ( {\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7\u2663\"], [\"one pair\", \"10\u2665\"]]} {\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4\u2660\"], [\"two pair\", \"9\u2660\"]]} {\"name\": \"May\", \"wins\": []} {\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5\u2663\"]]} ) \" ; std :: string line ; while ( std :: getline ( input , line )) { std :: cout << json :: parse ( line ) << std :: endl ; } } Output: { \"name\" : \"Gilbert\" , \"wins\" :[[ \"straight\" , \"7\u2663\" ],[ \"one pair\" , \"10\u2665\" ]]} { \"name\" : \"Alexa\" , \"wins\" :[[ \"two pair\" , \"4\u2660\" ],[ \"two pair\" , \"9\u2660\" ]]} { \"name\" : \"May\" , \"wins\" :[]} { \"name\" : \"Deloise\" , \"wins\" :[[ \"three of a kind\" , \"5\u2663\" ]]} Note Using operator>> like json j ; while ( input >> j ) { std :: cout << j << std :: endl ; } with a JSON Lines input does not work, because the parser will try to parse one value after the last one.","title":"JSON Lines"},{"location":"features/parsing/parse_exceptions/","text":"Parsing and Exceptions \u00b6 When the input is not valid JSON, an exception of type parse_error is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions . In case you process untrusted input, always enclose your code with a try / catch block, like json j ; try { j = json :: parse ( my_input ); } catch ( json :: parse_error & ex ) { std :: cerr << \"parse error at byte \" << ex . byte << std :: endl ; } In case exceptions are undesired or not supported by the environment, there are different ways to proceed: Switch off exceptions \u00b6 The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs ( true , default) or whether a discarded value should be returned ( false ). json j = json :: parse ( my_input , nullptr , false ); if ( j . is_discarded ()) { std :: cerr << \"parse error\" << std :: endl ; } Note there is no diagnostic information available in this scenario. Use accept() function \u00b6 Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON. if ( ! json :: accept ( my_input )) { std :: cerr << \"parse error\" << std :: endl ; } Again, there is no diagnostic information available. User-defined SAX interface \u00b6 Finally, you can implement the SAX interface and decide what should happen in case of a parse error. This function has the following interface: bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); The return value indicates whether the parsing should continue, so the function should usually return false . Example #include #include \"json.hpp\" using json = nlohmann :: json ; class sax_no_exception : public nlohmann :: detail :: json_sax_dom_parser < json > { public : sax_no_exception ( json & j ) : nlohmann :: detail :: json_sax_dom_parser < json > ( j , false ) {} bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) { std :: cerr << \"parse error at input byte \" << position << \" \\n \" << ex . what () << \" \\n \" << \"last read: \\\" \" << last_token << \" \\\" \" << std :: endl ; return false ; } }; int main () { std :: string myinput = \"[1,2,3,]\" ; json result ; sax_no_exception sax ( result ); bool parse_result = json :: sax_parse ( myinput , & sax ); if ( ! parse_result ) { std :: cerr << \"parsing unsuccessful!\" << std :: endl ; } std :: cout << \"parsed value: \" << result << std :: endl ; } Output: parse error at input byte 8 [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal last read: \"3,]\" parsing unsuccessful! parsed value: [1,2,3]","title":"Parsing and Exceptions"},{"location":"features/parsing/parse_exceptions/#parsing-and-exceptions","text":"When the input is not valid JSON, an exception of type parse_error is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a list of examples for parse error exceptions . In case you process untrusted input, always enclose your code with a try / catch block, like json j ; try { j = json :: parse ( my_input ); } catch ( json :: parse_error & ex ) { std :: cerr << \"parse error at byte \" << ex . byte << std :: endl ; } In case exceptions are undesired or not supported by the environment, there are different ways to proceed:","title":"Parsing and Exceptions"},{"location":"features/parsing/parse_exceptions/#switch-off-exceptions","text":"The parse() function accepts a bool parameter allow_exceptions which controls whether an exception is thrown when a parse error occurs ( true , default) or whether a discarded value should be returned ( false ). json j = json :: parse ( my_input , nullptr , false ); if ( j . is_discarded ()) { std :: cerr << \"parse error\" << std :: endl ; } Note there is no diagnostic information available in this scenario.","title":"Switch off exceptions"},{"location":"features/parsing/parse_exceptions/#use-accept-function","text":"Alternatively, function accept() can be used which does not return a json value, but a bool indicating whether the input is valid JSON. if ( ! json :: accept ( my_input )) { std :: cerr << \"parse error\" << std :: endl ; } Again, there is no diagnostic information available.","title":"Use accept() function"},{"location":"features/parsing/parse_exceptions/#user-defined-sax-interface","text":"Finally, you can implement the SAX interface and decide what should happen in case of a parse error. This function has the following interface: bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); The return value indicates whether the parsing should continue, so the function should usually return false . Example #include #include \"json.hpp\" using json = nlohmann :: json ; class sax_no_exception : public nlohmann :: detail :: json_sax_dom_parser < json > { public : sax_no_exception ( json & j ) : nlohmann :: detail :: json_sax_dom_parser < json > ( j , false ) {} bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ) { std :: cerr << \"parse error at input byte \" << position << \" \\n \" << ex . what () << \" \\n \" << \"last read: \\\" \" << last_token << \" \\\" \" << std :: endl ; return false ; } }; int main () { std :: string myinput = \"[1,2,3,]\" ; json result ; sax_no_exception sax ( result ); bool parse_result = json :: sax_parse ( myinput , & sax ); if ( ! parse_result ) { std :: cerr << \"parsing unsuccessful!\" << std :: endl ; } std :: cout << \"parsed value: \" << result << std :: endl ; } Output: parse error at input byte 8 [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal last read: \"3,]\" parsing unsuccessful! parsed value: [1,2,3]","title":"User-defined SAX interface"},{"location":"features/parsing/parser_callbacks/","text":"Parser Callbacks \u00b6 Overview \u00b6 With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. The type of the callback function is: template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ; Callback event types \u00b6 We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example When parsing the following JSON text, { \"name\" : \"Berlin\" , \"location\" : [ 52.519444 , 13.406667 ] } these calls are made to the callback function: event depth parsed object_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [ 52.519444 , 13.406667 ] object_end 0 { \"location\" :[ 52.519444 , 13.406667 ], \"name\" : \"Berlin\" } Return value \u00b6 Discarding a value (i.e., returning false ) has different effects depending on the context in which the 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. Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } }","title":"Parser Callbacks"},{"location":"features/parsing/parser_callbacks/#parser-callbacks","text":"","title":"Parser Callbacks"},{"location":"features/parsing/parser_callbacks/#overview","text":"With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse , it is called on certain events (passed as parse_event_t via parameter event ) with a set recursion depth depth and context JSON value parsed . The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. The type of the callback function is: template < typename BasicJsonType > using parser_callback_t = std :: function < bool ( int depth , parse_event_t event , BasicJsonType & parsed ) > ;","title":"Overview"},{"location":"features/parsing/parser_callbacks/#callback-event-types","text":"We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth , event , and parsed . parameter event description parameter depth parameter parsed parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value Example When parsing the following JSON text, { \"name\" : \"Berlin\" , \"location\" : [ 52.519444 , 13.406667 ] } these calls are made to the callback function: event depth parsed object_start 0 discarded key 1 \"name\" value 1 \"Berlin\" key 1 \"location\" array_start 1 discarded value 2 52.519444 value 2 13.406667 array_end 1 [ 52.519444 , 13.406667 ] object_end 0 { \"location\" :[ 52.519444 , 13.406667 ], \"name\" : \"Berlin\" }","title":"Callback event types"},{"location":"features/parsing/parser_callbacks/#return-value","text":"Discarding a value (i.e., returning false ) has different effects depending on the context in which the 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. Example The example below demonstrates the parse() function with and without callback function. #include #include #include using json = nlohmann :: json ; int main () { // a JSON text auto text = R \" ( { \"Image\": { \"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": { \"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100 }, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793] } } ) \" ; // parse and serialize JSON json j_complete = json :: parse ( text ); std :: cout << std :: setw ( 4 ) << j_complete << \" \\n\\n \" ; // define parser callback json :: parser_callback_t cb = []( int depth , json :: parse_event_t event , json & parsed ) { // skip object elements with key \"Thumbnail\" if ( event == json :: parse_event_t :: key and parsed == json ( \"Thumbnail\" )) { return false ; } else { return true ; } }; // parse (with callback) and serialize JSON json j_filtered = json :: parse ( text , cb ); std :: cout << std :: setw ( 4 ) << j_filtered << '\\n' ; } Output: { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Thumbnail\" : { \"Height\" : 125 , \"Url\" : \"http://www.example.com/image/481989943\" , \"Width\" : 100 }, \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } } { \"Image\" : { \"Animated\" : false , \"Height\" : 600 , \"IDs\" : [ 116 , 943 , 234 , 38793 ], \"Title\" : \"View from 15th Floor\" , \"Width\" : 800 } }","title":"Return value"},{"location":"features/parsing/sax_interface/","text":"SAX Interface \u00b6 The library uses a SAX-like interface with the following functions: // called when null is parsed bool null (); // called when a boolean is parsed; value is passed bool boolean ( bool val ); // called when a signed or unsigned integer number is parsed; value is passed bool number_integer ( number_integer_t val ); bool number_unsigned ( number_unsigned_t val ); // called when a floating-point number is parsed; value and original string is passed bool number_float ( number_float_t val , const string_t & s ); // called when a string is parsed; value is passed and can be safely moved away bool string ( string_t & val ); // called when a binary value is parsed; value is passed and can be safely moved away bool binary ( binary & val ); // called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known) bool start_object ( std :: size_t elements ); bool end_object (); bool start_array ( std :: size_t elements ); bool end_array (); // called when an object key is parsed; value is passed and can be safely moved away bool key ( string_t & val ); // called when a parse error occurs; byte position, the last token, and an exception is passed bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); 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 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 . See also \u00b6 json_sax - documentation of the SAX interface sax_parse - SAX parser","title":"SAX Interface"},{"location":"features/parsing/sax_interface/#sax-interface","text":"The library uses a SAX-like interface with the following functions: // called when null is parsed bool null (); // called when a boolean is parsed; value is passed bool boolean ( bool val ); // called when a signed or unsigned integer number is parsed; value is passed bool number_integer ( number_integer_t val ); bool number_unsigned ( number_unsigned_t val ); // called when a floating-point number is parsed; value and original string is passed bool number_float ( number_float_t val , const string_t & s ); // called when a string is parsed; value is passed and can be safely moved away bool string ( string_t & val ); // called when a binary value is parsed; value is passed and can be safely moved away bool binary ( binary & val ); // called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known) bool start_object ( std :: size_t elements ); bool end_object (); bool start_array ( std :: size_t elements ); bool end_array (); // called when an object key is parsed; value is passed and can be safely moved away bool key ( string_t & val ); // called when a parse error occurs; byte position, the last token, and an exception is passed bool parse_error ( std :: size_t position , const std :: string & last_token , const json :: exception & ex ); 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 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 .","title":"SAX Interface"},{"location":"features/parsing/sax_interface/#see-also","text":"json_sax - documentation of the SAX interface sax_parse - SAX parser","title":"See also"},{"location":"features/types/","text":"Types \u00b6 This page gives an overview how JSON values are stored and how this can be configured. Overview \u00b6 By default, JSON values are stored as follows: JSON type C++ type object std::map array std::vector 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. Storage \u00b6 Template arguments \u00b6 The data types to store a JSON value are derived from the template arguments passed to class basic_json : template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > > class basic_json ; Type json is an alias for basic_json<> and uses the default types. From the template arguments, the following types are derived: using object_comparator_t = std :: less <> ; using object_t = ObjectType < StringType , basic_json , object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; using string_t = StringType ; using boolean_t = BooleanType ; using number_integer_t = NumberIntegerType ; using number_unsigned_t = NumberUnsignedType ; using number_float_t = NumberFloatType ; using binary_t = nlohmann :: byte_container_with_subtype < BinaryType > ; Objects \u00b6 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. Default type \u00b6 With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type > Behavior \u00b6 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. Key order \u00b6 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. Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object. Storage \u00b6 Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced. Arrays \u00b6 RFC 8259 describes JSON arrays as follows: An array is an ordered sequence of zero or more values. Default type \u00b6 With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type > Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array. Storage \u00b6 Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced. Strings \u00b6 RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. Unicode values are split by the JSON class into byte-sized characters during deserialization. Default type \u00b6 With the default values for StringType ( std::string ), the default value for string_t is std :: string . Encoding \u00b6 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. String comparison \u00b6 RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit. Storage \u00b6 String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced. Booleans \u00b6 RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false . Default type \u00b6 With the default values for BooleanType ( bool ), the default value for boolean_t is bool . Storage \u00b6 Boolean values are stored directly inside a basic_json type. Numbers \u00b6 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. Default types \u00b6 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 . Default behavior \u00b6 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 . Limits \u00b6 RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 ( INT64_MAX ) and the minimal integer number that can be stored is -9223372036854775808 ( INT64_MIN ). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 ( UINT64_MAX ) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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 . Storage \u00b6 Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.","title":"Types"},{"location":"features/types/#types","text":"This page gives an overview how JSON values are stored and how this can be configured.","title":"Types"},{"location":"features/types/#overview","text":"By default, JSON values are stored as follows: JSON type C++ type object std::map array std::vector 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.","title":"Overview"},{"location":"features/types/#storage","text":"","title":"Storage"},{"location":"features/types/#template-arguments","text":"The data types to store a JSON value are derived from the template arguments passed to class basic_json : template < template < typename U , typename V , typename ... Args > class ObjectType = std :: map , template < typename U , typename ... Args > class ArrayType = std :: vector , class StringType = std :: string , class BooleanType = bool , class NumberIntegerType = std :: int64_t , class NumberUnsignedType = std :: uint64_t , class NumberFloatType = double , template < typename U > class AllocatorType = std :: allocator , template < typename T , typename SFINAE = void > class JSONSerializer = adl_serializer , class BinaryType = std :: vector < std :: uint8_t > > class basic_json ; Type json is an alias for basic_json<> and uses the default types. From the template arguments, the following types are derived: using object_comparator_t = std :: less <> ; using object_t = ObjectType < StringType , basic_json , object_comparator_t , AllocatorType < std :: pair < const StringType , basic_json >>> ; using array_t = ArrayType < basic_json , AllocatorType < basic_json >> ; using string_t = StringType ; using boolean_t = BooleanType ; using number_integer_t = NumberIntegerType ; using number_unsigned_t = NumberUnsignedType ; using number_float_t = NumberFloatType ; using binary_t = nlohmann :: byte_container_with_subtype < BinaryType > ;","title":"Template arguments"},{"location":"features/types/#objects","text":"RFC 8259 describes JSON objects as follows: An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.","title":"Objects"},{"location":"features/types/#default-type","text":"With the default values for ObjectType ( std::map ), StringType ( std::string ), and AllocatorType ( std::allocator ), the default value for object_t is: std :: map < std :: string , // key_type basic_json , // value_type std :: less <> , // key_compare std :: allocator < std :: pair < const std :: string , basic_json >> // allocator_type >","title":"Default type"},{"location":"features/types/#behavior","text":"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.","title":"Behavior"},{"location":"features/types/#key-order","text":"The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 8259 , because any order implements the specified \"unordered\" nature of JSON objects.","title":"Key order"},{"location":"features/types/#limits","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.","title":"Limits"},{"location":"features/types/#storage_1","text":"Objects are stored as pointers in a basic_json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.","title":"Storage"},{"location":"features/types/#arrays","text":"RFC 8259 describes JSON arrays as follows: An array is an ordered sequence of zero or more values.","title":"Arrays"},{"location":"features/types/#default-type_1","text":"With the default values for ArrayType ( std::vector ) and AllocatorType ( std::allocator ), the default value for array_t is: std :: vector < basic_json , // value_type std :: allocator < basic_json > // allocator_type >","title":"Default type"},{"location":"features/types/#limits_1","text":"RFC 8259 specifies: An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.","title":"Limits"},{"location":"features/types/#storage_2","text":"Arrays are stored as pointers in a basic_json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.","title":"Storage"},{"location":"features/types/#strings","text":"RFC 8259 describes JSON strings as follows: A string is a sequence of zero or more Unicode characters. Unicode values are split by the JSON class into byte-sized characters during deserialization.","title":"Strings"},{"location":"features/types/#default-type_2","text":"With the default values for StringType ( std::string ), the default value for string_t is std :: string .","title":"Default type"},{"location":"features/types/#encoding","text":"Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.","title":"Encoding"},{"location":"features/types/#string-comparison","text":"RFC 8259 states: Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that \"a\\\\b\" and \"a\\u005Cb\" are not equal. This implementation is interoperable as it does compare strings code unit by code unit.","title":"String comparison"},{"location":"features/types/#storage_3","text":"String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.","title":"Storage"},{"location":"features/types/#booleans","text":"RFC 8259 implicitly describes a boolean as a type which differentiates the two literals true and false .","title":"Booleans"},{"location":"features/types/#default-type_3","text":"With the default values for BooleanType ( bool ), the default value for boolean_t is bool .","title":"Default type"},{"location":"features/types/#storage_4","text":"Boolean values are stored directly inside a basic_json type.","title":"Storage"},{"location":"features/types/#numbers","text":"See the number handling article for a detailed discussion on how numbers are handled by this library. RFC 8259 describes numbers as follows: The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t , number_unsigned_t , and number_float_t are used.","title":"Numbers"},{"location":"features/types/#default-types","text":"With the default values for NumberIntegerType ( std::int64_t ), the default value for number_integer_t is std::int64_t . With the default values for NumberUnsignedType ( std::uint64_t ), the default value for number_unsigned_t is std::uint64_t . With the default values for NumberFloatType ( double ), the default value for number_float_t is double .","title":"Default types"},{"location":"features/types/#default-behavior","text":"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 .","title":"Default behavior"},{"location":"features/types/#limits_2","text":"RFC 8259 specifies: An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is 9223372036854775807 ( INT64_MAX ) and the minimal integer number that can be stored is -9223372036854775808 ( INT64_MIN ). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t . When the default type is used, the maximal unsigned integer number that can be stored is 18446744073709551615 ( UINT64_MAX ) and the minimal integer number that can be stored is 0 . Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t . RFC 8259 further states: Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-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 .","title":"Limits"},{"location":"features/types/#storage_5","text":"Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a basic_json type.","title":"Storage"},{"location":"features/types/number_handling/","text":"Number Handling \u00b6 This document describes how the library is handling numbers. Background \u00b6 This section briefly summarizes how the JSON specification describes how numbers should be handled. JSON number syntax \u00b6 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: Number interoperability \u00b6 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] [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values. Library implementation \u00b6 This section describes how the above number specification is implemented by this library. Number storage \u00b6 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 . Number limits \u00b6 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] [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1] [-2^{53}+1, 2^{53}-1] . All integers outside the range [-2^{63}, 2^{64}-1] [-2^{63}, 2^{64}-1] , as well as floating-point numbers are stored as double . This also concurs with the specification above. Zeros \u00b6 The JSON number grammar allows for different ways to express zero, and this library will store zeros differently: Literal Stored value and type Serialization 0 std :: uint64_t ( 0 ) 0 -0 std :: int64_t ( 0 ) 0 0.0 double ( 0.0 ) 0.0 -0.0 double ( -0.0 ) -0.0 0E0 double ( 0.0 ) 0.0 -0E0 double ( -0.0 ) -0.0 That is, -0 is stored as a signed integer, but the serialization does not reproduce the - . Number serialization \u00b6 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::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: float f = 0.3 ; json j = f ; std :: cout << j << '\\n' ; yields 0.30000001192092896 . All examples here can be reproduced by passing the original double value to std :: printf ( \"%.*g \\n \" , std :: numeric_limits < double >:: max_digits10 , double_value ); NaN handling \u00b6 NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded: RFC 8259 , Section 6 Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment. This library serializes NaN values as null . This corresponds to the behavior of JavaScript's JSON.stringify function. Example The following example shows how a NaN value is stored in a json value. int main () { double val = std :: numeric_limits < double >:: quiet_NaN (); std :: cout << \"val=\" << val << std :: endl ; json j = val ; std :: cout << \"j=\" << j . dump () << std :: endl ; val = j ; std :: cout << \"val=\" << val << std :: endl ; } output: val=nan j=null val=nan Number comparison \u00b6 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 > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-define an operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) { // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } } ... } (see #703 for more information.) Note NaN values never compare equal to themselves or to other NaN values. See #514 . Number conversion \u00b6 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 json jd = d ; // stores double value 42.3 std :: int64_t i = jd . template get < std :: int64_t > (); // now i==42; no warning or error is produced 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 #json-specification ). 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 if ( jd . is_number_integer ()) { // if so, do the conversion and use i std :: int64_t i = jd . template get < std :: int64_t > (); // ... } else { // otherwise, take appropriate action // ... } Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings. (Example taken from #777 .) Determine number types \u00b6 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() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string Template number types \u00b6 The number types can be changed with template parameters. position number type default type possible values 5 signed integers std :: int64_t std :: int32_t , std :: int16_t , etc. 6 unsigned integers std :: uint64_t std :: uint32_t , std :: uint16_t , etc. 7 floating-point double float , long double Constraints on number types 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 , std :: int64_t , std :: uint64_t , long double > ; 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 .","title":"Number Handling"},{"location":"features/types/number_handling/#number-handling","text":"This document describes how the library is handling numbers.","title":"Number Handling"},{"location":"features/types/number_handling/#background","text":"This section briefly summarizes how the JSON specification describes how numbers should be handled.","title":"Background"},{"location":"features/types/number_handling/#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:","title":"JSON number syntax"},{"location":"features/types/number_handling/#number-interoperability","text":"On number interoperability, the following remarks are made: RFC 8259 , Section 6 This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available. Note that when such software is used, numbers that are integers and are in the range [-2^{53}+1, 2^{53}-1] [-2^{53}+1, 2^{53}-1] are interoperable in the sense that implementations will agree exactly on their numeric values.","title":"Number interoperability"},{"location":"features/types/number_handling/#library-implementation","text":"This section describes how the above number specification is implemented by this library.","title":"Library implementation"},{"location":"features/types/number_handling/#number-storage","text":"In the default json type, numbers are stored as std :: uint64_t , std :: int64_t , and double , respectively. Thereby, std :: uint64_t and std :: int64_t are used only if they can store the number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as double . Notes 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 .","title":"Number storage"},{"location":"features/types/number_handling/#number-limits","text":"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] [-2^{63}, 2^{64}-1] is larger than the described range [-2^{53}+1, 2^{53}-1] [-2^{53}+1, 2^{53}-1] . All integers outside the range [-2^{63}, 2^{64}-1] [-2^{63}, 2^{64}-1] , as well as floating-point numbers are stored as double . This also concurs with the specification above.","title":"Number limits"},{"location":"features/types/number_handling/#zeros","text":"The JSON number grammar allows for different ways to express zero, and this library will store zeros differently: Literal Stored value and type Serialization 0 std :: uint64_t ( 0 ) 0 -0 std :: int64_t ( 0 ) 0 0.0 double ( 0.0 ) 0.0 -0.0 double ( -0.0 ) -0.0 0E0 double ( 0.0 ) 0.0 -0E0 double ( -0.0 ) -0.0 That is, -0 is stored as a signed integer, but the serialization does not reproduce the - .","title":"Zeros"},{"location":"features/types/number_handling/#number-serialization","text":"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::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: float f = 0.3 ; json j = f ; std :: cout << j << '\\n' ; yields 0.30000001192092896 . All examples here can be reproduced by passing the original double value to std :: printf ( \"%.*g \\n \" , std :: numeric_limits < double >:: max_digits10 , double_value );","title":"Number serialization"},{"location":"features/types/number_handling/#nan-handling","text":"NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded: RFC 8259 , Section 6 Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. That is, there is no way to parse a NaN value. However, NaN values can be stored in a JSON value by assignment. This library serializes NaN values as null . This corresponds to the behavior of JavaScript's JSON.stringify function. Example The following example shows how a NaN value is stored in a json value. int main () { double val = std :: numeric_limits < double >:: quiet_NaN (); std :: cout << \"val=\" << val << std :: endl ; json j = val ; std :: cout << \"j=\" << j . dump () << std :: endl ; val = j ; std :: cout << \"val=\" << val << std :: endl ; } output: val=nan j=null val=nan","title":"NaN handling"},{"location":"features/types/number_handling/#number-comparison","text":"Floating-point inside JSON values numbers are compared with json :: number_float_t :: operator == which is double :: operator == by default. Alternative comparison functions To compare floating-point while respecting an epsilon, an alternative comparison function could be used, for instance template < typename T , typename = typename std :: enable_if < std :: is_floating_point < T >:: value , T >:: type > inline bool is_same ( T a , T b , T epsilon = std :: numeric_limits < T >:: epsilon ()) noexcept { return std :: abs ( a - b ) <= epsilon ; } Or you can self-define an operator equal function like this: bool my_equal ( const_reference lhs , const_reference rhs ) { const auto lhs_type lhs . type (); const auto rhs_type rhs . type (); if ( lhs_type == rhs_type ) { switch ( lhs_type ) { // self_defined case case value_t :: number_float : return std :: abs ( lhs - rhs ) <= std :: numeric_limits < float >:: epsilon (); // other cases remain the same with the original ... } } ... } (see #703 for more information.) Note NaN values never compare equal to themselves or to other NaN values. See #514 .","title":"Number comparison"},{"location":"features/types/number_handling/#number-conversion","text":"Just like the C++ language itself, the get family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising. Unconditional number conversions double d = 42.3 ; // non-integer double value 42.3 json jd = d ; // stores double value 42.3 std :: int64_t i = jd . template get < std :: int64_t > (); // now i==42; no warning or error is produced 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 #json-specification ). 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 if ( jd . is_number_integer ()) { // if so, do the conversion and use i std :: int64_t i = jd . template get < std :: int64_t > (); // ... } else { // otherwise, take appropriate action // ... } Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings. (Example taken from #777 .)","title":"Number conversion"},{"location":"features/types/number_handling/#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() true true true false is_number_integer() true true false false is_number_unsigned() true false false false is_number_float() false false true false type_name() \"number\" \"number\" \"number\" \"string\" type() number_unsigned number_integer number_float string","title":"Determine number types"},{"location":"features/types/number_handling/#template-number-types","text":"The number types can be changed with template parameters. position number type default type possible values 5 signed integers std :: int64_t std :: int32_t , std :: int16_t , etc. 6 unsigned integers std :: uint64_t std :: uint32_t , std :: uint16_t , etc. 7 floating-point double float , long double Constraints on number types 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 , std :: int64_t , std :: uint64_t , long double > ; 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 .","title":"Template number types"},{"location":"home/code_of_conduct/","text":"Contributor Covenant Code of Conduct \u00b6 Our Pledge \u00b6 In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards \u00b6 Examples of behavior that contributes to creating a positive environment include: Using welcoming and inclusive language Being respectful of differing viewpoints and experiences Gracefully accepting constructive criticism Focusing on what is best for the community Showing empathy towards other community members Examples of unacceptable behavior by participants include: The use of sexualized language or imagery and unwelcome sexual attention or advances Trolling, insulting/derogatory comments, and personal or political attacks Public or private harassment Publishing others' private information, such as a physical or electronic address, without explicit permission Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities \u00b6 Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope \u00b6 This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement \u00b6 Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me . The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution \u00b6 This Code of Conduct is adapted from the Contributor Covenant , version 1.4, available at http://contributor-covenant.org/version/1/4","title":"Code of Conduct"},{"location":"home/code_of_conduct/#contributor-covenant-code-of-conduct","text":"","title":"Contributor Covenant Code of Conduct"},{"location":"home/code_of_conduct/#our-pledge","text":"In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.","title":"Our Pledge"},{"location":"home/code_of_conduct/#our-standards","text":"Examples of behavior that contributes to creating a positive environment include: Using welcoming and inclusive language Being respectful of differing viewpoints and experiences Gracefully accepting constructive criticism Focusing on what is best for the community Showing empathy towards other community members Examples of unacceptable behavior by participants include: The use of sexualized language or imagery and unwelcome sexual attention or advances Trolling, insulting/derogatory comments, and personal or political attacks Public or private harassment Publishing others' private information, such as a physical or electronic address, without explicit permission Other conduct which could reasonably be considered inappropriate in a professional setting","title":"Our Standards"},{"location":"home/code_of_conduct/#our-responsibilities","text":"Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.","title":"Our Responsibilities"},{"location":"home/code_of_conduct/#scope","text":"This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.","title":"Scope"},{"location":"home/code_of_conduct/#enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@nlohmann.me . The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.","title":"Enforcement"},{"location":"home/code_of_conduct/#attribution","text":"This Code of Conduct is adapted from the Contributor Covenant , version 1.4, available at http://contributor-covenant.org/version/1/4","title":"Attribution"},{"location":"home/design_goals/","text":"Design goals \u00b6 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. Check out the examples below , and you'll know what I mean. 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.","title":"Design goals"},{"location":"home/design_goals/#design-goals","text":"There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals: Intuitive syntax . In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code. Check out the examples below , and you'll know what I mean. 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.","title":"Design goals"},{"location":"home/exceptions/","text":"Exceptions \u00b6 Overview \u00b6 Base type \u00b6 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. Switch off exceptions \u00b6 Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION . In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw ), JSON_TRY_USER (overriding try ), and JSON_CATCH_USER (overriding catch ). Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior. Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 . See documentation of JSON_TRY_USER , JSON_CATCH_USER and JSON_THROW_USER for more information. Extended diagnostic messages \u00b6 Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult. Example #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer . As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp . Example #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type. See documentation of JSON_DIAGNOSTICS for more information. Parse errors \u00b6 This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Exceptions have ids 1xx. Byte index Member byte holds the byte index of the last read character in the input file. For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal exception id: 101 byte position of error: 8 json.exception.parse_error.101 \u00b6 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 No input: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal 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: '\"'\" 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: '\"' 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' \\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\"' 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'\" 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' 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.exception.parse_error.102 \u00b6 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 Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used. json.exception.parse_error.103 \u00b6 Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. Example message parse error: code points above 0x10FFFF are invalid Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used. json.exception.parse_error.104 \u00b6 RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects. Example message [json.exception.parse_error.104] parse error: JSON patch must be an array of objects json.exception.parse_error.105 \u00b6 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' [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from' [json.exception.parse_error.105] parse error: operation value 'foo' is invalid json.exception.parse_error.106 \u00b6 An array index in a JSON Pointer ( RFC 6901 ) may be 0 or any number without a leading 0 . Example message [json.exception.parse_error.106] parse error: array index '01' must not begin with '0' json.exception.parse_error.107 \u00b6 A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character. Example message [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo' json.exception.parse_error.108 \u00b6 In a JSON Pointer, only ~0 and ~1 are valid escape sequences. Example message [json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1' json.exception.parse_error.109 \u00b6 A JSON Pointer array index must be a number. Example messages [json.exception.parse_error.109] parse error: array index 'one' is not a number [json.exception.parse_error.109] parse error: array index '+1' is not a number json.exception.parse_error.110 \u00b6 When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. Example message [json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A json.exception.parse_error.112 \u00b6 An unexpected byte was read in a binary format or length information is invalid ( BSON ). Example messages [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648 [json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1 json.exception.parse_error.113 \u00b6 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 [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 [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 json.exception.parse_error.114 \u00b6 The parsing of the corresponding BSON record type is not implemented (yet). Example message [json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF json.exception.parse_error.115 \u00b6 A UBJSON high-precision number could not be parsed. Example message [json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A Iterator errors \u00b6 This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. Example The following code shows how an invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators exception id: 207 json.exception.invalid_iterator.201 \u00b6 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 json.exception.invalid_iterator.202 \u00b6 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 [json.exception.invalid_iterator.202] iterators first and last must point to objects json.exception.invalid_iterator.203 \u00b6 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 json.exception.invalid_iterator.204 \u00b6 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 json.exception.invalid_iterator.205 \u00b6 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 json.exception.invalid_iterator.206 \u00b6 The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. Example message [json.exception.invalid_iterator.206] cannot construct with iterators from null json.exception.invalid_iterator.207 \u00b6 The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. Example message [json.exception.invalid_iterator.207] cannot use key() for non-object iterators json.exception.invalid_iterator.208 \u00b6 The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.208] cannot use operator[] for object iterators json.exception.invalid_iterator.209 \u00b6 The offset operators ( + , - , += , -= ) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.209] cannot use offsets with object iterators json.exception.invalid_iterator.210 \u00b6 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 json.exception.invalid_iterator.211 \u00b6 The iterator range passed to the insert function must not be a subrange of the container to insert to. Example message [json.exception.invalid_iterator.211] passed iterators may not belong to container json.exception.invalid_iterator.212 \u00b6 When two iterators are compared, they must belong to the same container. Example message [json.exception.invalid_iterator.212] cannot compare iterators of different containers json.exception.invalid_iterator.213 \u00b6 The order of object iterators cannot be compared, because JSON objects are unordered. Example message [json.exception.invalid_iterator.213] cannot compare order of object iterators json.exception.invalid_iterator.214 \u00b6 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 Type errors \u00b6 This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.type_error.308] cannot use push_back() with string exception id: 308 json.exception.type_error.301 \u00b6 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 json.exception.type_error.302 \u00b6 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 [json.exception.type_error.302] type must be string, but is object json.exception.type_error.303 \u00b6 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 [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\" json.exception.type_error.304 \u00b6 The at() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.304] cannot use at() with string [json.exception.type_error.304] cannot use at() with number json.exception.type_error.305 \u00b6 The operator[] member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.305] cannot use operator[] with a string argument with array [json.exception.type_error.305] cannot use operator[] with a numeric argument with object json.exception.type_error.306 \u00b6 The value() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.306] cannot use value() with number json.exception.type_error.307 \u00b6 The erase() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.307] cannot use erase() with string json.exception.type_error.308 \u00b6 The push_back() and operator+= member functions can only be executed for certain JSON types. Example message [json.exception.type_error.308] cannot use push_back() with string json.exception.type_error.309 \u00b6 The insert() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.309] cannot use insert() with array [json.exception.type_error.309] cannot use insert() with number json.exception.type_error.310 \u00b6 The swap() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.310] cannot use swap() with number json.exception.type_error.311 \u00b6 The emplace() and emplace_back() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.311] cannot use emplace() with number [json.exception.type_error.311] cannot use emplace_back() with number json.exception.type_error.312 \u00b6 The update() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.312] cannot use update() with array json.exception.type_error.313 \u00b6 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 json.exception.type_error.314 \u00b6 The unflatten function only works for an object whose keys are JSON Pointers. Example message Calling unflatten() on an array [ 1 , 2 , 3 ] : [json.exception.type_error.314] only objects can be unflattened json.exception.type_error.315 \u00b6 The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive. Example message Calling unflatten() on an object { \"/1\" , [ 1 , 2 , 3 ]} : [json.exception.type_error.315] values in object must be primitive json.exception.type_error.316 \u00b6 The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded. Example message Calling dump() on a JSON value containing an ISO 8859-1 encoded string: [json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F Tip Store the source file with UTF-8 encoding. Pass an error handler as last parameter to the dump() function to avoid this exception: json::error_handler_t::replace will replace invalid bytes sequences with U+FFFD json::error_handler_t::ignore will silently ignore invalid byte sequences json.exception.type_error.317 \u00b6 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 Serializing [ 1 , 2 , 3 ] to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array Tip Encapsulate the JSON value in an object. That is, instead of serializing true , serialize { \"value\" : true } Out of range \u00b6 This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. Example The following code shows how an out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.out_of_range.401] array index 4 is out of range exception id: 401 json.exception.out_of_range.401 \u00b6 The provided array index i is larger than size-1 . Example message array index 3 is out of range json.exception.out_of_range.402 \u00b6 The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. Example message array index '-' (3) is out of range json.exception.out_of_range.403 \u00b6 The provided key was not found in the JSON object. Example message key 'foo' not found json.exception.out_of_range.404 \u00b6 A reference token in a JSON Pointer could not be resolved. Example message unresolved reference token 'foo' json.exception.out_of_range.405 \u00b6 The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. Example message JSON pointer has no parent json.exception.out_of_range.406 \u00b6 A parsed number could not be stored as without changing it to NaN or INF. Example message number overflow parsing '10E1000' json.exception.out_of_range.407 \u00b6 UBJSON and BSON only support integer numbers up to 9223372036854775807. Example message number overflow serializing '9223372036854775808' Note Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur. json.exception.out_of_range.408 \u00b6 The size (following # ) of an UBJSON array or object exceeds the maximal capacity. Example message excessive array size: 8658170730974374167 json.exception.out_of_range.409 \u00b6 Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string. Example message BSON key cannot contain code point U+0000 (at byte 2) Further exceptions \u00b6 This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. Example The following code shows how an other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"} exception id: 501 json.exception.other_error.501 \u00b6 A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. Example message Executing { \"op\" : \"test\" , \"path\" : \"/baz\" , \"value\" : \"bar\" } on { \"baz\" : \"qux\" } : [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}","title":"Exceptions"},{"location":"home/exceptions/#exceptions","text":"","title":"Exceptions"},{"location":"home/exceptions/#overview","text":"","title":"Overview"},{"location":"home/exceptions/#base-type","text":"All exceptions inherit from class json::exception (which in turn inherits from std::exception ). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as \"wildcard\" to catch exceptions.","title":"Base type"},{"location":"home/exceptions/#switch-off-exceptions","text":"Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION . In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw ), JSON_TRY_USER (overriding try ), and JSON_CATCH_USER (overriding catch ). Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior. Example The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. #include #define JSON_TRY_USER if(true) #define JSON_CATCH_USER(exception) if(false) #define JSON_THROW_USER(exception) \\ {std::clog << \"Error in \" << __FILE__ << \":\" << __LINE__ \\ << \" (function \" << __FUNCTION__ << \") - \" \\ << (exception).what() << std::endl; \\ std::abort();} #include Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824 . See documentation of JSON_TRY_USER , JSON_CATCH_USER and JSON_THROW_USER for more information.","title":"Switch off exceptions"},{"location":"home/exceptions/#extended-diagnostic-messages","text":"Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult. Example #include #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] type must be number, but is string This exception can be hard to debug if storing the value \"12\" and accessing it is further apart. To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer . As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp . Example #include # define JSON_DIAGNOSTICS 1 #include using json = nlohmann :: json ; int main () { json j ; j [ \"address\" ][ \"street\" ] = \"Fake Street\" ; j [ \"address\" ][ \"housenumber\" ] = \"12\" ; try { int housenumber = j [ \"address\" ][ \"housenumber\" ]; } catch ( const json :: exception & e ) { std :: cout << e . what () << '\\n' ; } } Output: [json.exception.type_error.302] (/address/housenumber) type must be number, but is string Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type. See documentation of JSON_DIAGNOSTICS for more information.","title":"Extended diagnostic messages"},{"location":"home/exceptions/#parse-errors","text":"This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Exceptions have ids 1xx. Byte index Member byte holds the byte index of the last read character in the input file. For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). Example The following code shows how a parse_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // parsing input with a syntax error json :: parse ( \"[1,2,3,]\" ); } catch ( const json :: parse_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << '\\n' << \"byte position of error: \" << e . byte << std :: endl ; } } Output: message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal exception id: 101 byte position of error: 8","title":"Parse errors"},{"location":"home/exceptions/#jsonexceptionparse_error101","text":"This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte indicates the error position. Example message Input ended prematurely: [json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal No input: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal 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: '\"'\" 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: '\"' 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' \\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\"' 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'\" 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' 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 .","title":"json.exception.parse_error.101"},{"location":"home/exceptions/#jsonexceptionparse_error102","text":"JSON uses the \\uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \\uxxxx entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. Example message parse error at 14: missing or wrong low surrogate Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.","title":"json.exception.parse_error.102"},{"location":"home/exceptions/#jsonexceptionparse_error103","text":"Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. Example message parse error: code points above 0x10FFFF are invalid Note This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.","title":"json.exception.parse_error.103"},{"location":"home/exceptions/#jsonexceptionparse_error104","text":"RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects. Example message [json.exception.parse_error.104] parse error: JSON patch must be an array of objects","title":"json.exception.parse_error.104"},{"location":"home/exceptions/#jsonexceptionparse_error105","text":"An operation of a JSON Patch document must contain exactly one \"op\" member, whose value indicates the operation to perform. Its value must be one of \"add\", \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are errors. Example message [json.exception.parse_error.105] parse error: operation 'add' must have member 'value' [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from' [json.exception.parse_error.105] parse error: operation value 'foo' is invalid","title":"json.exception.parse_error.105"},{"location":"home/exceptions/#jsonexceptionparse_error106","text":"An array index in a JSON Pointer ( RFC 6901 ) may be 0 or any number without a leading 0 . Example message [json.exception.parse_error.106] parse error: array index '01' must not begin with '0'","title":"json.exception.parse_error.106"},{"location":"home/exceptions/#jsonexceptionparse_error107","text":"A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character. Example message [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'","title":"json.exception.parse_error.107"},{"location":"home/exceptions/#jsonexceptionparse_error108","text":"In a JSON Pointer, only ~0 and ~1 are valid escape sequences. Example message [json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'","title":"json.exception.parse_error.108"},{"location":"home/exceptions/#jsonexceptionparse_error109","text":"A JSON Pointer array index must be a number. Example messages [json.exception.parse_error.109] parse error: array index 'one' is not a number [json.exception.parse_error.109] parse error: array index '+1' is not a number","title":"json.exception.parse_error.109"},{"location":"home/exceptions/#jsonexceptionparse_error110","text":"When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. Example message [json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A","title":"json.exception.parse_error.110"},{"location":"home/exceptions/#jsonexceptionparse_error112","text":"An unexpected byte was read in a binary format or length information is invalid ( BSON ). Example messages [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02 [json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648 [json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1","title":"json.exception.parse_error.112"},{"location":"home/exceptions/#jsonexceptionparse_error113","text":"While parsing a map key, a value that is not a string has been read. Example messages [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF [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 [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","title":"json.exception.parse_error.113"},{"location":"home/exceptions/#jsonexceptionparse_error114","text":"The parsing of the corresponding BSON record type is not implemented (yet). Example message [json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF","title":"json.exception.parse_error.114"},{"location":"home/exceptions/#jsonexceptionparse_error115","text":"A UBJSON high-precision number could not be parsed. Example message [json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A","title":"json.exception.parse_error.115"},{"location":"home/exceptions/#iterator-errors","text":"This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. Example The following code shows how an invalid_iterator exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling iterator::key() on non-object iterator json j = \"string\" ; json :: iterator it = j . begin (); auto k = it . key (); } catch ( const json :: invalid_iterator & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators exception id: 207","title":"Iterator errors"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator201","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range ( first , last ) is invalid. Example message [json.exception.invalid_iterator.201] iterators are not compatible","title":"json.exception.invalid_iterator.201"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator202","text":"In the erase or insert function, the passed iterator pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. Example messages [json.exception.invalid_iterator.202] iterator does not fit current value [json.exception.invalid_iterator.202] iterators first and last must point to objects","title":"json.exception.invalid_iterator.202"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator203","text":"Either iterator passed to function erase(IteratorType first, IteratorType last ) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. Example message [json.exception.invalid_iterator.203] iterators do not fit current value","title":"json.exception.invalid_iterator.203"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator204","text":"When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly ( begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid. Example message [json.exception.invalid_iterator.204] iterators out of range","title":"json.exception.invalid_iterator.204"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator205","text":"When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. Example message [json.exception.invalid_iterator.205] iterator out of range","title":"json.exception.invalid_iterator.205"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator206","text":"The iterators passed to constructor basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. Example message [json.exception.invalid_iterator.206] cannot construct with iterators from null","title":"json.exception.invalid_iterator.206"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator207","text":"The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. Example message [json.exception.invalid_iterator.207] cannot use key() for non-object iterators","title":"json.exception.invalid_iterator.207"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator208","text":"The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.208] cannot use operator[] for object iterators","title":"json.exception.invalid_iterator.208"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator209","text":"The offset operators ( + , - , += , -= ) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. Example message [json.exception.invalid_iterator.209] cannot use offsets with object iterators","title":"json.exception.invalid_iterator.209"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator210","text":"The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range ( first , last ) is invalid. Example message [json.exception.invalid_iterator.210] iterators do not fit","title":"json.exception.invalid_iterator.210"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator211","text":"The iterator range passed to the insert function must not be a subrange of the container to insert to. Example message [json.exception.invalid_iterator.211] passed iterators may not belong to container","title":"json.exception.invalid_iterator.211"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator212","text":"When two iterators are compared, they must belong to the same container. Example message [json.exception.invalid_iterator.212] cannot compare iterators of different containers","title":"json.exception.invalid_iterator.212"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator213","text":"The order of object iterators cannot be compared, because JSON objects are unordered. Example message [json.exception.invalid_iterator.213] cannot compare order of object iterators","title":"json.exception.invalid_iterator.213"},{"location":"home/exceptions/#jsonexceptioninvalid_iterator214","text":"Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin() . Example message [json.exception.invalid_iterator.214] cannot get value","title":"json.exception.invalid_iterator.214"},{"location":"home/exceptions/#type-errors","text":"This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. Example The following code shows how a type_error exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling push_back() on a string value json j = \"string\" ; j . push_back ( \"another string\" ); } catch ( const json :: type_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.type_error.308] cannot use push_back() with string exception id: 308","title":"Type errors"},{"location":"home/exceptions/#jsonexceptiontype_error301","text":"To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. Example message [json.exception.type_error.301] cannot create object from initializer list","title":"json.exception.type_error.301"},{"location":"home/exceptions/#jsonexceptiontype_error302","text":"During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. Example messages [json.exception.type_error.302] type must be object, but is null [json.exception.type_error.302] type must be string, but is object","title":"json.exception.type_error.302"},{"location":"home/exceptions/#jsonexceptiontype_error303","text":"To retrieve a reference to a value stored in a basic_json object with get_ref , the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t & . Example messages [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number\"","title":"json.exception.type_error.303"},{"location":"home/exceptions/#jsonexceptiontype_error304","text":"The at() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.304] cannot use at() with string [json.exception.type_error.304] cannot use at() with number","title":"json.exception.type_error.304"},{"location":"home/exceptions/#jsonexceptiontype_error305","text":"The operator[] member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.305] cannot use operator[] with a string argument with array [json.exception.type_error.305] cannot use operator[] with a numeric argument with object","title":"json.exception.type_error.305"},{"location":"home/exceptions/#jsonexceptiontype_error306","text":"The value() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.306] cannot use value() with number","title":"json.exception.type_error.306"},{"location":"home/exceptions/#jsonexceptiontype_error307","text":"The erase() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.307] cannot use erase() with string","title":"json.exception.type_error.307"},{"location":"home/exceptions/#jsonexceptiontype_error308","text":"The push_back() and operator+= member functions can only be executed for certain JSON types. Example message [json.exception.type_error.308] cannot use push_back() with string","title":"json.exception.type_error.308"},{"location":"home/exceptions/#jsonexceptiontype_error309","text":"The insert() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.309] cannot use insert() with array [json.exception.type_error.309] cannot use insert() with number","title":"json.exception.type_error.309"},{"location":"home/exceptions/#jsonexceptiontype_error310","text":"The swap() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.310] cannot use swap() with number","title":"json.exception.type_error.310"},{"location":"home/exceptions/#jsonexceptiontype_error311","text":"The emplace() and emplace_back() member functions can only be executed for certain JSON types. Example messages [json.exception.type_error.311] cannot use emplace() with number [json.exception.type_error.311] cannot use emplace_back() with number","title":"json.exception.type_error.311"},{"location":"home/exceptions/#jsonexceptiontype_error312","text":"The update() member functions can only be executed for certain JSON types. Example message [json.exception.type_error.312] cannot use update() with array","title":"json.exception.type_error.312"},{"location":"home/exceptions/#jsonexceptiontype_error313","text":"The unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined. Example message [json.exception.type_error.313] invalid value to unflatten","title":"json.exception.type_error.313"},{"location":"home/exceptions/#jsonexceptiontype_error314","text":"The unflatten function only works for an object whose keys are JSON Pointers. Example message Calling unflatten() on an array [ 1 , 2 , 3 ] : [json.exception.type_error.314] only objects can be unflattened","title":"json.exception.type_error.314"},{"location":"home/exceptions/#jsonexceptiontype_error315","text":"The unflatten() function only works for an object whose keys are JSON Pointers and whose values are primitive. Example message Calling unflatten() on an object { \"/1\" , [ 1 , 2 , 3 ]} : [json.exception.type_error.315] values in object must be primitive","title":"json.exception.type_error.315"},{"location":"home/exceptions/#jsonexceptiontype_error316","text":"The dump() function only works with UTF-8 encoded strings; that is, if you assign a std::string to a JSON value, make sure it is UTF-8 encoded. Example message Calling dump() on a JSON value containing an ISO 8859-1 encoded string: [json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F Tip Store the source file with UTF-8 encoding. Pass an error handler as last parameter to the dump() function to avoid this exception: json::error_handler_t::replace will replace invalid bytes sequences with U+FFFD json::error_handler_t::ignore will silently ignore invalid byte sequences","title":"json.exception.type_error.316"},{"location":"home/exceptions/#jsonexceptiontype_error317","text":"The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true or null JSON object cannot be serialized to BSON) Example messages Serializing null to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null Serializing [ 1 , 2 , 3 ] to BSON: [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array Tip Encapsulate the JSON value in an object. That is, instead of serializing true , serialize { \"value\" : true }","title":"json.exception.type_error.317"},{"location":"home/exceptions/#out-of-range","text":"This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. Example The following code shows how an out_of_range exception can be caught. #include #include using json = nlohmann :: json ; int main () { try { // calling at() for an invalid index json j = { 1 , 2 , 3 , 4 }; j . at ( 4 ) = 10 ; } catch ( const json :: out_of_range & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.out_of_range.401] array index 4 is out of range exception id: 401","title":"Out of range"},{"location":"home/exceptions/#jsonexceptionout_of_range401","text":"The provided array index i is larger than size-1 . Example message array index 3 is out of range","title":"json.exception.out_of_range.401"},{"location":"home/exceptions/#jsonexceptionout_of_range402","text":"The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. Example message array index '-' (3) is out of range","title":"json.exception.out_of_range.402"},{"location":"home/exceptions/#jsonexceptionout_of_range403","text":"The provided key was not found in the JSON object. Example message key 'foo' not found","title":"json.exception.out_of_range.403"},{"location":"home/exceptions/#jsonexceptionout_of_range404","text":"A reference token in a JSON Pointer could not be resolved. Example message unresolved reference token 'foo'","title":"json.exception.out_of_range.404"},{"location":"home/exceptions/#jsonexceptionout_of_range405","text":"The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. Example message JSON pointer has no parent","title":"json.exception.out_of_range.405"},{"location":"home/exceptions/#jsonexceptionout_of_range406","text":"A parsed number could not be stored as without changing it to NaN or INF. Example message number overflow parsing '10E1000'","title":"json.exception.out_of_range.406"},{"location":"home/exceptions/#jsonexceptionout_of_range407","text":"UBJSON and BSON only support integer numbers up to 9223372036854775807. Example message number overflow serializing '9223372036854775808' Note Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.","title":"json.exception.out_of_range.407"},{"location":"home/exceptions/#jsonexceptionout_of_range408","text":"The size (following # ) of an UBJSON array or object exceeds the maximal capacity. Example message excessive array size: 8658170730974374167","title":"json.exception.out_of_range.408"},{"location":"home/exceptions/#jsonexceptionout_of_range409","text":"Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string. Example message BSON key cannot contain code point U+0000 (at byte 2)","title":"json.exception.out_of_range.409"},{"location":"home/exceptions/#further-exceptions","text":"This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. Example The following code shows how an other_error exception can be caught. #include #include using json = nlohmann :: json ; using namespace nlohmann :: literals ; int main () { try { // executing a failing JSON Patch operation json value = R \" ( { \"best_biscuit\": { \"name\": \"Oreo\" } } ) \" _json ; json patch = R \" ( [{ \"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Leibniz\" }] ) \" _json ; value . patch ( patch ); } catch ( const json :: other_error & e ) { // output exception information std :: cout << \"message: \" << e . what () << '\\n' << \"exception id: \" << e . id << std :: endl ; } } Output: message: [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/best_biscuit/name\",\"value\":\"Choco Leibniz\"} exception id: 501","title":"Further exceptions"},{"location":"home/exceptions/#jsonexceptionother_error501","text":"A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. Example message Executing { \"op\" : \"test\" , \"path\" : \"/baz\" , \"value\" : \"bar\" } on { \"baz\" : \"qux\" } : [json.exception.other_error.501] unsuccessful: {\"op\":\"test\",\"path\":\"/baz\",\"value\":\"bar\"}","title":"json.exception.other_error.501"},{"location":"home/faq/","text":"Frequently Asked Questions (FAQ) \u00b6 Known bugs \u00b6 Brace initialization yields arrays \u00b6 Question Why does json j { true }; and json j ( true ); yield different results ( [ true ] vs. true )? This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like json array = { 1 , 2 , 3 , 4 }; for arrays and json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; 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. Limitations \u00b6 Relaxed parsing \u00b6 Question Can you add an option to ignore trailing commas? This library does not support any feature which would jeopardize interoperability. Parse errors reading non-ASCII characters \u00b6 Questions 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. Wide string handling \u00b6 Question Why are wide strings (e.g., std::wstring ) dumped as arrays of numbers? As described above , the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding. Example #include // codecvt_utf8 #include // wstring_convert // encoding function std :: string to_utf8 ( std :: wstring & wide_string ) { static std :: wstring_convert < std :: codecvt_utf8 < wchar_t >> utf8_conv ; return utf8_conv . to_bytes ( wide_string ); } json j ; std :: wstring ws = L \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" ; j [ \"original\" ] = ws ; j [ \"encoded\" ] = to_utf8 ( ws ); std :: cout << j << std :: endl ; The result is: { \"encoded\" : \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" , \"original\" : [ 36554 , 66 , 49 , 50 , 51 , 52 , 32 , 12371 , 12435 , 12395 , 12385 , 12399 ] } Exceptions \u00b6 Parsing without exceptions \u00b6 Question Is it possible to indicate a parse error without throwing an exception? Yes, see Parsing and exceptions . Key name in exceptions \u00b6 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 . Serialization issues \u00b6 Number precision \u00b6 Question 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::digits10 (15 for IEEE double s) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip. cppreference.com The value of std::numeric_limits::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. Compilation issues \u00b6 Android SDK \u00b6 Question Why does the code not compile with Android SDK? Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk . This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default. APP_STL : = c++_shared NDK_TOOLCHAIN_VERSION : = clang3.6 APP_CPPFLAGS + = -frtti -fexceptions The code compiles successfully with Android NDK , Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10. Missing STL function \u00b6 Questions 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 .","title":"FAQ"},{"location":"home/faq/#frequently-asked-questions-faq","text":"","title":"Frequently Asked Questions (FAQ)"},{"location":"home/faq/#known-bugs","text":"","title":"Known bugs"},{"location":"home/faq/#brace-initialization-yields-arrays","text":"Question Why does json j { true }; and json j ( true ); yield different results ( [ true ] vs. true )? This is a known issue, and -- even worse -- the behavior differs between GCC and Clang. The \"culprit\" for this is the library's constructor overloads for initializer lists to allow syntax like json array = { 1 , 2 , 3 , 4 }; for arrays and json object = {{ \"one\" , 1 }, { \"two\" , 2 }}; 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.","title":"Brace initialization yields arrays"},{"location":"home/faq/#limitations","text":"","title":"Limitations"},{"location":"home/faq/#relaxed-parsing","text":"Question Can you add an option to ignore trailing commas? This library does not support any feature which would jeopardize interoperability.","title":"Relaxed parsing"},{"location":"home/faq/#parse-errors-reading-non-ascii-characters","text":"Questions 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.","title":"Parse errors reading non-ASCII characters"},{"location":"home/faq/#wide-string-handling","text":"Question Why are wide strings (e.g., std::wstring ) dumped as arrays of numbers? As described above , the library assumes UTF-8 as encoding. To store a wide string, you need to change the encoding. Example #include // codecvt_utf8 #include // wstring_convert // encoding function std :: string to_utf8 ( std :: wstring & wide_string ) { static std :: wstring_convert < std :: codecvt_utf8 < wchar_t >> utf8_conv ; return utf8_conv . to_bytes ( wide_string ); } json j ; std :: wstring ws = L \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" ; j [ \"original\" ] = ws ; j [ \"encoded\" ] = to_utf8 ( ws ); std :: cout << j << std :: endl ; The result is: { \"encoded\" : \"\u8ecaB1234 \u3053\u3093\u306b\u3061\u306f\" , \"original\" : [ 36554 , 66 , 49 , 50 , 51 , 52 , 32 , 12371 , 12435 , 12395 , 12385 , 12399 ] }","title":"Wide string handling"},{"location":"home/faq/#exceptions","text":"","title":"Exceptions"},{"location":"home/faq/#parsing-without-exceptions","text":"Question Is it possible to indicate a parse error without throwing an exception? Yes, see Parsing and exceptions .","title":"Parsing without exceptions"},{"location":"home/faq/#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 .","title":"Key name in exceptions"},{"location":"home/faq/#serialization-issues","text":"","title":"Serialization issues"},{"location":"home/faq/#number-precision","text":"Question 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::digits10 (15 for IEEE double s) digits for serialization. This value is sufficient to guarantee roundtripping. If one uses more than this number of digits of precision, then string -> value -> string is not guaranteed to round-trip. cppreference.com The value of std::numeric_limits::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.","title":"Number precision"},{"location":"home/faq/#compilation-issues","text":"","title":"Compilation issues"},{"location":"home/faq/#android-sdk","text":"Question Why does the code not compile with Android SDK? Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your Application.mk . This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default. APP_STL : = c++_shared NDK_TOOLCHAIN_VERSION : = clang3.6 APP_CPPFLAGS + = -frtti -fexceptions The code compiles successfully with Android NDK , Revision 9 - 11 (and possibly later) and CrystaX's Android NDK version 10.","title":"Android SDK"},{"location":"home/faq/#missing-stl-function","text":"Questions 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 .","title":"Missing STL function"},{"location":"home/license/","text":"License \u00b6 The class is licensed under the MIT License : Copyright \u00a9 2013-2022 Niels Lohmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0 .","title":"License"},{"location":"home/license/#license","text":"The class is licensed under the MIT License : Copyright \u00a9 2013-2022 Niels Lohmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the MIT License (see above). Copyright \u00a9 2008-2009 Bj\u00f6rn Hoehrmann bjoern@hoehrmann.de The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the MIT License (see above). Copyright \u00a9 2009 Florian Loitsch The class contains a copy of Hedley from Evan Nemerson which is licensed as CC0-1.0 .","title":"License"},{"location":"home/releases/","text":"Releases \u00b6 v3.7.3 \u00b6 Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip) Summary \u00b6 This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible. Bug Fixes \u00b6 Removed reserve() calls from the destructor which could lead to quadratic complexity. #1837 #1838 Deprecated functions \u00b6 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. v3.7.2 \u00b6 Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip) Summary \u00b6 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. Bug Fixes \u00b6 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 Further Changes \u00b6 Added WhiteStone Bolt. #1830 Deprecated functions \u00b6 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. v3.7.1 \u00b6 Files include.zip (273 KB) include.zip.asc (1 KB) json.hpp (789 KB) json.hpp.asc (1 KB) Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip) Summary \u00b6 This release fixes several small bugs in the library. All changes are backward-compatible. Bug Fixes \u00b6 Fixed a segmentation fault when serializing std::int64_t minimum value. #1708 #1722 Fixed the contains() function for JSON Pointers. #1727 #1741 Fixed too lax SFINAE guard for conversion from std::pair and std::tuple to json . #1805 #1806 #1825 #1826 Fixed some regressions detected by UBSAN. Updated CI to use Clang-Tidy 7.1.0. #1716 #1728 Fixed integer truncation in iteration_proxy . #1797 Updated Hedley to v11 to fix a E2512 error in MSVC. #1799 Fixed a compile error in enum deserialization of non non-default-constructible types. #1647 #1821 Fixed the conversion from json to std::valarray . Improvements \u00b6 The items() function can now be used with a custom string type. #1765 Made json_pointer::back const . #1764 #1769 Meson is part of the release archive. #1672 #1694 Improved documentation on the Meson and Spack package manager. #1694 #1720 Further Changes \u00b6 Added GitHub Workflow with ubuntu-latest /GCC 7.4.0 as CI step. Added GCC 9 to Travis CI to compile with C++20 support. #1724 Added MSVC 2019 to the AppVeyor CI. #1780 Added badge to fuzzing status . Fixed some cppcheck warnings. #1760 Fixed several typos in the documentation. #1720 #1767 #1803 Added documentation on the JSON_THROW_USER , JSON_TRY_USER , and JSON_CATCH_USER macros to control user-defined exception handling. Used GitHub's CODEOWNERS and SECURITY feature. Removed GLOB from CMake files. #1779 Updated to Doctest 2.3.5. Deprecated functions \u00b6 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. v3.7.0 \u00b6 Files include.zip (143 KB) include.zip.asc (1 KB) json.hpp (782 KB) json.hpp.asc (1 KB) Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip) Summary \u00b6 This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible. New Features \u00b6 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 Bug Fixes \u00b6 Fix an issue where typedefs with certain names yielded a compilation error. #1642 #1643 Fix a conversion to std::string_view in the unit tests. #1634 #1639 Fix MSVC Debug build. #1536 #1570 #1608 Fix get_to method to clear existing content before writing. #1511 #1555 Fix a -Wc++17-extensions warning. nodiscard attributes are now only used with Clang when -std=c++17 is used. #1535 #1551 Improvements \u00b6 Switch from Catch to doctest for the unit tests which speeds up compilation and runtime of the 112,112,308 tests. Add an explicit section to the README about the frequently addressed topics character encoding , comments in JSON , and the order of object keys . Further Changes \u00b6 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. Deprecated functions \u00b6 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. v3.6.1 \u00b6 Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip) Summary \u00b6 This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible. Bug Fixes \u00b6 Fixed regression of #590 which could lead to compilation errors with GCC 7 and GCC 8. #1530 Fixed a compilation error when was included. #1531 Further Changes \u00b6 Fixed a warning for missing field initializers. #1527 Deprecated functions \u00b6 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. v3.6.0 \u00b6 Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip) \u2139\ufe0f This release introduced a regression. Please update to version 3.6.1 ! Summary \u00b6 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. New Features \u00b6 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 Bug Fixes \u00b6 Fixed a compilation issues with libc 2.12. #1483 #1514 Fixed endian conversion on PPC64. #1489 Fixed library to compile with GCC 9. #1472 #1492 Fixed a compilation issue with GCC 7 on CentOS. #1496 Fixed an integer overflow. #1447 Fixed buffer flushing in serializer. #1445 #1446 Improvements \u00b6 The performance of dumping integers has been greatly improved. #1411 Added CMake parameter JSON_Install to control whether the library should be installed (default: on). #1330 Fixed a lot of compiler and linter warnings. #1400 #1435 #1502 Reduced required CMake version from 3.8 to 3.1. #1409 #1428 #1441 #1498 Added nodiscard attribute to meta() , array() , object() , from_cbor , from_msgpack , from_ubjson , from_bson , and parse . #1433 Further Changes \u00b6 Added missing headers. #1500 Fixed typos and broken links in README. #1417 #1423 #1425 #1451 #1455 #1491 Fixed documentation of parse function. #1473 Suppressed warning that cannot be fixed inside the library. #1401 #1468 Imroved package manager suppert: Updated Buckaroo instructions. #1495 Improved Meson support. #1463 Added Conda package manager documentation. #1430 Added NuGet package manager documentation. #1132 Continuous Integration Removed unstable or deprecated Travis builders (Xcode 6.4 - 8.2) and added Xcode 10.1 builder. Added Clang 7 to Travis CI. Fixed AppVeyor x64 builds. #1374 #1414 Updated thirdparty libraries: Catch 1.12.0 -> 1.12.2 Google Benchmark 1.3.0 -> 1.4.1 Doxygen 1.8.15 -> 1.8.16 Deprecated functions \u00b6 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. v3.5.0 \u00b6 Files include.zip (133 KB) include.zip.asc (1 KB) json.hpp (693 KB) json.hpp.asc (1 KB) Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip) Summary \u00b6 This release introduces the support for structured bindings and reading from FILE* . Besides, a few bugs have been fixed. All changes are backward-compatible. New Features \u00b6 Structured bindings are now supported for JSON objects and arrays via the items() member function, so finally this code is possible: for ( auto & [ key , val ] : j . items ()) { std :: cout << key << ':' << val << '\\n' ; } #1388 #1391 Added support for reading from FILE* to support situations in which streams are nit available or would require too much RAM. #1370 #1392 Bug Fixes \u00b6 The eofbit was not set for input streams when the end of a stream was reached while parsing. #1340 #1343 Fixed a bug in the SAX parser for BSON arrays. Improvements \u00b6 Added support for Clang 5.0.1 (PS4 version). #1341 #1342 Further Changes \u00b6 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 Added code to allow installation via Meson. #1345 Deprecated functions \u00b6 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. v3.4.0 \u00b6 Files include.zip (132 KB) include.zip.asc (1 KB) json.hpp (689 KB) json.hpp.asc (1 KB) Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip) Summary \u00b6 This release introduces three new features: 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. New Features \u00b6 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 Bug Fixes \u00b6 fixed truncation #1286 #1315 fixed an issue with std::pair #1299 #1301 fixed an issue with std::variant #1292 #1294 fixed a bug in the JSON Pointer parser Improvements \u00b6 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: '' 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: '' . #1280 #1288 #1303 Further Changes \u00b6 improved Meson documentation #1305 fixed some more linter warnings #1280 fixed Clang detection for third-party Google Benchmark library #1277 Deprecated functions \u00b6 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. v3.3.0 \u00b6 Files include.zip (123 KB) include.zip.asc (1 KB) json.hpp (635 KB) json.hpp.asc (1 KB) Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip) Summary \u00b6 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. New Features \u00b6 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 Bug Fixes \u00b6 Fixed a bug in the CMake file that made target_link_libraries to not properly include nlohmann_json . #1243 #1245 #1260 Fixed a warning in MSVC 2017 complaining about a constexpr if. #1204 #1268 #1272 Fixed a bug that prevented compilation with ICPC. #755 #1222 Improved the SFINAE correctness to fix a bug in the conversion operator. #1237 #1238 Fixed a -Wctor-dtor-privacy warning. #1224 Fixed a warning on a lambda in unevaluated context. #1225 #1230 Fixed a bug introduced in version 3.2.0 where defining JSON_CATCH_USER led to duplicate macro definition of JSON_INTERNAL_CATCH . #1213 #1214 Fixed a bug that prevented compilation with Clang 3.4.2 in RHEL 7. #1179 #1249 Improvements \u00b6 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 Further Changes \u00b6 GCC 4.8 and Xcode 10 were added to the continuous integration suite at Travis. Added lgtm checks to pull requests. Added tests for CMake integration. #1260 Deprecated functions \u00b6 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. v3.2.0 \u00b6 Files include.zip (124 KB) include.zip.asc (1 KB) json.hpp (636 KB) json.hpp.asc (1 KB) Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip) Summary \u00b6 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 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. New Features \u00b6 added a parser with a SAX interface (#971, #1153) 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) Bug Fixes \u00b6 allow to create nullptr_t from JSON allowing to properly roundtrip null values (#1169) allow compare user-defined string types (#1130) better support for algorithms using iterators from items() (#1045, #1134) added parameter to avoid compilation error with MSVC 2015 debug builds (#1114) re-added accidentally skipped unit tests (#1176) fixed MSVC issue with std::swap (#1168) Improvements \u00b6 key() function for iterators returns a const reference rather than a string copy (#1098) binary formats CBOR, MessagePack, and UBJSON now supports float as type for floating-point numbers (#1021) Further Changes \u00b6 changed issue templates 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 updated to Catch 1.12.0 Deprecated functions \u00b6 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. v3.1.2 \u00b6 Files include.zip (115 KB) include.zip.asc (1 KB) json.hpp (582 KB) json.hpp.asc (1 KB) Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip) Summary \u00b6 This release fixes several bugs in the library. All changes are backward-compatible. Bug Fixes \u00b6 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). Improvements \u00b6 The parser and the serialization now support user-defined string types (#1006, #1009). Further Changes \u00b6 Clang Analyzer is now used as additional static analyzer; see make clang_analyze . Overworked README by adding links to the documentation (#981). Deprecated functions \u00b6 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. v3.1.1 \u00b6 Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip) Summary \u00b6 This release fixes several bugs in the library. All changes are backward-compatible. Bug Fixes \u00b6 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() . Further Changes \u00b6 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 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). Deprecated functions \u00b6 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. v3.1.0 \u00b6 Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip) Summary \u00b6 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. New features \u00b6 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. Improvements \u00b6 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. Reorganization \u00b6 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). Further changes \u00b6 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. Deprecated functions \u00b6 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): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead. v3.0.1 \u00b6 Files json.hpp (502 KB) json.hpp.asc (1 KB) Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c Summary \u00b6 This release fixes small issues in the implementation of JSON Pointer and JSON Patch . All changes are backward-compatible. Changes \u00b6 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) Fixed some compiler warnings (see #858, #882). Deprecated functions \u00b6 To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead. v3.0.0 \u00b6 Files json.hpp (501 KB) json.hpp.asc (1 KB) Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462 Summary \u00b6 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. Breaking changes \u00b6 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 (#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 , , and 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). Deprecated functions \u00b6 To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead. New features \u00b6 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 (#494). Fixed support for std::valarray (#702), std::array (#553), and std::map (#600, #607). Further changes \u00b6 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. Moving from 2.x.x to 3.0.0 \u00b6 User-defined Exceptions \u00b6 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: new exception previous exception parse_error.101 invalid_argument parse_error.102 invalid_argument parse_error.103 invalid_argument parse_error.104 invalid_argument parse_error.105 invalid_argument parse_error.106 domain_error parse_error.107 domain_error parse_error.108 domain_error parse_error.109 invalid_argument parse_error.110 out_of_range parse_error.111 invalid_argument parse_error.112 invalid_argument invalid_iterator.201 domain_error invalid_iterator.202 domain_error invalid_iterator.203 domain_error invalid_iterator.204 out_of_range invalid_iterator.205 out_of_range invalid_iterator.206 domain_error invalid_iterator.207 domain_error invalid_iterator.208 domain_error invalid_iterator.209 domain_error invalid_iterator.210 domain_error invalid_iterator.211 domain_error invalid_iterator.212 domain_error invalid_iterator.213 domain_error invalid_iterator.214 out_of_range type_error.301 domain_error type_error.302 domain_error type_error.303 domain_error type_error.304 domain_error type_error.305 domain_error type_error.306 domain_error type_error.307 domain_error type_error.308 domain_error type_error.309 domain_error type_error.310 domain_error type_error.311 domain_error type_error.313 domain_error type_error.314 domain_error type_error.315 domain_error out_of_range.401 out_of_range out_of_range.402 out_of_range out_of_range.403 out_of_range out_of_range.404 out_of_range out_of_range.405 domain_error other_error.501 domain_error Handling of NaN and INF \u00b6 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 . Removal of deprecated functions \u00b6 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 ); New code: json j = json :: parse ( ss , cb ); If no callback function is used, also the following code works: json j ; j << ss ; or json j ; ss >> j ; v2.1.1 \u00b6 Files json.hpp (437 KB) json.hpp.asc (1 KB) Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57 Summary \u00b6 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. Changes \u00b6 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 . Removed Doozer. Added Codacity. Upgraded Catch to version 1.7.2. v2.1.0 \u00b6 Files json.hpp (426 KB) json.hpp.asc (1 KB) Release date: 2017-01-28 SHA-256: a571dee92515b685784fd527e38405cf3f5e13e96edbfe3f03d6df2e363a767b Summary \u00b6 This release introduces a means to convert from/to user-defined types. The release is backwards compatible. Changes \u00b6 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. Updated to Catch v1.6.0 . Some typos in the documentation have been fixed. v2.0.10 \u00b6 Files json.hpp (409 KB) json.hpp.asc (1 KB) Release date: 2017-01-02 SHA-256: ec27d4e74e9ce0f78066389a70724afd07f10761009322dc020656704ad5296d Summary \u00b6 This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible. Changes \u00b6 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. v2.0.9 \u00b6 Files json.hpp (406 KB) json.hpp.asc (1 KB) Release date: 2016-12-16 SHA-256: fbf3396f13e187d6c214c297bddc742d918ea9b55e10bfb3d9f458b9bfdc22e5 Summary \u00b6 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. Changes \u00b6 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 test suite now contains 11201886 tests v2.0.8 \u00b6 Files json.hpp (360 KB) json.hpp.asc (1 KB) Release date: 2016-12-02 SHA-256: b70db0ad34f8e0e61dc3f0cbab88099336c9674c193d8a3439d93d6aca2d7120 Summary \u00b6 This release combines a lot of small fixes and improvements. The fixes are backwards compatible. Changes \u00b6 fixed a bug that froze the parser if a passed file was not found (now, std::invalid_argument is thrown) fixed a bug that lead to an error of a file at EOF was parsed again (now, std::invalid_argument is thrown) the well known functions emplace and emplace_back have been added to JSON values and work as expected improved the performance of the serialization ( dump function) improved the performance of the deserialization (parser) some continuous integration images at Travis were added and retired; see here for the current continuous integration setup the Coverity scan works again the benchmarking code has been improved to produce more stable results the README file has been extended and includes more frequently asked examples the test suite now contains 8905518 tests updated Catch to version 1.5.8 v2.0.7 \u00b6 Files json.hpp (355 KB) json.hpp.asc (1 KB) Release date: 2016-11-02 SHA-256: 5545c323670f8165bae90b9dc6078825e86ec310d96cc4e5b47233ea43715bbf Summary \u00b6 This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible. Changes \u00b6 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. v2.0.6 \u00b6 Files json.hpp (349 KB) json.hpp.asc (1 KB) Release date: 2016-10-15 SHA256: 459cc93d5e2f503e50c6d5876eb86bfea7daf405f5a567c5a2c9abc2383756ae Summary \u00b6 This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible. Changes \u00b6 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 restored test coverage to 100%. v2.0.5 \u00b6 Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-14 SHA-256: 8b7565263a44e2b7d3b89808bc73d2d639037ff0c1f379e3d56dbd77e00b98d9 Summary \u00b6 This release fixes a regression bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible. Changes \u00b6 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. v2.0.4 \u00b6 Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-11 SHA-256: 632ceec4c25c4e2153f71470d3a2b992c8355f6d8b4d627d05dd16095cd3aeda Summary \u00b6 This release fixes a bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible. Changes \u00b6 Bug fix : The end of a file stream was not detected properly which led to parse errors. Fixed a compiler warning about an unused variable. v2.0.3 \u00b6 Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-08-31 SHA-256: 535b73efe5546fde9e763c14aeadfc7b58183c0b3cd43c29741025aba6cf6bd3 Summary \u00b6 This release combines a lot of small fixes and improvements. The release is backwards compatible. Changes \u00b6 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. v2.0.2 \u00b6 Files json.hpp (338 KB) json.hpp.asc (1 KB) Release date: 2016-07-31 SHA-256: 8e97b7965b4594b00998d6704465412360e1a0ed927badb51ded8b82291a8f3d Summary \u00b6 This release combines a lot of small fixes and improvements. The release is backwards compatible. Changes \u00b6 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. Avoided output to std::cout in the test cases. v2.0.1 \u00b6 Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-28 SHA-256: ef550fcd7df572555bf068e9ec4e9d3b9e4cdd441cecb0dcea9ea7fd313f72dd Summary \u00b6 This release fixes a performance regression in the JSON serialization (function dump() ). This fix is backwards compatible. Changes \u00b6 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. v2.0.0 \u00b6 Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-24 SHA-256: ac9e1fb25c2ac9ca5fc501fcd2fe3281fe04f07018a1b48820e7b1b11491bb6c Summary \u00b6 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. Changes \u00b6 \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 ). Added noexcept specifier to basic_json(boolean_t) , basic_json(const number_integer_t) , basic_json(const int) , basic_json(const number_float_t) , iterator functions ( begin() , end() , etc.) When parsing numbers, the sign of 0.0 (vs. -0.0 ) is preserved. Improved MSVC 2015, Android, and MinGW support. See README for more information. Improved test coverage (added 2,225,386 tests). Removed some misuses of std::move . Fixed several compiler warnings. Improved error messages from JSON parser. Updated to re2c to version 0.16 to use a minimal DFAs for the lexer. Updated test suite to use Catch version 1.5.6. Made type getters ( is_number , etc.) and const value access constexpr . Functions push_back and operator+= now work with key/value pairs passed as initializer list, e.g. j_object += {\"key\", 1} . Overworked CMakeLists.txt to make it easier to integrate the library into other projects. Notes \u00b6 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. v1.1.0 \u00b6 Files json.hpp (257 KB) json.hpp.asc (1 KB) Release date: 2016-01-24 SHA-256: c0cf0e3017798ca6bb18e757ebc570d21a3bdac877845e2b9e9573d183ed2f05 Summary \u00b6 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: Changes \u00b6 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] Notes \u00b6 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. v1.0.0 \u00b6 Files json.hpp (243 KB) json.hpp.asc (1 KB) Release date: 2015-12-28 SHA-256: 767dc2fab1819d7b9e19b6e456d61e38d21ef7182606ecf01516e3f5230446de Summary \u00b6 This is the first official release. Compared to the prerelease version 1.0.0-rc1 , only a few minor improvements have been made: Changes \u00b6 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.","title":"Releases"},{"location":"home/releases/#releases","text":"","title":"Releases"},{"location":"home/releases/#v373","text":"Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-17 SHA-256: 3b5d2b8f8282b80557091514d8ab97e27f9574336c804ee666fda673a9b59926 (json.hpp), 87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014 (include.zip)","title":"v3.7.3"},{"location":"home/releases/#summary","text":"This release fixes a bug introduced in release 3.7.2 which could yield quadratic complexity in destructor calls. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes","text":"Removed reserve() calls from the destructor which could lead to quadratic complexity. #1837 #1838","title":"Bug Fixes"},{"location":"home/releases/#deprecated-functions","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v372","text":"Files include.zip (274 KB) include.zip.asc (1 KB) json.hpp (791 KB) json.hpp.asc (1 KB) Release date: 2019-11-10 SHA-256: 0a65fcbbe1b334d3f45c9498e5ee28c3f3b2428aea98557da4a3ff12f0f14ad6 (json.hpp), 67f69c9a93b7fa0612dc1b6273119d2c560317333581845f358aaa68bff8f087 (include.zip)","title":"v3.7.2"},{"location":"home/releases/#summary_1","text":"Project bad_json_parsers tested how JSON parser libraries react on deeply nested inputs . It turns out that this library segfaulted at a certain nesting depth. This bug was fixed with this release. Now the parsing is only bounded by the available memory. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_1","text":"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","title":"Bug Fixes"},{"location":"home/releases/#further-changes","text":"Added WhiteStone Bolt. #1830","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_1","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v371","text":"Files include.zip (273 KB) include.zip.asc (1 KB) json.hpp (789 KB) json.hpp.asc (1 KB) Release date: 2019-11-06 SHA-256: b5ba7228f3c22a882d379e93d08eab4349458ee16fbf45291347994eac7dc7ce (json.hpp), 77b9f54b34e7989e6f402afb516f7ff2830df551c3a36973085e2c7a6b1045fe (include.zip)","title":"v3.7.1"},{"location":"home/releases/#summary_2","text":"This release fixes several small bugs in the library. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_2","text":"Fixed a segmentation fault when serializing std::int64_t minimum value. #1708 #1722 Fixed the contains() function for JSON Pointers. #1727 #1741 Fixed too lax SFINAE guard for conversion from std::pair and std::tuple to json . #1805 #1806 #1825 #1826 Fixed some regressions detected by UBSAN. Updated CI to use Clang-Tidy 7.1.0. #1716 #1728 Fixed integer truncation in iteration_proxy . #1797 Updated Hedley to v11 to fix a E2512 error in MSVC. #1799 Fixed a compile error in enum deserialization of non non-default-constructible types. #1647 #1821 Fixed the conversion from json to std::valarray .","title":"Bug Fixes"},{"location":"home/releases/#improvements","text":"The items() function can now be used with a custom string type. #1765 Made json_pointer::back const . #1764 #1769 Meson is part of the release archive. #1672 #1694 Improved documentation on the Meson and Spack package manager. #1694 #1720","title":"Improvements"},{"location":"home/releases/#further-changes_1","text":"Added GitHub Workflow with ubuntu-latest /GCC 7.4.0 as CI step. Added GCC 9 to Travis CI to compile with C++20 support. #1724 Added MSVC 2019 to the AppVeyor CI. #1780 Added badge to fuzzing status . Fixed some cppcheck warnings. #1760 Fixed several typos in the documentation. #1720 #1767 #1803 Added documentation on the JSON_THROW_USER , JSON_TRY_USER , and JSON_CATCH_USER macros to control user-defined exception handling. Used GitHub's CODEOWNERS and SECURITY feature. Removed GLOB from CMake files. #1779 Updated to Doctest 2.3.5.","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_2","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v370","text":"Files include.zip (143 KB) include.zip.asc (1 KB) json.hpp (782 KB) json.hpp.asc (1 KB) Release date: 2019-07-28 SHA-256: a503214947952b69f0062f572cb74c17582a495767446347ce2e452963fc2ca4 (json.hpp), 541c34438fd54182e9cdc68dd20c898d766713ad6d901fb2c6e28ff1f1e7c10d (include.zip)","title":"v3.7.0"},{"location":"home/releases/#summary_3","text":"This release introduces a few convenience functions and performs a lot of house keeping (bug fixes and small improvements). All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_3","text":"Fix an issue where typedefs with certain names yielded a compilation error. #1642 #1643 Fix a conversion to std::string_view in the unit tests. #1634 #1639 Fix MSVC Debug build. #1536 #1570 #1608 Fix get_to method to clear existing content before writing. #1511 #1555 Fix a -Wc++17-extensions warning. nodiscard attributes are now only used with Clang when -std=c++17 is used. #1535 #1551","title":"Bug Fixes"},{"location":"home/releases/#improvements_1","text":"Switch from Catch to doctest for the unit tests which speeds up compilation and runtime of the 112,112,308 tests. Add an explicit section to the README about the frequently addressed topics character encoding , comments in JSON , and the order of object keys .","title":"Improvements"},{"location":"home/releases/#further-changes_2","text":"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.","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_3","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v361","text":"Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: d2eeb25d2e95bffeb08ebb7704cdffd2e8fca7113eba9a0b38d60a5c391ea09a (json.hpp), 69cc88207ce91347ea530b227ff0776db82dcb8de6704e1a3d74f4841bc651cf (include.zip)","title":"v3.6.1"},{"location":"home/releases/#summary_4","text":"This release fixes a regression and a bug introduced by the earlier 3.6.0 release. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_4","text":"Fixed regression of #590 which could lead to compilation errors with GCC 7 and GCC 8. #1530 Fixed a compilation error when was included. #1531","title":"Bug Fixes"},{"location":"home/releases/#further-changes_3","text":"Fixed a warning for missing field initializers. #1527","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_4","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v360","text":"Files include.zip (136 KB) include.zip.asc (1 KB) json.hpp (711 KB) json.hpp.asc (1 KB) Release date: 2019-03-20 SHA-256: ce9839370f28094c71107c405affb3b08c4a098154988014cbb0800b1c44a831 (json.hpp), 237c5e66e7f8186a02804ce9dbd5f69ce89fe7424ef84adf6142e973bd9532f4 (include.zip) \u2139\ufe0f This release introduced a regression. Please update to version 3.6.1 !","title":"v3.6.0"},{"location":"home/releases/#summary_5","text":"This release adds some convenience functions for JSON Pointers , introduces a contains function to check if a key is present in an object, and improves the performance of integer serialization . Furthermore, a lot of small bug fixes and improvements have been made. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_1","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_5","text":"Fixed a compilation issues with libc 2.12. #1483 #1514 Fixed endian conversion on PPC64. #1489 Fixed library to compile with GCC 9. #1472 #1492 Fixed a compilation issue with GCC 7 on CentOS. #1496 Fixed an integer overflow. #1447 Fixed buffer flushing in serializer. #1445 #1446","title":"Bug Fixes"},{"location":"home/releases/#improvements_2","text":"The performance of dumping integers has been greatly improved. #1411 Added CMake parameter JSON_Install to control whether the library should be installed (default: on). #1330 Fixed a lot of compiler and linter warnings. #1400 #1435 #1502 Reduced required CMake version from 3.8 to 3.1. #1409 #1428 #1441 #1498 Added nodiscard attribute to meta() , array() , object() , from_cbor , from_msgpack , from_ubjson , from_bson , and parse . #1433","title":"Improvements"},{"location":"home/releases/#further-changes_4","text":"Added missing headers. #1500 Fixed typos and broken links in README. #1417 #1423 #1425 #1451 #1455 #1491 Fixed documentation of parse function. #1473 Suppressed warning that cannot be fixed inside the library. #1401 #1468 Imroved package manager suppert: Updated Buckaroo instructions. #1495 Improved Meson support. #1463 Added Conda package manager documentation. #1430 Added NuGet package manager documentation. #1132 Continuous Integration Removed unstable or deprecated Travis builders (Xcode 6.4 - 8.2) and added Xcode 10.1 builder. Added Clang 7 to Travis CI. Fixed AppVeyor x64 builds. #1374 #1414 Updated thirdparty libraries: Catch 1.12.0 -> 1.12.2 Google Benchmark 1.3.0 -> 1.4.1 Doxygen 1.8.15 -> 1.8.16","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_5","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v350","text":"Files include.zip (133 KB) include.zip.asc (1 KB) json.hpp (693 KB) json.hpp.asc (1 KB) Release date: 2018-12-22 SHA-256: 8a6dbf3bf01156f438d0ca7e78c2971bca50eec4ca6f0cf59adf3464c43bb9d5 (json.hpp), 3564da9c5b0cf2e032f97c69baedf10ddbc98030c337d0327a215ea72259ea21 (include.zip)","title":"v3.5.0"},{"location":"home/releases/#summary_6","text":"This release introduces the support for structured bindings and reading from FILE* . Besides, a few bugs have been fixed. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_2","text":"Structured bindings are now supported for JSON objects and arrays via the items() member function, so finally this code is possible: for ( auto & [ key , val ] : j . items ()) { std :: cout << key << ':' << val << '\\n' ; } #1388 #1391 Added support for reading from FILE* to support situations in which streams are nit available or would require too much RAM. #1370 #1392","title":"New Features"},{"location":"home/releases/#bug-fixes_6","text":"The eofbit was not set for input streams when the end of a stream was reached while parsing. #1340 #1343 Fixed a bug in the SAX parser for BSON arrays.","title":"Bug Fixes"},{"location":"home/releases/#improvements_3","text":"Added support for Clang 5.0.1 (PS4 version). #1341 #1342","title":"Improvements"},{"location":"home/releases/#further-changes_5","text":"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 Added code to allow installation via Meson. #1345","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_6","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v340","text":"Files include.zip (132 KB) include.zip.asc (1 KB) json.hpp (689 KB) json.hpp.asc (1 KB) Release date: 2018-10-30 SHA-256: 63da6d1f22b2a7bb9e4ff7d6b255cf691a161ff49532dcc45d398a53e295835f (json.hpp), bfec46fc0cee01c509cf064d2254517e7fa80d1e7647fea37cf81d97c5682bdc (include.zip)","title":"v3.4.0"},{"location":"home/releases/#summary_7","text":"This release introduces three new features: 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.","title":"Summary"},{"location":"home/releases/#new-features_3","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_7","text":"fixed truncation #1286 #1315 fixed an issue with std::pair #1299 #1301 fixed an issue with std::variant #1292 #1294 fixed a bug in the JSON Pointer parser","title":"Bug Fixes"},{"location":"home/releases/#improvements_4","text":"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: '' 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: '' . #1280 #1288 #1303","title":"Improvements"},{"location":"home/releases/#further-changes_6","text":"improved Meson documentation #1305 fixed some more linter warnings #1280 fixed Clang detection for third-party Google Benchmark library #1277","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_7","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v330","text":"Files include.zip (123 KB) include.zip.asc (1 KB) json.hpp (635 KB) json.hpp.asc (1 KB) Release date: 2018-10-05 SHA-256: f1327bb60c58757a3dd2b0c9c45d49503d571337681d950ec621f8374bcc14d4 (json.hpp), 9588d63557333aaa485e92221ec38014a85a6134e7486fe3441e0541a5a89576 (include.zip)","title":"v3.3.0"},{"location":"home/releases/#summary_8","text":"This release adds support for GCC 4.8 . Furthermore, it adds a function get_to to write a JSON value to a passed reference. Another topic of this release was the CMake support which has been overworked and documented. Besides, a lot of bugs have been fixed and slight improvements have been made. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_4","text":"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","title":"New Features"},{"location":"home/releases/#bug-fixes_8","text":"Fixed a bug in the CMake file that made target_link_libraries to not properly include nlohmann_json . #1243 #1245 #1260 Fixed a warning in MSVC 2017 complaining about a constexpr if. #1204 #1268 #1272 Fixed a bug that prevented compilation with ICPC. #755 #1222 Improved the SFINAE correctness to fix a bug in the conversion operator. #1237 #1238 Fixed a -Wctor-dtor-privacy warning. #1224 Fixed a warning on a lambda in unevaluated context. #1225 #1230 Fixed a bug introduced in version 3.2.0 where defining JSON_CATCH_USER led to duplicate macro definition of JSON_INTERNAL_CATCH . #1213 #1214 Fixed a bug that prevented compilation with Clang 3.4.2 in RHEL 7. #1179 #1249","title":"Bug Fixes"},{"location":"home/releases/#improvements_5","text":"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","title":"Improvements"},{"location":"home/releases/#further-changes_7","text":"GCC 4.8 and Xcode 10 were added to the continuous integration suite at Travis. Added lgtm checks to pull requests. Added tests for CMake integration. #1260","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_8","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v320","text":"Files include.zip (124 KB) include.zip.asc (1 KB) json.hpp (636 KB) json.hpp.asc (1 KB) Release date: 2018-08-20 SHA-256: ce6b5610a051ec6795fa11c33854abebb086f0fd67c311f5921c3c07f9531b44 (json.hpp), 35ee642558b90e2f9bc758995c4788c4b4d4dec54eef95fb8f38cb4d49c8fc7c (include.zip)","title":"v3.2.0"},{"location":"home/releases/#summary_9","text":"This release introduces a SAX interface to the library. While this may be a very special feature used by only few people, it allowed to unify all functions that consumed input and created some kind of JSON value. Internally, now all existing functions like parse , accept , from_cbor , from_msgpack , and from_ubjson use the SAX interface with different event processors. This allowed to separate the input processing from the value generation. Furthermore, throwing an exception in case of a parse error is now optional and up to the event processor. Finally, the JSON parser is now non-recursive (meaning it does not use the call stack, but std::vector 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.","title":"Summary"},{"location":"home/releases/#new-features_5","text":"added a parser with a SAX interface (#971, #1153) 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)","title":"New Features"},{"location":"home/releases/#bug-fixes_9","text":"allow to create nullptr_t from JSON allowing to properly roundtrip null values (#1169) allow compare user-defined string types (#1130) better support for algorithms using iterators from items() (#1045, #1134) added parameter to avoid compilation error with MSVC 2015 debug builds (#1114) re-added accidentally skipped unit tests (#1176) fixed MSVC issue with std::swap (#1168)","title":"Bug Fixes"},{"location":"home/releases/#improvements_6","text":"key() function for iterators returns a const reference rather than a string copy (#1098) binary formats CBOR, MessagePack, and UBJSON now supports float as type for floating-point numbers (#1021)","title":"Improvements"},{"location":"home/releases/#further-changes_8","text":"changed issue templates 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 updated to Catch 1.12.0","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_9","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v312","text":"Files include.zip (115 KB) include.zip.asc (1 KB) json.hpp (582 KB) json.hpp.asc (1 KB) Release date: 2018-03-14 SHA-256: fbdfec4b4cf63b3b565d09f87e6c3c183bdd45c5be1864d3fcb338f6f02c1733 (json.hpp), 495362ee1b9d03d9526ba9ccf1b4a9c37691abe3a642ddbced13e5778c16660c (include.zip)","title":"v3.1.2"},{"location":"home/releases/#summary_10","text":"This release fixes several bugs in the library. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_10","text":"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).","title":"Bug Fixes"},{"location":"home/releases/#improvements_7","text":"The parser and the serialization now support user-defined string types (#1006, #1009).","title":"Improvements"},{"location":"home/releases/#further-changes_9","text":"Clang Analyzer is now used as additional static analyzer; see make clang_analyze . Overworked README by adding links to the documentation (#981).","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_10","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v311","text":"Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-13 SHA-256: e14ce5e33d6a2daf748026bd4947f3d9686ca4cfd53d10c3da46a0a9aceb7f2e (json.hpp), fde771d4b9e4f222965c00758a2bdd627d04fb7b59e09b7f3d1965abdc848505 (include.zip)","title":"v3.1.1"},{"location":"home/releases/#summary_11","text":"This release fixes several bugs in the library. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#bug-fixes_11","text":"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() .","title":"Bug Fixes"},{"location":"home/releases/#further-changes_10","text":"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 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).","title":"Further Changes"},{"location":"home/releases/#deprecated-functions_11","text":"This release does not deprecate any functions. As an overview, the following functions have been deprecated in earlier versions and will be removed in the next major version (i.e., 4.0.0): 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.","title":"Deprecated functions"},{"location":"home/releases/#v310","text":"Files include.zip (114 KB) include.zip.asc (1 KB) json.hpp (577 KB) json.hpp.asc (1 KB) Release date: 2018-02-01 SHA-256: d40f614d10a6e4e4e80dca9463da905285f20e93116c36d97d4dc1aa63d10ba4 (json.hpp), 2b7234fca394d1e27b7e017117ed80b7518fafbb4f4c13a7c069624f6f924673 (include.zip)","title":"v3.1.0"},{"location":"home/releases/#summary_12","text":"This release adds support for the UBJSON format and JSON Merge Patch . It also contains some minor changes and bug fixes. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#new-features_6","text":"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.","title":"New features"},{"location":"home/releases/#improvements_8","text":"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.","title":"Improvements"},{"location":"home/releases/#reorganization","text":"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).","title":"Reorganization"},{"location":"home/releases/#further-changes_11","text":"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.","title":"Further changes"},{"location":"home/releases/#deprecated-functions_12","text":"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): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.","title":"Deprecated functions"},{"location":"home/releases/#v301","text":"Files json.hpp (502 KB) json.hpp.asc (1 KB) Release date: 2017-12-29 SHA-256: c9b3591f1bb94e723a0cd7be861733a3a555b234ef132be1e9027a0364118c4c","title":"v3.0.1"},{"location":"home/releases/#summary_13","text":"This release fixes small issues in the implementation of JSON Pointer and JSON Patch . All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#changes","text":"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) Fixed some compiler warnings (see #858, #882).","title":"Changes"},{"location":"home/releases/#deprecated-functions_13","text":"To unify the interfaces and to improve similarity with the STL, the following functions are deprecated since version 3.0.0 and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.","title":"Deprecated functions"},{"location":"home/releases/#v300","text":"Files json.hpp (501 KB) json.hpp.asc (1 KB) Release date: 2017-12-17 SHA-256: 076d4a0cb890a3c3d389c68421a11c3d77c64bd788e85d50f1b77ed252f2a462","title":"v3.0.0"},{"location":"home/releases/#summary_14","text":"After almost a year, here is finally a new release of JSON for Modern C++, and it is a major one! As we adhere to semantic versioning , this means the release includes some breaking changes, so please read the next section carefully before you update. But don't worry, we also added a few new features and put a lot of effort into fixing a lot of bugs and straighten out a few inconsistencies.","title":"Summary"},{"location":"home/releases/#breaking-changes","text":"This section describes changes that change the public API of the library and may require changes in code using a previous version of the library. In section \"Moving from 2.x.x to 3.0.0\" at the end of the release notes, we describe in detail how existing code needs to be changed. The library now uses user-defined exceptions instead of re-using those defined in (#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 , , and 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).","title":"Breaking changes"},{"location":"home/releases/#deprecated-functions_14","text":"To unify the interfaces and to improve similarity with the STL, the following functions are now deprecated and will be removed in the next major version (i.e., 4.0.0): friend std::istream& operator<<(basic_json&, std::istream&) friend std::ostream& operator>>(const basic_json&, std::ostream&) Please use friend std::istream& operator>>(std::istream&, basic_json&) and friend operator<<(std::ostream&, const basic_json&) instead.","title":"Deprecated functions"},{"location":"home/releases/#new-features_7","text":"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 (#494). Fixed support for std::valarray (#702), std::array (#553), and std::map (#600, #607).","title":"New features"},{"location":"home/releases/#further-changes_12","text":"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.","title":"Further changes"},{"location":"home/releases/#moving-from-2xx-to-300","text":"","title":"Moving from 2.x.x to 3.0.0"},{"location":"home/releases/#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: new exception previous exception parse_error.101 invalid_argument parse_error.102 invalid_argument parse_error.103 invalid_argument parse_error.104 invalid_argument parse_error.105 invalid_argument parse_error.106 domain_error parse_error.107 domain_error parse_error.108 domain_error parse_error.109 invalid_argument parse_error.110 out_of_range parse_error.111 invalid_argument parse_error.112 invalid_argument invalid_iterator.201 domain_error invalid_iterator.202 domain_error invalid_iterator.203 domain_error invalid_iterator.204 out_of_range invalid_iterator.205 out_of_range invalid_iterator.206 domain_error invalid_iterator.207 domain_error invalid_iterator.208 domain_error invalid_iterator.209 domain_error invalid_iterator.210 domain_error invalid_iterator.211 domain_error invalid_iterator.212 domain_error invalid_iterator.213 domain_error invalid_iterator.214 out_of_range type_error.301 domain_error type_error.302 domain_error type_error.303 domain_error type_error.304 domain_error type_error.305 domain_error type_error.306 domain_error type_error.307 domain_error type_error.308 domain_error type_error.309 domain_error type_error.310 domain_error type_error.311 domain_error type_error.313 domain_error type_error.314 domain_error type_error.315 domain_error out_of_range.401 out_of_range out_of_range.402 out_of_range out_of_range.403 out_of_range out_of_range.404 out_of_range out_of_range.405 domain_error other_error.501 domain_error","title":"User-defined Exceptions"},{"location":"home/releases/#handling-of-nan-and-inf","text":"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 .","title":"Handling of NaN and INF"},{"location":"home/releases/#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 ); New code: json j = json :: parse ( ss , cb ); If no callback function is used, also the following code works: json j ; j << ss ; or json j ; ss >> j ;","title":"Removal of deprecated functions"},{"location":"home/releases/#v211","text":"Files json.hpp (437 KB) json.hpp.asc (1 KB) Release date: 2017-02-25 SHA-256: faa2321beb1aa7416d035e7417fcfa59692ac3d8c202728f9bcc302e2d558f57","title":"v2.1.1"},{"location":"home/releases/#summary_15","text":"This release fixes a locale-related bug in the parser . To do so, the whole number handling (lexer, parser, and also the serialization) have been overworked. Furthermore, a lot of small changes added up that were added to this release. All changes are backward-compatible.","title":"Summary"},{"location":"home/releases/#changes_1","text":"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 . Removed Doozer. Added Codacity. Upgraded Catch to version 1.7.2.","title":"Changes"},{"location":"home/releases/#v210","text":"Files json.hpp (426 KB) json.hpp.asc (1 KB) Release date: 2017-01-28 SHA-256: a571dee92515b685784fd527e38405cf3f5e13e96edbfe3f03d6df2e363a767b","title":"v2.1.0"},{"location":"home/releases/#summary_16","text":"This release introduces a means to convert from/to user-defined types. The release is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_2","text":"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. Updated to Catch v1.6.0 . Some typos in the documentation have been fixed.","title":"Changes"},{"location":"home/releases/#v2010","text":"Files json.hpp (409 KB) json.hpp.asc (1 KB) Release date: 2017-01-02 SHA-256: ec27d4e74e9ce0f78066389a70724afd07f10761009322dc020656704ad5296d","title":"v2.0.10"},{"location":"home/releases/#summary_17","text":"This release fixes several security-relevant bugs in the MessagePack and CBOR parsers. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_3","text":"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.","title":"Changes"},{"location":"home/releases/#v209","text":"Files json.hpp (406 KB) json.hpp.asc (1 KB) Release date: 2016-12-16 SHA-256: fbf3396f13e187d6c214c297bddc742d918ea9b55e10bfb3d9f458b9bfdc22e5","title":"v2.0.9"},{"location":"home/releases/#summary_18","text":"This release implements with CBOR and MessagePack two binary serialization/deserialization formats . It further contains some small fixes and improvements. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_4","text":"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 test suite now contains 11201886 tests","title":"Changes"},{"location":"home/releases/#v208","text":"Files json.hpp (360 KB) json.hpp.asc (1 KB) Release date: 2016-12-02 SHA-256: b70db0ad34f8e0e61dc3f0cbab88099336c9674c193d8a3439d93d6aca2d7120","title":"v2.0.8"},{"location":"home/releases/#summary_19","text":"This release combines a lot of small fixes and improvements. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_5","text":"fixed a bug that froze the parser if a passed file was not found (now, std::invalid_argument is thrown) fixed a bug that lead to an error of a file at EOF was parsed again (now, std::invalid_argument is thrown) the well known functions emplace and emplace_back have been added to JSON values and work as expected improved the performance of the serialization ( dump function) improved the performance of the deserialization (parser) some continuous integration images at Travis were added and retired; see here for the current continuous integration setup the Coverity scan works again the benchmarking code has been improved to produce more stable results the README file has been extended and includes more frequently asked examples the test suite now contains 8905518 tests updated Catch to version 1.5.8","title":"Changes"},{"location":"home/releases/#v207","text":"Files json.hpp (355 KB) json.hpp.asc (1 KB) Release date: 2016-11-02 SHA-256: 5545c323670f8165bae90b9dc6078825e86ec310d96cc4e5b47233ea43715bbf","title":"v2.0.7"},{"location":"home/releases/#summary_20","text":"This release fixes a few bugs in the JSON parser found in the Parsing JSON is a Minefield \ud83d\udca3 article. The fixes are backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_6","text":"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.","title":"Changes"},{"location":"home/releases/#v206","text":"Files json.hpp (349 KB) json.hpp.asc (1 KB) Release date: 2016-10-15 SHA256: 459cc93d5e2f503e50c6d5876eb86bfea7daf405f5a567c5a2c9abc2383756ae","title":"v2.0.6"},{"location":"home/releases/#summary_21","text":"This release fixes the semantics of operator[] for JSON Pointers (see below). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_7","text":"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 restored test coverage to 100%.","title":"Changes"},{"location":"home/releases/#v205","text":"Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-14 SHA-256: 8b7565263a44e2b7d3b89808bc73d2d639037ff0c1f379e3d56dbd77e00b98d9","title":"v2.0.5"},{"location":"home/releases/#summary_22","text":"This release fixes a regression bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_8","text":"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.","title":"Changes"},{"location":"home/releases/#v204","text":"Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-09-11 SHA-256: 632ceec4c25c4e2153f71470d3a2b992c8355f6d8b4d627d05dd16095cd3aeda","title":"v2.0.4"},{"location":"home/releases/#summary_23","text":"This release fixes a bug in the stream parser (function parse() and the << / >> operators). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_9","text":"Bug fix : The end of a file stream was not detected properly which led to parse errors. Fixed a compiler warning about an unused variable.","title":"Changes"},{"location":"home/releases/#v203","text":"Files json.hpp (347 KB) json.hpp.asc (1 KB) Release date: 2016-08-31 SHA-256: 535b73efe5546fde9e763c14aeadfc7b58183c0b3cd43c29741025aba6cf6bd3","title":"v2.0.3"},{"location":"home/releases/#summary_24","text":"This release combines a lot of small fixes and improvements. The release is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_10","text":"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.","title":"Changes"},{"location":"home/releases/#v202","text":"Files json.hpp (338 KB) json.hpp.asc (1 KB) Release date: 2016-07-31 SHA-256: 8e97b7965b4594b00998d6704465412360e1a0ed927badb51ded8b82291a8f3d","title":"v2.0.2"},{"location":"home/releases/#summary_25","text":"This release combines a lot of small fixes and improvements. The release is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_11","text":"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. Avoided output to std::cout in the test cases.","title":"Changes"},{"location":"home/releases/#v201","text":"Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-28 SHA-256: ef550fcd7df572555bf068e9ec4e9d3b9e4cdd441cecb0dcea9ea7fd313f72dd","title":"v2.0.1"},{"location":"home/releases/#summary_26","text":"This release fixes a performance regression in the JSON serialization (function dump() ). This fix is backwards compatible.","title":"Summary"},{"location":"home/releases/#changes_12","text":"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.","title":"Changes"},{"location":"home/releases/#v200","text":"Files json.hpp (321 KB) json.hpp.asc (1 KB) Release date: 2016-06-24 SHA-256: ac9e1fb25c2ac9ca5fc501fcd2fe3281fe04f07018a1b48820e7b1b11491bb6c","title":"v2.0.0"},{"location":"home/releases/#summary_27","text":"This release adds several features such as JSON Pointers, JSON Patch, or support for 64 bit unsigned integers. Furthermore, several (subtle) bugs have been fixed. As noexcept and constexpr specifier have been added to several functions, the public API has effectively been changed in a (potential) non-backwards compatible manner. As we adhere to Semantic Versioning , this calls for a new major version, so say hello to 2\ufe0f\u20e3.0\ufe0f\u20e3.0\ufe0f\u20e3.","title":"Summary"},{"location":"home/releases/#changes_13","text":"\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 ). Added noexcept specifier to basic_json(boolean_t) , basic_json(const number_integer_t) , basic_json(const int) , basic_json(const number_float_t) , iterator functions ( begin() , end() , etc.) When parsing numbers, the sign of 0.0 (vs. -0.0 ) is preserved. Improved MSVC 2015, Android, and MinGW support. See README for more information. Improved test coverage (added 2,225,386 tests). Removed some misuses of std::move . Fixed several compiler warnings. Improved error messages from JSON parser. Updated to re2c to version 0.16 to use a minimal DFAs for the lexer. Updated test suite to use Catch version 1.5.6. Made type getters ( is_number , etc.) and const value access constexpr . Functions push_back and operator+= now work with key/value pairs passed as initializer list, e.g. j_object += {\"key\", 1} . Overworked CMakeLists.txt to make it easier to integrate the library into other projects.","title":"Changes"},{"location":"home/releases/#notes","text":"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.","title":"Notes"},{"location":"home/releases/#v110","text":"Files json.hpp (257 KB) json.hpp.asc (1 KB) Release date: 2016-01-24 SHA-256: c0cf0e3017798ca6bb18e757ebc570d21a3bdac877845e2b9e9573d183ed2f05","title":"v1.1.0"},{"location":"home/releases/#summary_28","text":"This release fixes several small bugs and adds functionality in a backwards-compatible manner. Compared to the last version (1.0.0) , the following changes have been made:","title":"Summary"},{"location":"home/releases/#changes_14","text":"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]","title":"Changes"},{"location":"home/releases/#notes_1","text":"There are still known open issues (#178, #187) which will be fixed in version 2.0.0. However, these fixes will require a small API change and will not be entirely backwards-compatible.","title":"Notes"},{"location":"home/releases/#v100","text":"Files json.hpp (243 KB) json.hpp.asc (1 KB) Release date: 2015-12-28 SHA-256: 767dc2fab1819d7b9e19b6e456d61e38d21ef7182606ecf01516e3f5230446de","title":"v1.0.0"},{"location":"home/releases/#summary_29","text":"This is the first official release. Compared to the prerelease version 1.0.0-rc1 , only a few minor improvements have been made:","title":"Summary"},{"location":"home/releases/#changes_15","text":"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.","title":"Changes"},{"location":"home/sponsors/","text":"Sponsors \u00b6 You can sponsor this library at GitHub Sponsors . Named Sponsors \u00b6 Michael Hartmann Stefan Hagen Steve Sperandeo Robert Jefe Lindst\u00e4dt Steve Wagner Thanks everyone!","title":"Sponsors"},{"location":"home/sponsors/#sponsors","text":"You can sponsor this library at GitHub Sponsors .","title":"Sponsors"},{"location":"home/sponsors/#named-sponsors","text":"Michael Hartmann Stefan Hagen Steve Sperandeo Robert Jefe Lindst\u00e4dt Steve Wagner Thanks everyone!","title":"Named Sponsors"},{"location":"integration/","text":"Header only \u00b6 json.hpp is the single required file in single_include/nlohmann or released here . You need to add #include // for convenience using json = nlohmann :: json ; to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang). You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.","title":"Header only"},{"location":"integration/#header-only","text":"json.hpp is the single required file in single_include/nlohmann or released here . You need to add #include // for convenience using json = nlohmann :: json ; to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., -std=c++11 for GCC and Clang). You can further use file single_include/nlohmann/json_fwd.hpp for forward declarations.","title":"Header only"},{"location":"integration/cmake/","text":"CMake \u00b6 Integration \u00b6 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. External \u00b6 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 ) project ( ExampleProject LANGUAGES CXX ) find_package ( nlohmann_json 3.11.2 REQUIRED ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) The package configuration file, nlohmann_jsonConfig.cmake , can be used either from an install tree or directly out of the build tree. Embedded \u00b6 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 ) project ( ExampleProject LANGUAGES CXX ) # If you only include this third party in PRIVATE source files, you do not need to install it # when your main project gets installed. set ( JSON_Install OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) 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. Supporting Both \u00b6 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 ) option ( EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF ) add_subdirectory ( thirdparty ) add_executable ( example example.cpp ) # Note that the namespaced target will always be available regardless of the import method target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) thirdparty/CMakeLists.txt if ( EXAMPLE_USE_EXTERNAL_JSON ) find_package ( nlohmann_json 3.11.2 REQUIRED ) else () set ( JSON_BuildTests OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) endif () thirdparty/nlohmann_json is then a complete copy of this source tree. FetchContent \u00b6 Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type. Example CMakeLists.txt cmake_minimum_required ( VERSION 3.11 ) project ( ExampleProject LANGUAGES CXX ) include ( FetchContent ) FetchContent_Declare ( json URL https://github.com/nlohmann/json/releases/download/v3.11.2/json.tar.xz ) FetchContent_MakeAvailable ( json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) Note It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like FetchContent_Declare ( json GIT_REPOSITORY https://github.com/nlohmann/json GIT_TAG v3.11.2 ) However, the repository https://github.com/nlohmann/json download size is quite large. You might want to depend on a smaller repository. For instance, you might want to replace the URL in the example by https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent . CMake Options \u00b6 JSON_BuildTests \u00b6 Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option. JSON_CI \u00b6 Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default. JSON_Diagnostics \u00b6 Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS . This option is OFF by default. JSON_DisableEnumSerialization \u00b6 Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION . This option is OFF by default. JSON_FastTests \u00b6 Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests . JSON_GlobalUDLs \u00b6 Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS . This option is OFF by default. JSON_ImplicitConversions \u00b6 Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS . This option is ON by default. JSON_Install \u00b6 Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project. JSON_MultipleHeaders \u00b6 Use non-amalgamated version of the library. This option is OFF by default. JSON_SystemInclude \u00b6 Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default. JSON_Valgrind \u00b6 Execute test suite with Valgrind . This option is OFF by default. Depends on JSON_BuildTests .","title":"CMake"},{"location":"integration/cmake/#cmake","text":"","title":"CMake"},{"location":"integration/cmake/#integration","text":"You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags.","title":"Integration"},{"location":"integration/cmake/#external","text":"To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration: Example CMakeLists.txt cmake_minimum_required ( VERSION 3.1 ) project ( ExampleProject LANGUAGES CXX ) find_package ( nlohmann_json 3.11.2 REQUIRED ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) The package configuration file, nlohmann_jsonConfig.cmake , can be used either from an install tree or directly out of the build tree.","title":"External"},{"location":"integration/cmake/#embedded","text":"To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file. Example CMakeLists.txt cmake_minimum_required ( VERSION 3.1 ) project ( ExampleProject LANGUAGES CXX ) # If you only include this third party in PRIVATE source files, you do not need to install it # when your main project gets installed. set ( JSON_Install OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) 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.","title":"Embedded"},{"location":"integration/cmake/#supporting-both","text":"To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following. Example CMakeLists.txt project ( ExampleProject LANGUAGES CXX ) option ( EXAMPLE_USE_EXTERNAL_JSON \"Use an external JSON library\" OFF ) add_subdirectory ( thirdparty ) add_executable ( example example.cpp ) # Note that the namespaced target will always be available regardless of the import method target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) thirdparty/CMakeLists.txt if ( EXAMPLE_USE_EXTERNAL_JSON ) find_package ( nlohmann_json 3.11.2 REQUIRED ) else () set ( JSON_BuildTests OFF CACHE INTERNAL \"\" ) add_subdirectory ( nlohmann_json ) endif () thirdparty/nlohmann_json is then a complete copy of this source tree.","title":"Supporting Both"},{"location":"integration/cmake/#fetchcontent","text":"Since CMake v3.11, FetchContent can be used to automatically download a release as a dependency at configure type. Example CMakeLists.txt cmake_minimum_required ( VERSION 3.11 ) project ( ExampleProject LANGUAGES CXX ) include ( FetchContent ) FetchContent_Declare ( json URL https://github.com/nlohmann/json/releases/download/v3.11.2/json.tar.xz ) FetchContent_MakeAvailable ( json ) add_executable ( example example.cpp ) target_link_libraries ( example PRIVATE nlohmann_json::nlohmann_json ) Note It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like FetchContent_Declare ( json GIT_REPOSITORY https://github.com/nlohmann/json GIT_TAG v3.11.2 ) However, the repository https://github.com/nlohmann/json download size is quite large. You might want to depend on a smaller repository. For instance, you might want to replace the URL in the example by https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent .","title":"FetchContent"},{"location":"integration/cmake/#cmake-options","text":"","title":"CMake Options"},{"location":"integration/cmake/#json_buildtests","text":"Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option.","title":"JSON_BuildTests"},{"location":"integration/cmake/#json_ci","text":"Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.","title":"JSON_CI"},{"location":"integration/cmake/#json_diagnostics","text":"Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS . This option is OFF by default.","title":"JSON_Diagnostics"},{"location":"integration/cmake/#json_disableenumserialization","text":"Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION . This option is OFF by default.","title":"JSON_DisableEnumSerialization"},{"location":"integration/cmake/#json_fasttests","text":"Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests .","title":"JSON_FastTests"},{"location":"integration/cmake/#json_globaludls","text":"Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS . This option is OFF by default.","title":"JSON_GlobalUDLs"},{"location":"integration/cmake/#json_implicitconversions","text":"Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS . This option is ON by default.","title":"JSON_ImplicitConversions"},{"location":"integration/cmake/#json_install","text":"Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project.","title":"JSON_Install"},{"location":"integration/cmake/#json_multipleheaders","text":"Use non-amalgamated version of the library. This option is OFF by default.","title":"JSON_MultipleHeaders"},{"location":"integration/cmake/#json_systeminclude","text":"Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to checks for this library by tools like Clang-Tidy. This option is OFF by default.","title":"JSON_SystemInclude"},{"location":"integration/cmake/#json_valgrind","text":"Execute test suite with Valgrind . This option is OFF by default. Depends on JSON_BuildTests .","title":"JSON_Valgrind"},{"location":"integration/migration_guide/","text":"Migration Guide \u00b6 This page collects some guidelines on how to future-proof your code for future versions of this library. Replace deprecated functions \u00b6 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. Parsing \u00b6 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. Deprecated Future-proof nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); j << ss ; nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); ss >> j ; 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}) . Deprecated Future-proof const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ({ s , s + std :: strlen ( s )}); const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ( s , s + std :: strlen ( s )); JSON Pointers \u00b6 Comparing JSON Pointers with strings via operator== and operator!= is deprecated since 3.11.2. To compare a json_pointer p with a string s , convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!= . Deprecated Future-proof nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == \"/foo/bar/1\" ); nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == nlohmann :: json :: json_pointer ( \"/foo/bar/1\" )); 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. Deprecated Future-proof nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr ; nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr . to_string (); 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. Deprecated Future-proof using my_json = nlohmann :: basic_json < std :: map , std :: vector , my_string_type > ; nlohmann :: json_pointer < my_json > ptr ( \"/foo/bar/1\" ); nlohmann :: json_pointer < my_string_type > ptr ( \"/foo/bar/1\" ); Thereby, nlohmann::my_json::json_pointer is an alias for nlohmann::json_pointer and is always an alias to the json_pointer with the appropriate string type for all specializations of basic_json . Miscellaneous functions \u00b6 The function iterator_wrapper is deprecated since 3.1.0. Please use the member function items instead. Deprecated Future-proof for ( auto & x : nlohmann :: json :: iterator_wrapper ( j )) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } for ( auto & x : j . items ()) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } 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. Deprecated Future-proof j >> std :: cout ; std :: cout << j ; 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 . Deprecated Future-proof #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include #include Replace implicit conversions \u00b6 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 . Deprecated Future-proof Future-proof (alternative) nlohmann :: json j = \"Hello, world!\" ; std :: string s = j ; nlohmann :: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > (); nlohmann :: json j = \"Hello, world!\" ; std :: string s ; j . get_to ( s ); You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get . Import namespace literals for UDLs \u00b6 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. Deprecated Future-proof nlohmann :: json j = \"[1,2,3]\" _json ; using namespace nlohmann :: literals ; nlohmann :: json j = \"[1,2,3]\" _json ; To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed. Do not hard-code the complete library namespace \u00b6 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. Dangerous Future-proof Future-proof (alternative) void to_json ( nlohmann :: json_abi_v3_11_2 :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( nlohmann :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( NLOHMANN_JSON_NAMESPACE :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } Do not use the details namespace \u00b6 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.","title":"Migration Guide"},{"location":"integration/migration_guide/#migration-guide","text":"This page collects some guidelines on how to future-proof your code for future versions of this library.","title":"Migration Guide"},{"location":"integration/migration_guide/#replace-deprecated-functions","text":"The following functions have been deprecated and will be removed in the next major version (i.e., 4.0.0). All deprecations are annotated with HEDLEY_DEPRECATED_FOR to report which function to use instead.","title":"Replace deprecated functions"},{"location":"integration/migration_guide/#parsing","text":"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. Deprecated Future-proof nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); j << ss ; nlohmann :: json j ; std :: stringstream ss ( \"[1,2,3]\" ); ss >> j ; 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}) . Deprecated Future-proof const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ({ s , s + std :: strlen ( s )}); const char * s = \"[1,2,3]\" ; bool ok = nlohmann :: json :: accept ( s , s + std :: strlen ( s ));","title":"Parsing"},{"location":"integration/migration_guide/#json-pointers","text":"Comparing JSON Pointers with strings via operator== and operator!= is deprecated since 3.11.2. To compare a json_pointer p with a string s , convert s to a json_pointer first and use json_pointer::operator== or json_pointer::operator!= . Deprecated Future-proof nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == \"/foo/bar/1\" ); nlohmann :: json :: json_pointer lhs ( \"/foo/bar/1\" ); assert ( lhs == nlohmann :: json :: json_pointer ( \"/foo/bar/1\" )); 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. Deprecated Future-proof nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr ; nlohmann :: json :: json_pointer ptr ( \"/foo/bar/1\" ); std :: string s = ptr . to_string (); 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. Deprecated Future-proof using my_json = nlohmann :: basic_json < std :: map , std :: vector , my_string_type > ; nlohmann :: json_pointer < my_json > ptr ( \"/foo/bar/1\" ); nlohmann :: json_pointer < my_string_type > ptr ( \"/foo/bar/1\" ); Thereby, nlohmann::my_json::json_pointer is an alias for nlohmann::json_pointer and is always an alias to the json_pointer with the appropriate string type for all specializations of basic_json .","title":"JSON Pointers"},{"location":"integration/migration_guide/#miscellaneous-functions","text":"The function iterator_wrapper is deprecated since 3.1.0. Please use the member function items instead. Deprecated Future-proof for ( auto & x : nlohmann :: json :: iterator_wrapper ( j )) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } for ( auto & x : j . items ()) { std :: cout << x . key () << \":\" << x . value () << std :: endl ; } 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. Deprecated Future-proof j >> std :: cout ; std :: cout << j ; 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 . Deprecated Future-proof #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include #include ","title":"Miscellaneous functions"},{"location":"integration/migration_guide/#replace-implicit-conversions","text":"Implicit conversions via operator ValueType will be switched off by default in the next major release of the library. You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get , get_to , get_ref , or get_ptr . Deprecated Future-proof Future-proof (alternative) nlohmann :: json j = \"Hello, world!\" ; std :: string s = j ; nlohmann :: json j = \"Hello, world!\" ; auto s = j . template get < std :: string > (); nlohmann :: json j = \"Hello, world!\" ; std :: string s ; j . get_to ( s ); You can prepare existing code by already defining JSON_USE_IMPLICIT_CONVERSIONS to 0 and replace any implicit conversions with calls to get .","title":"Replace implicit conversions"},{"location":"integration/migration_guide/#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. Deprecated Future-proof nlohmann :: json j = \"[1,2,3]\" _json ; using namespace nlohmann :: literals ; nlohmann :: json j = \"[1,2,3]\" _json ; To prepare existing code, define JSON_USE_GLOBAL_UDLS to 0 and bring the string literals into scope where needed.","title":"Import namespace literals for UDLs"},{"location":"integration/migration_guide/#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. Dangerous Future-proof Future-proof (alternative) void to_json ( nlohmann :: json_abi_v3_11_2 :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( nlohmann :: json & j , const person & p ) { j [ \"age\" ] = p . age ; } void to_json ( NLOHMANN_JSON_NAMESPACE :: json & j , const person & p ) { j [ \"age\" ] = p . age ; }","title":"Do not hard-code the complete library namespace"},{"location":"integration/migration_guide/#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.","title":"Do not use the details namespace"},{"location":"integration/package_managers/","text":"Package Managers \u00b6 Throughout this page, we will describe how to compile the example file example.cpp below. #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } When executed, this program should create output similar to { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } } Homebrew \u00b6 If you are using OS X and Homebrew , just type brew install nlohmann-json and you're set. If you want the bleeding edge rather than the latest release, use brew install nlohmann-json --HEAD instead. See nlohmann-json for more information. Example Create the following file: example.cpp #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } Install the package brew install nlohmann-json Determine the include path, which defaults to /usr/local/Cellar/nlohmann-json/$version/include , where $version is the version of the library, e.g. 3.7.3 . The path of the library can be determined with brew list nlohmann-json Compile the code. For instance, the code can be compiled using Clang with clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std = c++11 -o example The formula is updated automatically. Meson \u00b6 If you are using the Meson Build System , add this source tree as a meson subproject . You may also use the include.zip published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB , or simply use meson wrap install nlohmann_json . Please see the meson project for any issues regarding the packaging. The provided meson.build can also be used as an alternative to cmake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly. Bazel \u00b6 This repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive , git_repository , or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g. via deps attribute). Conan \u00b6 If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile 's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages. Example Create the following files: Conanfile.txt [requires] nlohmann_json/3.7.3 [generators] cmake CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) add_definitions ( \"-std=c++11\" ) include ( ${ CMAKE_BINARY_DIR } /conanbuildinfo.cmake ) conan_basic_setup () add_executable ( json_example example.cpp ) target_link_libraries ( json_example ${ CONAN_LIBS } ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Build: mkdir build cd build conan install .. cmake .. cmake --build . The package is updated automatically. Spack \u00b6 If you are using Spack to manage your dependencies, you can use the nlohmann-json package . Please see the spack project for any issues regarding the packaging. Hunter \u00b6 If you are using hunter on your project for external dependencies, then you can use the nlohmann_json package . Please see the hunter project for any issues regarding the packaging. Buckaroo \u00b6 If you are using Buckaroo , you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json . Please file issues here . There is a demo repo here . vcpkg \u00b6 If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with vcpkg install nlohmann-json and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging. Example Create the following files: CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) find_package ( nlohmann_json CONFIG REQUIRED ) add_executable ( json_example example.cpp ) target_link_libraries ( json_example PRIVATE nlohmann_json::nlohmann_json ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Install package: vcpkg install nlohmann-json Build: mkdir build cd build cmake .. -DCMAKE_TOOLCHAIN_FILE = /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake cmake --build . Note you need to adjust /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake to your system. cget \u00b6 If you are using cget , you can install the latest development version with cget install nlohmann/json . A specific version can be installed with cget install nlohmann/json@v3.1.0 . Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON ). cget reads directly from the GitHub repository and is always up-to-date. CocoaPods \u00b6 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 . NuGet \u00b6 If you are using NuGet , you can use the package nlohmann.json . Please check this extensive description on how to use the package. Please file issues here . Conda \u00b6 If you are using conda , you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json . Please file issues here . MSYS2 \u00b6 If you are using MSYS2 , you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages. The package is updated automatically. MacPorts \u00b6 If you are using MacPorts , execute sudo port install nlohmann-json to install the nlohmann-json package. The package is updated automatically. build2 \u00b6 If you are using build2 , you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository . In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints ). If you are not familiar with using dependencies in build2 , please read this introduction . Please file issues here if you experience problems with the packages. The package is updated automatically. wsjcpp \u00b6 If you are using wsjcpp , you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch. wsjcpp reads directly from the GitHub repository and is always up-to-date. CPM.cmake \u00b6 If you are using CPM.cmake , you can check this example . After adding CPM script to your project, implement the following snippet to your CMake: CPMAddPackage ( NAME nlohmann_json GITHUB_REPOSITORY nlohmann/json VERSION 3.9.1 )","title":"Package Managers"},{"location":"integration/package_managers/#package-managers","text":"Throughout this page, we will describe how to compile the example file example.cpp below. #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } When executed, this program should create output similar to { \"compiler\" : { \"c++\" : \"201103\" , \"family\" : \"gcc\" , \"version\" : \"12.1.0\" }, \"copyright\" : \"(C) 2013-2022 Niels Lohmann\" , \"name\" : \"JSON for Modern C++\" , \"platform\" : \"apple\" , \"url\" : \"https://github.com/nlohmann/json\" , \"version\" : { \"major\" : 3 , \"minor\" : 11 , \"patch\" : 2 , \"string\" : \"3.11.2\" } }","title":"Package Managers"},{"location":"integration/package_managers/#homebrew","text":"If you are using OS X and Homebrew , just type brew install nlohmann-json and you're set. If you want the bleeding edge rather than the latest release, use brew install nlohmann-json --HEAD instead. See nlohmann-json for more information. Example Create the following file: example.cpp #include #include #include using json = nlohmann :: json ; int main () { std :: cout << std :: setw ( 4 ) << json :: meta () << std :: endl ; } Install the package brew install nlohmann-json Determine the include path, which defaults to /usr/local/Cellar/nlohmann-json/$version/include , where $version is the version of the library, e.g. 3.7.3 . The path of the library can be determined with brew list nlohmann-json Compile the code. For instance, the code can be compiled using Clang with clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std = c++11 -o example The formula is updated automatically.","title":"Homebrew"},{"location":"integration/package_managers/#meson","text":"If you are using the Meson Build System , add this source tree as a meson subproject . You may also use the include.zip published in this project's Releases to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from Meson WrapDB , or simply use meson wrap install nlohmann_json . Please see the meson project for any issues regarding the packaging. The provided meson.build can also be used as an alternative to cmake for installing nlohmann_json system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the nlohmann_json pkg-config dependency. In Meson, it is preferred to use the dependency() object with a subproject fallback, rather than using the subproject directly.","title":"Meson"},{"location":"integration/package_managers/#bazel","text":"This repository provides a Bazel WORKSPACE.bazel and a corresponding BUILD.bazel file. Therefore, this repository can be referenced by workspace rules such as http_archive , git_repository , or local_repository from other Bazel workspaces. To use the library you only need to depend on the target @nlohmann_json//:json (e.g. via deps attribute).","title":"Bazel"},{"location":"integration/package_managers/#conan","text":"If you are using Conan to manage your dependencies, merely add nlohmann_json/x.y.z to your conanfile 's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages. Example Create the following files: Conanfile.txt [requires] nlohmann_json/3.7.3 [generators] cmake CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) add_definitions ( \"-std=c++11\" ) include ( ${ CMAKE_BINARY_DIR } /conanbuildinfo.cmake ) conan_basic_setup () add_executable ( json_example example.cpp ) target_link_libraries ( json_example ${ CONAN_LIBS } ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Build: mkdir build cd build conan install .. cmake .. cmake --build . The package is updated automatically.","title":"Conan"},{"location":"integration/package_managers/#spack","text":"If you are using Spack to manage your dependencies, you can use the nlohmann-json package . Please see the spack project for any issues regarding the packaging.","title":"Spack"},{"location":"integration/package_managers/#hunter","text":"If you are using hunter on your project for external dependencies, then you can use the nlohmann_json package . Please see the hunter project for any issues regarding the packaging.","title":"Hunter"},{"location":"integration/package_managers/#buckaroo","text":"If you are using Buckaroo , you can install this library's module with buckaroo add github.com/buckaroo-pm/nlohmann-json . Please file issues here . There is a demo repo here .","title":"Buckaroo"},{"location":"integration/package_managers/#vcpkg","text":"If you are using vcpkg on your project for external dependencies, then you can install the nlohmann-json package with vcpkg install nlohmann-json and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging. Example Create the following files: CMakeLists.txt project ( json_example ) cmake_minimum_required ( VERSION 2.8.12 ) find_package ( nlohmann_json CONFIG REQUIRED ) add_executable ( json_example example.cpp ) target_link_libraries ( json_example PRIVATE nlohmann_json::nlohmann_json ) example.cpp #include #include using json = nlohmann :: json ; int main () { std :: cout << json :: meta () << std :: endl ; } Install package: vcpkg install nlohmann-json Build: mkdir build cd build cmake .. -DCMAKE_TOOLCHAIN_FILE = /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake cmake --build . Note you need to adjust /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake to your system.","title":"vcpkg"},{"location":"integration/package_managers/#cget","text":"If you are using cget , you can install the latest development version with cget install nlohmann/json . A specific version can be installed with cget install nlohmann/json@v3.1.0 . Also, the multiple header version can be installed by adding the -DJSON_MultipleHeaders=ON flag (i.e., cget install nlohmann/json -DJSON_MultipleHeaders=ON ). cget reads directly from the GitHub repository and is always up-to-date.","title":"cget"},{"location":"integration/package_managers/#cocoapods","text":"If you are using CocoaPods , you can use the library by adding pod \"nlohmann_json\", '~>3.1.2' to your podfile (see an example ). Please file issues here .","title":"CocoaPods"},{"location":"integration/package_managers/#nuget","text":"If you are using NuGet , you can use the package nlohmann.json . Please check this extensive description on how to use the package. Please file issues here .","title":"NuGet"},{"location":"integration/package_managers/#conda","text":"If you are using conda , you can use the package nlohmann_json from conda-forge executing conda install -c conda-forge nlohmann_json . Please file issues here .","title":"Conda"},{"location":"integration/package_managers/#msys2","text":"If you are using MSYS2 , you can use the mingw-w64-nlohmann-json package, just type pacman -S mingw-w64-i686-nlohmann-json or pacman -S mingw-w64-x86_64-nlohmann-json for installation. Please file issues here if you experience problems with the packages. The package is updated automatically.","title":"MSYS2"},{"location":"integration/package_managers/#macports","text":"If you are using MacPorts , execute sudo port install nlohmann-json to install the nlohmann-json package. The package is updated automatically.","title":"MacPorts"},{"location":"integration/package_managers/#build2","text":"If you are using build2 , you can use the nlohmann-json package from the public repository http://cppget.org or directly from the package's sources repository . In your project's manifest file, just add depends: nlohmann-json (probably with some version constraints ). If you are not familiar with using dependencies in build2 , please read this introduction . Please file issues here if you experience problems with the packages. The package is updated automatically.","title":"build2"},{"location":"integration/package_managers/#wsjcpp","text":"If you are using wsjcpp , you can use the command wsjcpp install \"https://github.com/nlohmann/json:develop\" to get the latest version. Note you can change the branch \":develop\" to an existing tag or another branch. wsjcpp reads directly from the GitHub repository and is always up-to-date.","title":"wsjcpp"},{"location":"integration/package_managers/#cpmcmake","text":"If you are using CPM.cmake , you can check this example . After adding CPM script to your project, implement the following snippet to your CMake: CPMAddPackage ( NAME nlohmann_json GITHUB_REPOSITORY nlohmann/json VERSION 3.9.1 )","title":"CPM.cmake"},{"location":"integration/pkg-config/","text":"Pkg-config \u00b6 If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed: pkg-config nlohmann_json --cflags Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config : json = dependency ( 'nlohmann_json' , required : true )","title":"Pkg-config"},{"location":"integration/pkg-config/#pkg-config","text":"If you are using bare Makefiles, you can use pkg-config to generate the include flags that point to where the library is installed: pkg-config nlohmann_json --cflags Users of the Meson build system will also be able to use a system-wide library, which will be found by pkg-config : json = dependency ( 'nlohmann_json' , required : true )","title":"Pkg-config"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 8c6262fc6..633174ad2 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,1117 +2,1122 @@ https://json.nlohmann.me/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/operator_gtgt/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/operator_literal_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/operator_literal_json_pointer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/operator_ltlt/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/ordered_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/ordered_map/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/adl_serializer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/adl_serializer/from_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/adl_serializer/to_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/accept/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/array/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/array_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/at/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/back/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/basic_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/begin/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/binary/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/binary_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/boolean_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/cbegin/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/cbor_tag_handler_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/cend/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/clear/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/contains/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/count/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/crbegin/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/crend/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/default_object_comparator_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/diff/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/dump/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/emplace/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/emplace_back/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/empty/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/end/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/erase/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/error_handler_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/exception/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/find/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/flatten/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/from_bjdata/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/from_bson/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/from_cbor/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/from_msgpack/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/from_ubjson/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/front/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/get/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/get_allocator/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/get_binary/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/get_ptr/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/get_ref/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/get_to/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/input_format_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/insert/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/invalid_iterator/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_array/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_binary/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_boolean/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_discarded/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_null/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_number/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_number_float/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_number_integer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_number_unsigned/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_object/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_primitive/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_string/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/is_structured/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/items/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/json_base_class_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/json_serializer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/max_size/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/merge_patch/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/meta/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/number_float_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/number_integer_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/number_unsigned_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/object/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/object_comparator_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/object_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator%2B%3D/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator%3D/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_ValueType/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_eq/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_ge/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_gt/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_le/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_lt/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_ne/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_spaceship/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/operator_value_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/other_error/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/out_of_range/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/parse/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/parse_error/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/parse_event_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/parser_callback_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/patch/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/patch_inplace/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/push_back/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/rbegin/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/rend/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/sax_parse/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/size/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/std_hash/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/std_swap/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/string_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/swap/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/to_bjdata/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/to_bson/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/to_cbor/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/to_msgpack/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/to_string/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/to_ubjson/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/type/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/type_error/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/type_name/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/unflatten/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/update/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/value/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/value_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/basic_json/~basic_json/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/byte_container_with_subtype/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/back/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/empty/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/json_pointer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/operator_eq/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/operator_ne/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/operator_slash/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/operator_string_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/parent_pointer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/pop_back/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/push_back/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/string_t/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_pointer/to_string/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/binary/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/boolean/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/end_array/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/end_object/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/key/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/null/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/number_float/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/number_integer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/number_unsigned/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/parse_error/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/start_array/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/start_object/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/json_sax/string/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_assert/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_diagnostics/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_disable_enum_serialization/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_has_cpp_11/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_has_filesystem/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_has_ranges/ - 2023-09-23 + 2023-09-24 + daily + + + https://json.nlohmann.me/api/macros/json_has_static_rtti/ + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_has_three_way_comparison/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_no_io/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_noexception/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_skip_library_version_check/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_skip_unsupported_compiler_check/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_throw_user/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_use_global_udls/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_use_implicit_conversions/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/json_use_legacy_discarded_value_comparison/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_json_namespace/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_json_namespace_begin/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_json_namespace_no_version/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_json_serialize_enum/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/api/macros/nlohmann_json_version_major/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/arbitrary_types/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/assertions/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_values/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/comments/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/enum_conversion/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/iterators/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/json_patch/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/json_pointer/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/macros/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/merge_patch/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/namespace/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/object_order/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_formats/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_formats/bjdata/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_formats/bson/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_formats/cbor/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_formats/messagepack/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/binary_formats/ubjson/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/element_access/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/element_access/checked_access/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/element_access/default_value/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/element_access/unchecked_access/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/parsing/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/parsing/json_lines/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/parsing/parse_exceptions/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/parsing/parser_callbacks/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/parsing/sax_interface/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/types/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/features/types/number_handling/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/code_of_conduct/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/design_goals/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/exceptions/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/faq/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/license/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/releases/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/home/sponsors/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/integration/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/integration/cmake/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/integration/migration_guide/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/integration/package_managers/ - 2023-09-23 + 2023-09-24 daily https://json.nlohmann.me/integration/pkg-config/ - 2023-09-23 + 2023-09-24 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index aad7f68e9..ee5c4d2d9 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ