From f99a460b9b2d952607eb4342219eccbdb831d995 Mon Sep 17 00:00:00 2001 From: nlohmann Date: Mon, 5 Oct 2026 05:14:25 +0000 Subject: [PATCH] deploy: 6b4b825af2c487991538ca01c40aa6421f12de78 --- api/basic_json/number_float_t.md | 4 + api/basic_json/number_float_t/index.html | 4 +- api/basic_json/number_float_t/index.md | 2 + api/basic_json/number_integer_t.md | 5 +- api/basic_json/number_integer_t/index.html | 4 +- api/basic_json/number_integer_t/index.md | 2 +- api/basic_json/number_unsigned_t.md | 5 +- api/basic_json/number_unsigned_t/index.html | 4 +- api/basic_json/number_unsigned_t/index.md | 2 +- features/binary_formats/cbor.md | 6 +- features/binary_formats/cbor/index.html | 4 +- features/binary_formats/cbor/index.md | 2 +- home/exceptions.md | 12 +- home/exceptions/index.html | 8 +- home/exceptions/index.md | 12 +- search/search_index.json | 2 +- sitemap.xml | 546 ++++++++++---------- sitemap.xml.gz | Bin 2017 -> 2017 bytes 18 files changed, 317 insertions(+), 307 deletions(-) diff --git a/api/basic_json/number_float_t.md b/api/basic_json/number_float_t.md index 8419a392d..282bb6123 100644 --- a/api/basic_json/number_float_t.md +++ b/api/basic_json/number_float_t.md @@ -55,6 +55,10 @@ This implementation does exactly follow this approach, as it uses double precisi smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. +During deserialization (from JSON text or any of the binary formats), a finite number that does not fit into +`number_float_t` is rejected with [`out_of_range.406`](../../home/exceptions.md#jsonexceptionout_of_range406), for +example a double-precision number in a binary format when `number_float_t` is `#!cpp float`. + ### Storage Floating-point number values are stored directly inside a `basic_json` type. diff --git a/api/basic_json/number_float_t/index.html b/api/basic_json/number_float_t/index.html index 8e0f6d8f0..995637008 100644 --- a/api/basic_json/number_float_t/index.html +++ b/api/basic_json/number_float_t/index.html @@ -1,5 +1,5 @@ number_float_t - JSON for Modern C++
Skip to content

nlohmann::basic_json::number_float_t

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.

Template parameters

NumberFloatType
the type to store floating-point numbers. Parsing and serialization are implemented in terms of std::strtof/std::strtod/std::strtold and std::snprintf, so the type must be float, double, or long double. The binary formats additionally require float or double, because they have no encoding for long double. See Template Parameter Requirements.

Notes

Default type

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

Default behavior

  • The restrictions about leading zeros are not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as a 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

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

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

Examples

Example

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

#include <iostream>
+

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.

Template parameters

NumberFloatType
the type to store floating-point numbers. Parsing and serialization are implemented in terms of std::strtof/std::strtod/std::strtold and std::snprintf, so the type must be float, double, or long double. The binary formats additionally require float or double, because they have no encoding for long double. See Template Parameter Requirements.

Notes

Default type

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

Default behavior

  • The restrictions about leading zeros are not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as a 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

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.

During deserialization (from JSON text or any of the binary formats), a finite number that does not fit into number_float_t is rejected with out_of_range.406, for example a double-precision number in a binary format when number_float_t is float.

Storage

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

Examples

Example

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

#include <iostream>
 #include <iomanip>
 #include <nlohmann/json.hpp>
 
@@ -10,4 +10,4 @@
     std::cout << std::boolalpha << std::is_same<double, json::number_float_t>::value << std::endl;
 }
 

Output:

true
-

See also

Version history

  • Added in version 1.0.0.
\ No newline at end of file +

See also

Version history

\ No newline at end of file diff --git a/api/basic_json/number_float_t/index.md b/api/basic_json/number_float_t/index.md index aac4e1c7f..75e2b7ef5 100644 --- a/api/basic_json/number_float_t/index.md +++ b/api/basic_json/number_float_t/index.md @@ -37,6 +37,8 @@ With the default values for `NumberFloatType` (`double`), the default value for 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`. +During deserialization (from JSON text or any of the binary formats), a finite number that does not fit into `number_float_t` is rejected with [`out_of_range.406`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range406), for example a double-precision number in a binary format when `number_float_t` is `float`. + ### Storage Floating-point number values are stored directly inside a `basic_json` type. diff --git a/api/basic_json/number_integer_t.md b/api/basic_json/number_integer_t.md index d77c6a24d..48d2873ed 100644 --- a/api/basic_json/number_integer_t.md +++ b/api/basic_json/number_integer_t.md @@ -47,8 +47,9 @@ With the default values for `NumberIntegerType` (`std::int64_t`), the default va 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 automatically be stored as [`number_unsigned_t`](number_unsigned_t.md) or [`number_float_t`](number_float_t.md). +range will yield over/underflow when used in a constructor. During deserialization (from JSON text or any of the binary +formats), too large or small integer numbers will automatically be stored as [`number_unsigned_t`](number_unsigned_t.md) +or [`number_float_t`](number_float_t.md). [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: > Note that when such software is used, numbers that are integers and are in the range [-253+1, 253-1] are diff --git a/api/basic_json/number_integer_t/index.html b/api/basic_json/number_integer_t/index.html index 8f6189299..52af59cc7 100644 --- a/api/basic_json/number_integer_t/index.html +++ b/api/basic_json/number_integer_t/index.html @@ -1,5 +1,5 @@ number_integer_t - JSON for Modern C++
Skip to content

nlohmann::basic_json::number_integer_t

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.

Template parameters

NumberIntegerType
the type to store signed integers. It must be a signed integral type (std::is_integral) with a std::numeric_limits specialization, and it is stored directly inside a basic_json value. See Template Parameter Requirements.

Notes

Default type

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

Default behavior

  • The restrictions about leading zeros are not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as an octal number. Internally, the value will be stored as a decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.

Limits

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 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 [-253+1, 253-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

Integer number values are stored directly inside a basic_json type.

Examples

Example

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

#include <iostream>
+

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.

Template parameters

NumberIntegerType
the type to store signed integers. It must be a signed integral type (std::is_integral) with a std::numeric_limits specialization, and it is stored directly inside a basic_json value. See Template Parameter Requirements.

Notes

Default type

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

Default behavior

  • The restrictions about leading zeros are not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as an octal number. Internally, the value will be stored as a decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.

Limits

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 (from JSON text or any of the binary formats), too large or small integer numbers will 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 [-253+1, 253-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

Integer number values are stored directly inside a basic_json type.

Examples

Example

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

#include <iostream>
 #include <iomanip>
 #include <nlohmann/json.hpp>
 
@@ -10,4 +10,4 @@
     std::cout << std::boolalpha << std::is_same<std::int64_t, json::number_integer_t>::value << std::endl;
 }
 

Output:

true
-

See also

Version history

  • Added in version 1.0.0.
\ No newline at end of file +

See also

Version history

\ No newline at end of file diff --git a/api/basic_json/number_integer_t/index.md b/api/basic_json/number_integer_t/index.md index fba0f003a..11e528460 100644 --- a/api/basic_json/number_integer_t/index.md +++ b/api/basic_json/number_integer_t/index.md @@ -34,7 +34,7 @@ With the default values for `NumberIntegerType` (`std::int64_t`), the default va > 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 automatically be stored as [`number_unsigned_t`](https://json.nlohmann.me/api/basic_json/number_unsigned_t/index.md) or [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md). +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 (from JSON text or any of the binary formats), too large or small integer numbers will automatically be stored as [`number_unsigned_t`](https://json.nlohmann.me/api/basic_json/number_unsigned_t/index.md) or [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md). [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: diff --git a/api/basic_json/number_unsigned_t.md b/api/basic_json/number_unsigned_t.md index 774fda638..81cc00f77 100644 --- a/api/basic_json/number_unsigned_t.md +++ b/api/basic_json/number_unsigned_t.md @@ -48,8 +48,9 @@ With the default values for `NumberUnsignedType` (`std::uint64_t`), the default 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 automatically be stored -as [`number_integer_t`](number_integer_t.md) or [`number_float_t`](number_float_t.md). +when used in a constructor. During deserialization (from JSON text or any of the binary formats), too large or small +integer numbers will automatically be stored as [`number_integer_t`](number_integer_t.md) or +[`number_float_t`](number_float_t.md). [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: > Note that when such software is used, numbers that are integers and are in the range [-253+1, 253-1] are diff --git a/api/basic_json/number_unsigned_t/index.html b/api/basic_json/number_unsigned_t/index.html index 88f0c1159..aab0b809c 100644 --- a/api/basic_json/number_unsigned_t/index.html +++ b/api/basic_json/number_unsigned_t/index.html @@ -1,5 +1,5 @@ number_unsigned_t - JSON for Modern C++
Skip to content

nlohmann::basic_json::number_unsigned_t

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.

Template parameters

NumberUnsignedType
the type to store unsigned integers. It must be an unsigned integral type (std::is_integral) with a std::numeric_limits specialization, and it must be able to represent the absolute value of every number_integer_t value. See Template Parameter Requirements.

Notes

Default type

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

Default behavior

  • The restrictions about leading zeros are not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as an octal number. Internally, the value will be stored as a decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.

Limits

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 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 [-253+1, 253-1] 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

Integer number values are stored directly inside a basic_json type.

Examples

Example

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

#include <iostream>
+

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.

Template parameters

NumberUnsignedType
the type to store unsigned integers. It must be an unsigned integral type (std::is_integral) with a std::numeric_limits specialization, and it must be able to represent the absolute value of every number_integer_t value. See Template Parameter Requirements.

Notes

Default type

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

Default behavior

  • The restrictions about leading zeros are not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as an octal number. Internally, the value will be stored as a decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.

Limits

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 (from JSON text or any of the binary formats), too large or small integer numbers will 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 [-253+1, 253-1] 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

Integer number values are stored directly inside a basic_json type.

Examples

Example

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

#include <iostream>
 #include <iomanip>
 #include <nlohmann/json.hpp>
 
@@ -10,4 +10,4 @@
     std::cout << std::boolalpha << std::is_same<std::uint64_t, json::number_unsigned_t>::value << std::endl;
 }
 

Output:

true
-

See also

Version history

  • Added in version 2.0.0.
\ No newline at end of file +

See also

Version history

\ No newline at end of file diff --git a/api/basic_json/number_unsigned_t/index.md b/api/basic_json/number_unsigned_t/index.md index 3fd23bfaf..4779126f7 100644 --- a/api/basic_json/number_unsigned_t/index.md +++ b/api/basic_json/number_unsigned_t/index.md @@ -34,7 +34,7 @@ With the default values for `NumberUnsignedType` (`std::uint64_t`), the default > 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 automatically be stored as [`number_integer_t`](https://json.nlohmann.me/api/basic_json/number_integer_t/index.md) or [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md). +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 (from JSON text or any of the binary formats), too large or small integer numbers will automatically be stored as [`number_integer_t`](https://json.nlohmann.me/api/basic_json/number_integer_t/index.md) or [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md). [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: diff --git a/features/binary_formats/cbor.md b/features/binary_formats/cbor.md index 7b5be4631..1b226cd15 100644 --- a/features/binary_formats/cbor.md +++ b/features/binary_formats/cbor.md @@ -168,9 +168,9 @@ The library maps CBOR types to JSON value types as follows: !!! warning "Negative integer overflow" CBOR negative integers (major type 1) are decoded as `-1 - n`. If the encoded magnitude `n` is too large for the - result to fit into `number_integer_t` (`std::int64_t` by default), parsing fails with a - [`parse_error.112`](../../home/exceptions.md#jsonexceptionparse_error112) exception rather than overflowing - silently. + result to fit into `number_integer_t` (`std::int64_t` by default), the result is stored as `number_float_t`, like + a too small integer in JSON text. For example, `-18446744073709551616` (`0x3B` followed by eight `0xFF` bytes) is + stored as `-1.8446744073709552e+19`. !!! warning "Object keys" diff --git a/features/binary_formats/cbor/index.html b/features/binary_formats/cbor/index.html index 7a959a0c9..bad066af9 100644 --- a/features/binary_formats/cbor/index.html +++ b/features/binary_formats/cbor/index.html @@ -21,7 +21,7 @@ std::cout << std::endl; }

Output:

0xa2 0x67 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf5 0x66 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 
-

Deserialization

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:

Tagged items (0xC0..0xDB) are not interpreted either; see the note on tagged items below.

Negative integer overflow

CBOR negative integers (major type 1) are decoded as -1 - n. If the encoded magnitude n is too large for the result to fit into number_integer_t (std::int64_t by default), parsing fails with a parse_error.112 exception rather than overflowing silently.

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 text strings (major type 3) are rejected with a parse_error.113 exception (or, with allow_exceptions set to false, a discarded value) naming the type of the key that was found, for instance:

[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR object key: only string keys are supported, but found an unsigned integer; last byte: 0x01
+

Deserialization

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:

  • simple values (0xE0..0xF3, 0xF8)
  • undefined (0xF7)

Tagged items (0xC0..0xDB) are not interpreted either; see the note on tagged items below.

Negative integer overflow

CBOR negative integers (major type 1) are decoded as -1 - n. If the encoded magnitude n is too large for the result to fit into number_integer_t (std::int64_t by default), the result is stored as number_float_t, like a too small integer in JSON text. For example, -18446744073709551616 (0x3B followed by eight 0xFF bytes) is stored as -1.8446744073709552e+19.

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 text strings (major type 3) are rejected with a parse_error.113 exception (or, with allow_exceptions set to false, a discarded value) naming the type of the key that was found, for instance:

[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR object key: only string keys are supported, but found an unsigned integer; last byte: 0x01
 

This applies to the SAX interface as well, as the key is read before it is passed on. This is a deliberate restriction of the library's JSON value model, not an oversight: formats built on CBOR maps with integer keys, such as COSE (RFC 9052) or CWT (RFC 8392), cannot be read with this library and need a general-purpose CBOR library instead.

Ill-formed UTF-8 in text strings

RFC 8949, Section 3.1 requires CBOR text strings (major type 3) to be valid UTF-8, but leaves it up to the decoder whether to enforce this, so checking is opt-in: with the error_handler parameter left at keep (the default), from_cbor() accepts a text string (object keys included) whose bytes are not valid UTF-8 and hands them back unchanged. Passing error_handler_t::strict makes from_cbor() check and throw parse_error.113 for ill-formed UTF-8, and replace/ignore sanitize the string instead of keeping it. However, dump() still requires valid UTF-8 and throws type_error.316 for a value read with the default keep handler, unless an error handler is passed that replaces or ignores the ill-formed bytes. to_cbor()'s own error_handler parameter defaults to keep, so such a value is written back unchanged; with strict (the default if JSON_STRICT_BINARY_UTF8 is enabled), it throws the same exception instead. Byte strings (major type 2) are unaffected, since they are not required to hold text.

Tagged items

Tagged items (0xC0..0xDB) will throw a parse error by default. They can be ignored by passing cbor_tag_handler_t::ignore to function from_cbor, in which case the tag is skipped and the enclosed data item is parsed on its own. Passing cbor_tag_handler_t::store to function from_cbor stores tagged byte strings (for bytes 0xd8..0xdb) as binary values with the tag as subtype; other tagged values are read as if the tag were ignored. If several tags precede a byte string, only the innermost one is stored. Note that no tag is ever interpreted: for instance, a text string tagged with tag 0 (date/time) stays a string.

Example: deserialize a JSON value from CBOR
#include <iostream>
 #include <iomanip>
 #include <nlohmann/json.hpp>
@@ -46,4 +46,4 @@
   "compact": true,
   "schema": 0
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/features/binary_formats/cbor/index.md b/features/binary_formats/cbor/index.md index 52a83034f..ced9e55a1 100644 --- a/features/binary_formats/cbor/index.md +++ b/features/binary_formats/cbor/index.md @@ -181,7 +181,7 @@ Tagged items (0xC0..0xDB) are not interpreted either; see the note on tagged ite Negative integer overflow -CBOR negative integers (major type 1) are decoded as `-1 - n`. If the encoded magnitude `n` is too large for the result to fit into `number_integer_t` (`std::int64_t` by default), parsing fails with a [`parse_error.112`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error112) exception rather than overflowing silently. +CBOR negative integers (major type 1) are decoded as `-1 - n`. If the encoded magnitude `n` is too large for the result to fit into `number_integer_t` (`std::int64_t` by default), the result is stored as `number_float_t`, like a too small integer in JSON text. For example, `-18446744073709551616` (`0x3B` followed by eight `0xFF` bytes) is stored as `-1.8446744073709552e+19`. Object keys diff --git a/home/exceptions.md b/home/exceptions.md index e7eb8fd03..a4706dfdd 100644 --- a/home/exceptions.md +++ b/home/exceptions.md @@ -331,9 +331,6 @@ An unexpected byte was read in a [binary format](../features/binary_formats/inde [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.112] parse error at byte 9: syntax error while parsing CBOR value: negative integer overflow - ``` - ``` [json.exception.parse_error.112] parse error at byte 5: syntax error while parsing BSON document: document size 6 does not match the number of bytes read (5) ``` @@ -863,13 +860,18 @@ The JSON Patch operations 'remove' and 'add' cannot be applied to the root eleme ### json.exception.out_of_range.406 -A parsed number could not be stored as without changing it to NaN or INF. +A parsed number could not be stored without changing it to NaN or INF. For the binary formats, this happens when a +finite floating-point number does not fit into [`number_float_t`](../api/basic_json/number_float_t.md), for example a +double-precision number when `number_float_t` is `#!cpp float`. -!!! failure "Example message" +!!! failure "Example messages" ``` number overflow parsing '10E1000' ``` + ``` + [json.exception.out_of_range.406] syntax error while parsing CBOR value: number overflow + ``` ### json.exception.out_of_range.407 diff --git a/home/exceptions/index.html b/home/exceptions/index.html index e88df4d0a..389aae1cf 100644 --- a/home/exceptions/index.html +++ b/home/exceptions/index.html @@ -129,7 +129,6 @@ byte position of error: 8
[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.112] parse error at byte 9: syntax error while parsing CBOR value: negative integer overflow
 
[json.exception.parse_error.112] parse error at byte 5: syntax error while parsing BSON document: document size 6 does not match the number of bytes read (5)
 

json.exception.parse_error.113

A string could not be read from a binary format: either a value that is not a string was read where one was required (for instance as a map key), the string's length specification is invalid, or the string's bytes are not valid UTF-8 and the error_handler parameter of the corresponding from_* function is set to strict. By default (error_handler_t::keep), the bytes of a string are not checked for valid UTF-8 on read; see the ill-formed UTF-8 notes on the individual binary format pages for how such a string is handled depending on error_handler.

CBOR and MessagePack allow map keys of any type, but JSON object keys are always strings. Maps with keys of any other type (for instance integers or null) are therefore not supported; see the notes on CBOR and MessagePack.

Example messages

[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR object key: only string keys are supported, but found an unsigned integer; last byte: 0x01
 
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack object key: only string keys are supported, but found nil; last byte: 0xC0
@@ -250,8 +249,9 @@ exception id: 401
 

json.exception.out_of_range.403

The provided key was not found in the JSON object.

Example message

key 'foo' not found
 

json.exception.out_of_range.404

A reference token in a JSON Pointer could not be resolved.

Example message

unresolved reference token 'foo'
 

json.exception.out_of_range.405

The JSON Patch operations 'remove' and 'add' cannot be applied to the root element of the JSON value.

Example message

JSON pointer has no parent
-

json.exception.out_of_range.406

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

This exception previously indicated that the UBJSON and BSON binary formats did not support integer numbers greater than 9223372036854775807 due to limitations in the implemented mapping. However, these limitations have since been resolved, and this exception no longer occurs.

Exception cannot occur any more

json.exception.out_of_range.408

The size of an array or object in a binary format exceeds the maximal capacity: the size following # for UBJSON/BJData, or the encoded length for CBOR.

The exception is also thrown for a UBJSON array of a type that is encoded by its marker alone (Z, T or F) whose declared count exceeds 1,048,576 (1 << 20). Such an array has no payload, so its count alone decides how much memory is allocated, and a handful of bytes would otherwise describe billions of values. to_ubjson writes longer arrays of these types without the size and type annotation, so any value it produces can still be read back.

Example messages

excessive array size: 8658170730974374167
+

json.exception.out_of_range.406

A parsed number could not be stored without changing it to NaN or INF. For the binary formats, this happens when a finite floating-point number does not fit into number_float_t, for example a double-precision number when number_float_t is float.

Example messages

number overflow parsing '10E1000'
+
[json.exception.out_of_range.406] syntax error while parsing CBOR value: number overflow
+

json.exception.out_of_range.407

This exception previously indicated that the UBJSON and BSON binary formats did not support integer numbers greater than 9223372036854775807 due to limitations in the implemented mapping. However, these limitations have since been resolved, and this exception no longer occurs.

Exception cannot occur any more

json.exception.out_of_range.408

The size of an array or object in a binary format exceeds the maximal capacity: the size following # for UBJSON/BJData, or the encoded length for CBOR.

The exception is also thrown for a UBJSON array of a type that is encoded by its marker alone (Z, T or F) whose declared count exceeds 1,048,576 (1 << 20). Such an array has no payload, so its count alone decides how much memory is allocated, and a handful of bytes would otherwise describe billions of values. to_ubjson writes longer arrays of these types without the size and type annotation, so any value it produces can still be read back.

Example messages

excessive array size: 8658170730974374167
 
[json.exception.out_of_range.408] syntax error while parsing CBOR size: excessive array size
 
[json.exception.out_of_range.408] syntax error while parsing CBOR size: excessive map size
 
[json.exception.out_of_range.408] syntax error while parsing UBJSON size: excessive array size
@@ -298,4 +298,4 @@ array index 18446744073709551616 exceeds size_type
 exception id: 501
 

json.exception.other_error.501

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"}
 

json.exception.other_error.502

to_ubjson and to_bjdata were called with use_type = true but use_size = false. UBJSON requires a size marker (#) after a type marker ($).

Example message

[json.exception.other_error.502] use_type requires use_size = true
-

Note

This exception was added in version 3.13.0 unreleased. Before that, debug builds aborted on an assertion and release builds wrote a $ marker without #, which from_ubjson then rejected.

\ No newline at end of file +

Note

This exception was added in version 3.13.0 unreleased. Before that, debug builds aborted on an assertion and release builds wrote a $ marker without #, which from_ubjson then rejected.

\ No newline at end of file diff --git a/home/exceptions/index.md b/home/exceptions/index.md index 771140fec..52b32456d 100644 --- a/home/exceptions/index.md +++ b/home/exceptions/index.md @@ -395,10 +395,6 @@ Example messages [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.112] parse error at byte 9: syntax error while parsing CBOR value: negative integer overflow -``` - ``` [json.exception.parse_error.112] parse error at byte 5: syntax error while parsing BSON document: document size 6 does not match the number of bytes read (5) ``` @@ -993,14 +989,18 @@ JSON pointer has no parent ### json.exception.out_of_range.406 -A parsed number could not be stored as without changing it to NaN or INF. +A parsed number could not be stored without changing it to NaN or INF. For the binary formats, this happens when a finite floating-point number does not fit into [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md), for example a double-precision number when `number_float_t` is `float`. -Example message +Example messages ``` number overflow parsing '10E1000' ``` +``` +[json.exception.out_of_range.406] syntax error while parsing CBOR value: number overflow +``` + ### json.exception.out_of_range.407 This exception previously indicated that the UBJSON and BSON binary formats did not support integer numbers greater than 9223372036854775807 due to limitations in the implemented mapping. However, these limitations have since been resolved, and this exception no longer occurs. diff --git a/search/search_index.json b/search/search_index.json index 9ba93db40..8614f3714 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-\\.]","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"JSON for Modern C++","text":"

JSON for Modern C++ is a header-only C++11 library that turns JSON into a first-class C++ data type, using the operator magic of modern C++ so that creating, reading, and modifying JSON values feels as natural as it does in languages like Python. The whole library is available as a single header, json.hpp, with no dependencies, no subproject, and no complex build system to set up; a companion header, json_fwd.hpp, provides forward declarations to keep compile times down. See header-only integration for details. It is heavily unit-tested with 100% code coverage, checked with Valgrind and the Clang Sanitizers for memory leaks, and continuously fuzz-tested by Google OSS-Fuzz.

"},{"location":"#quick-start","title":"Quick start","text":"

Add the single header to your project and use the library like this:

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // parse a JSON string\n    json j = json::parse(R\"({\"happy\": true, \"pi\": 3.141})\");\n\n    // access and modify values\n    j[\"name\"] = \"Niels\";\n    j[\"list\"] = {1, 0, 2};\n\n    // serialize with an indent of 4 spaces\n    std::cout << j.dump(4) << '\\n';\n}\n

Get the library by copying the single header json.hpp from the releases page into a directory nlohmann on your include path, or by installing it with a package manager:

brew install nlohmann-json    # Homebrew\nvcpkg install nlohmann-json   # vcpkg\n
find_package(nlohmann_json 3.12.0 REQUIRED)\ntarget_link_libraries(myproject PRIVATE nlohmann_json::nlohmann_json)\n

See Integration for CMake in detail, all supported package managers (Conan, Meson, Bazel, Conda, and more), and pkg-config.

"},{"location":"#explore-the-documentation","title":"Explore the documentation","text":"

Unreleased changes

This documentation is built from the develop branch and may describe changes that are not part of a release yet. Their version numbers are followed by an unreleased badge; see Releases for what shipped in each version.

The library is licensed under the MIT License. The source code, issue tracker, and discussions are on GitHub.

"},{"location":"api/json/","title":"nlohmann::json","text":"
using json = basic_json<>;\n

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

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j =\n    {\n        {\"pi\", 3.141},\n        {\"happy\", true},\n        {\"name\", \"Niels\"},\n        {\"nothing\", nullptr},\n        {\n            \"answer\", {\n                {\"everything\", 42}\n            }\n        },\n        {\"list\", {1, 0, 2}},\n        {\n            \"object\", {\n                {\"currency\", \"USD\"},\n                {\"value\", 42.99}\n            }\n        }\n    };\n\n    // add new values\n    j[\"new\"][\"key\"][\"value\"] = {\"another\", \"list\"};\n\n    // count elements\n    auto s = j.size();\n    j[\"size\"] = s;\n\n    // pretty print with indent of 4 spaces\n    std::cout << std::setw(4) << j << '\\n';\n}\n

Output:

{\n    \"answer\": {\n        \"everything\": 42\n    },\n    \"happy\": true,\n    \"list\": [\n        1,\n        0,\n        2\n    ],\n    \"name\": \"Niels\",\n    \"new\": {\n        \"key\": {\n            \"value\": [\n                \"another\",\n                \"list\"\n            ]\n        }\n    },\n    \"nothing\": null,\n    \"object\": {\n        \"currency\": \"USD\",\n        \"value\": 42.99\n    },\n    \"pi\": 3.141,\n    \"size\": 8\n}\n
"},{"location":"api/json/#see-also","title":"See also","text":""},{"location":"api/json/#version-history","title":"Version history","text":"

Since version 1.0.0.

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

Deserializes an input stream to a JSON value.

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

the stream i

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

Strong guarantee: if an exception is thrown, there are no changes in j.

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

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

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

A UTF-8 byte order mark is silently ignored.

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

operator>> parses exactly one JSON value, so it can be called repeatedly to read a sequence of concatenated JSON values from the same stream:

json j1, j2;\ninput >> j1;  // parses the first value\ninput >> j2;  // parses the next value\n

A number must be followed by whitespace

A number is only terminated by the character that follows it. That character is read from the stream to detect the end of the number, and it is not put back. When a value that is a number is immediately followed by the next value, the first character of that next value is lost:

std::istringstream input(\"1true\");\njson j1, j2;\ninput >> j1;  // j1 == 1\ninput >> j2;  // throws parse_error.101: the stream now starts at \"rue\"\n

Separating the values with whitespace avoids this, because the character that is eaten is then the separator:

std::istringstream input(\"1 true\");\njson j1, j2;\ninput >> j1;  // j1 == 1\ninput >> j2;  // j2 == true\n

Only numbers are affected. Values ending in a self-delimiting character do not read past themselves, so truefalse, [1][2], {\"a\":1}{\"b\":2}, and \"a\"\"b\" can be read back to back without a separator.

Define JSON_PRECISE_STREAM_POSITION to 1 to leave the terminating character in the stream instead, so that the stream is positioned right after the value for every value type and no separator is needed. This is tracked in #5340.

Note that reading concatenated values does not work for JSON Lines (newline-delimited JSON) input -- see that page for why and for the recommended alternative.

By default, a '\\0' (NUL) byte encountered while reading a value is treated as end of input, rather than as an ordinary (and, outside of a string, invalid) byte; see the FAQ entry for details and the JSON_STRICT_NUL_HANDLING macro to opt into rejecting it instead. Because operator>> only parses a single value and does not require the rest of the stream to be consumed, a NUL byte after a complete value has no effect on operator>> either way; it only matters while a value is still being read.

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

See the migration guide for how to update existing code.

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

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

#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create stream with serialized JSON\n    std::stringstream ss;\n    ss << R\"({\n        \"number\": 23,\n        \"string\": \"Hello, world!\",\n        \"array\": [1, 2, 3, 4, 5],\n        \"boolean\": false,\n        \"null\": null\n    })\";\n\n    // create JSON value and read the serialization from the stream\n    json j;\n    ss >> j;\n\n    // serialize JSON\n    std::cout << std::setw(2) << j << '\\n';\n}\n

Output:

{\n  \"array\": [\n    1,\n    2,\n    3,\n    4,\n    5\n  ],\n  \"boolean\": false,\n  \"null\": null,\n  \"number\": 23,\n  \"string\": \"Hello, world!\"\n}\n
"},{"location":"api/operator_gtgt/#see-also","title":"See also","text":""},{"location":"api/operator_gtgt/#version-history","title":"Version history","text":""},{"location":"api/operator_literal_json/","title":"nlohmann::operator\"\"_json","text":"
json operator \"\"_json(const char* s, std::size_t n);\njson operator \"\"_json(const char8_t* s, std::size_t n);  // since C++20\n

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

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

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

This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS and the migration guide for details. The operator is declared in header <nlohmann/json_literals.hpp>, which <nlohmann/json.hpp> includes unless JSON_NO_AUTOMATIC_UDLS is defined.

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

json value parsed from s

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

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

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

Linear.

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    json j = R\"( {\"hello\": \"world\", \"answer\": 42} )\"_json;\n\n    std::cout << std::setw(2) << j << '\\n';\n}\n

Output:

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

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

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

using nlohmann::literals::operator \"\"_json_pointer;\nusing namespace nlohmann::literals;\nusing namespace nlohmann::json_literals;\nusing namespace nlohmann::literals::json_literals;\nusing namespace nlohmann;\n
This is suggested to ease migration to the next major version release of the library. See JSON_USE_GLOBAL_UDLS and the migration guide for details. The operator is declared in header <nlohmann/json_literals.hpp>, which <nlohmann/json.hpp> includes unless JSON_NO_AUTOMATIC_UDLS is defined.

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

json_pointer value parsed from s

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

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

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

Linear.

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    json j = R\"( {\"hello\": \"world\", \"answer\": 42} )\"_json;\n    auto val = j[\"/hello\"_json_pointer];\n\n    std::cout << std::setw(2) << val << '\\n';\n}\n

Output:

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

the stream o

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

Linear.

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

Deprecation

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

See the migration guide for how to update existing code.

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_array = {1, 2, 4, 8, 16};\n\n    // serialize without indentation\n    std::cout << j_object << \"\\n\\n\";\n    std::cout << j_array << \"\\n\\n\";\n\n    // serialize with indentation\n    std::cout << std::setw(4) << j_object << \"\\n\\n\";\n    std::cout << std::setw(2) << j_array << \"\\n\\n\";\n    std::cout << std::setw(1) << std::setfill('\\t') << j_object << \"\\n\\n\";\n}\n

Output:

{\"one\":1,\"two\":2}\n\n[1,2,4,8,16]\n\n{\n    \"one\": 1,\n    \"two\": 2\n}\n\n[\n  1,\n  2,\n  4,\n  8,\n  16\n]\n\n{\n    \"one\": 1,\n    \"two\": 2\n}\n
Example: (2) write JSON pointer to stream

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON pointer\n    json::json_pointer ptr(\"/foo/bar/baz\");\n\n    // write string representation to stream\n    std::cout << ptr << std::endl;\n}\n

Output:

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

This type preserves the insertion order of object keys.

"},{"location":"api/ordered_json/#iterator-invalidation","title":"Iterator invalidation","text":"

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

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

ordered_map has no lookup index: every key-based object operation is a linear scan, so building or parsing an object of n keys costs O(n\u00b2) rather than O(n log n). See ordered_map complexity for the per-operation table and for measured numbers.

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing ordered_json = nlohmann::ordered_json;\n\nint main()\n{\n    ordered_json j;\n    j[\"one\"] = 1;\n    j[\"two\"] = 2;\n    j[\"three\"] = 3;\n\n    std::cout << j.dump(2) << '\\n';\n}\n

Output:

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

Since version 3.9.0.

"},{"location":"api/ordered_map/","title":"nlohmann::ordered_map","text":"
template<class Key, class T, class IgnoredLess = std::less<Key>,\n         class Allocator = std::allocator<std::pair<const Key, T>>>\nstruct ordered_map : std::vector<std::pair<const Key, T>, Allocator>;\n

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

"},{"location":"api/ordered_map/#template-parameters","title":"Template parameters","text":"Key key type T mapped type IgnoredLess comparison function (ignored and only added to ensure compatibility with std::map) Allocator allocator type"},{"location":"api/ordered_map/#iterator-invalidation","title":"Iterator invalidation","text":"

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

When the storage grows, the keys are copied and the mapped values are moved to the new storage. A plain std::vector would copy the whole elements instead, because their const keys make them not nothrow move constructible; for ordered_json, this would be a deep copy of every nested value. The values are only copied if T is not default constructible or not nothrow move assignable.

"},{"location":"api/ordered_map/#member-types","title":"Member types","text":""},{"location":"api/ordered_map/#member-functions","title":"Member functions","text":""},{"location":"api/ordered_map/#exception-safety","title":"Exception safety","text":"

emplace, operator[], and insert(value) have the strong exception guarantee: if an exception is thrown (for instance, because copying a key or allocating memory fails), the contents of the container are unchanged.

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

Because the elements are stored in a std::vector in insertion order, there is no index to look a key up by. Every key-based operation performs a linear scan over the stored elements. With n denoting the number of elements in the container:

Operation Complexity Note emplace O(n) scans for an existing key, then appends (amortized O(1)) operator[] O(n) delegates to emplace (non-const) or at (const) at O(n) throws std::out_of_range if the key is not found find O(n) count O(n) the result is always 0 or 1 erase(key) O(n) scan, then move the remaining elements one position down erase(pos), erase(first, last) O(n) moves all elements after the erased range insert(value) O(n) equivalent to emplace insert(first, last) O((n + m) * m) for m inserted elements

This differs from std::map, where the same operations are O(log n).

Quadratic cost of building large objects

Because every insertion scans all elements inserted so far, building an object of n distinct keys costs O(n\u00b2) in total. This applies to filling an ordered_json object key by key as well as to parsing one, since the parser inserts each key as it is read.

The cost is negligible for the object sizes typically found in configuration files or API payloads, but it grows steeply for machine-generated objects with many thousands of keys. Measured with -O2 -DNDEBUG for parsing a flat object of n keys, relative to nlohmann::json (which uses std::map):

n json ordered_json factor 2000 0.7 ms 3.6 ms 5\u00d7 4000 0.8 ms 14.0 ms 19\u00d7 8000 1.6 ms 67.8 ms 43\u00d7 16 000 3.3 ms 181.6 ms 54\u00d7

If key order matters for objects of that size, consider a container with a lookup index, such as nlohmann::fifo_map (integration), as the object type -- see object order.

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\n// simple output function\ntemplate<typename Map>\nvoid output(const char* prefix, const Map& m)\n{\n    std::cout << prefix << \" = { \";\n    for (auto& element : m)\n    {\n        std::cout << element.first << \":\" << element.second << ' ';\n    }\n    std::cout << \"}\" << std::endl;\n}\n\nint main()\n{\n    // create and fill two maps\n    nlohmann::ordered_map<std::string, std::string> m_ordered;\n    m_ordered[\"one\"] = \"eins\";\n    m_ordered[\"two\"] = \"zwei\";\n    m_ordered[\"three\"] = \"drei\";\n\n    std::map<std::string, std::string> m_std;\n    m_std[\"one\"] = \"eins\";\n    m_std[\"two\"] = \"zwei\";\n    m_std[\"three\"] = \"drei\";\n\n    // output: m_ordered is ordered by insertion order, m_std is ordered by key\n    output(\"m_ordered\", m_ordered);\n    output(\"m_std\", m_std);\n\n    // erase and re-add \"one\" key\n    m_ordered.erase(\"one\");\n    m_ordered[\"one\"] = \"eins\";\n\n    m_std.erase(\"one\");\n    m_std[\"one\"] = \"eins\";\n\n    // output: m_ordered shows newly added key at the end; m_std is again ordered by key\n    output(\"m_ordered\", m_ordered);\n    output(\"m_std\", m_std);\n}\n

Output:

m_ordered = { one:eins two:zwei three:drei }\nm_std = { one:eins three:drei two:zwei }\nm_ordered = { two:zwei three:drei one:eins }\nm_std = { one:eins three:drei two:zwei }\n
"},{"location":"api/ordered_map/#see-also","title":"See also","text":""},{"location":"api/ordered_map/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/","title":"nlohmann::adl_serializer","text":"
template<typename, typename>\nstruct adl_serializer;\n

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

It is implemented similarly to

template<typename ValueType>\nstruct adl_serializer {\n    template<typename BasicJsonType>\n    static void to_json(BasicJsonType& j, const T& value) {\n        // calls the \"to_json\" method in T's namespace\n    }\n\n    template<typename BasicJsonType>\n    static void from_json(const BasicJsonType& j, T& value) {\n        // same thing, but with the \"from_json\" method\n    }\n};\n
"},{"location":"api/adl_serializer/#member-functions","title":"Member functions","text":""},{"location":"api/adl_serializer/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/from_json/","title":"nlohmann::adl_serializer::from_json","text":"
// (1)\ntemplate<typename BasicJsonType, typename TargetType = ValueType>\nstatic auto from_json(BasicJsonType && j, TargetType& val) noexcept(\n    noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))\n-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())\n\n// (2)\ntemplate<typename BasicJsonType, typename TargetType = ValueType>\nstatic auto from_json(BasicJsonType && j) noexcept(\nnoexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))\n-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))\n

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

  1. This function is chosen for default-constructible value types.
  2. This function is chosen for value types which are not default-constructible.
"},{"location":"api/adl_serializer/from_json/#parameters","title":"Parameters","text":"j (in) JSON value to read from val (out) value to write to"},{"location":"api/adl_serializer/from_json/#return-value","title":"Return value","text":"
  1. (none) -- the converted value is written to the output parameter val.
  2. the JSON value j converted to TargetType
"},{"location":"api/adl_serializer/from_json/#examples","title":"Examples","text":"Example: (1) Default-constructible type

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n    std::string name;\n    std::string address;\n    int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid from_json(const json& j, person& p)\n{\n    j.at(\"name\").get_to(p.name);\n    j.at(\"address\").get_to(p.address);\n    j.at(\"age\").get_to(p.age);\n}\n} // namespace ns\n\nint main()\n{\n    json j;\n    j[\"name\"] = \"Ned Flanders\";\n    j[\"address\"] = \"744 Evergreen Terrace\";\n    j[\"age\"] = 60;\n\n    auto p = j.get<ns::person>();\n\n    std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person (not default constructible)\nstruct person\n{\n    person(std::string n, std::string a, int aa)\n        : name(std::move(n)), address(std::move(a)), age(aa)\n    {}\n\n    std::string name;\n    std::string address;\n    int age;\n};\n} // namespace ns\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer<ns::person>\n{\n    static ns::person from_json(const json& j)\n    {\n        return {j.at(\"name\"), j.at(\"address\"), j.at(\"age\")};\n    }\n\n    // Here's the catch! You must provide a to_json method! Otherwise, you\n    // will not be able to convert person to json, since you fully\n    // specialized adl_serializer on that type\n    static void to_json(json& j, ns::person p)\n    {\n        j[\"name\"] = p.name;\n        j[\"address\"] = p.address;\n        j[\"age\"] = p.age;\n    }\n};\n} // namespace nlohmann\n\nint main()\n{\n    json j;\n    j[\"name\"] = \"Ned Flanders\";\n    j[\"address\"] = \"744 Evergreen Terrace\";\n    j[\"age\"] = 60;\n\n    auto p = j.get<ns::person>();\n\n    std::cout << p.name << \" (\" << p.age << \") lives in \" << p.address << std::endl;\n}\n

Output:

Ned Flanders (60) lives in 744 Evergreen Terrace\n
"},{"location":"api/adl_serializer/from_json/#see-also","title":"See also","text":""},{"location":"api/adl_serializer/from_json/#version-history","title":"Version history","text":""},{"location":"api/adl_serializer/to_json/","title":"nlohmann::adl_serializer::to_json","text":"
template<typename BasicJsonType, typename TargetType = ValueType>\nstatic auto to_json(BasicJsonType& j, TargetType && val) noexcept(\n    noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))\n-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())\n

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

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nnamespace ns\n{\n// a simple struct to model a person\nstruct person\n{\n    std::string name;\n    std::string address;\n    int age;\n};\n} // namespace ns\n\nnamespace ns\n{\nvoid to_json(json& j, const person& p)\n{\n    j = json{ {\"name\", p.name}, {\"address\", p.address}, {\"age\", p.age} };\n}\n} // namespace ns\n\nint main()\n{\n    ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n    json j = p;\n\n    std::cout << j << std::endl;\n}\n

Output:

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

Defined in header <nlohmann/json.hpp>

template<\n    template<typename U, typename V, typename... Args> class ObjectType = std::map,\n    template<typename U, typename... Args> class ArrayType = std::vector,\n    class StringType = std::string,\n    class BooleanType = bool,\n    class NumberIntegerType = std::int64_t,\n    class NumberUnsignedType = std::uint64_t,\n    class NumberFloatType = double,\n    template<typename U> class AllocatorType = std::allocator,\n    template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,\n    class BinaryType = std::vector<std::uint8_t>,\n    class CustomBaseClass = void\n>\nclass basic_json;\n
"},{"location":"api/basic_json/#template-parameters","title":"Template parameters","text":"Template parameter Description Derived type ObjectType type for JSON objects object_t ArrayType type for JSON arrays array_t StringType type for JSON strings and object keys string_t BooleanType type for JSON booleans boolean_t NumberIntegerType type for JSON integer numbers number_integer_t NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t NumberFloatType type for JSON floating-point numbers number_float_t AllocatorType type of the allocator to use JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer BinaryType type for binary arrays binary_t CustomBaseClass extension point for user code json_base_class_t

The library imposes a number of requirements on these types that are not expressed as C++ concepts, such as the container operations object_t and array_t must provide, or the fact that StringType must be char-based. They are collected in Template Parameter Requirements.

"},{"location":"api/basic_json/#specializations","title":"Specializations","text":""},{"location":"api/basic_json/#iterator-invalidation","title":"Iterator invalidation","text":"

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

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

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

The class satisfies the following concept requirements:

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

Functions to inspect the type of a JSON value.

Optional functions to access the diagnostic positions.

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

Direct access to the stored value of a JSON value.

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

Access to the JSON value

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

The example shows how the library is used.

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j =\n    {\n        {\"pi\", 3.141},\n        {\"happy\", true},\n        {\"name\", \"Niels\"},\n        {\"nothing\", nullptr},\n        {\n            \"answer\", {\n                {\"everything\", 42}\n            }\n        },\n        {\"list\", {1, 0, 2}},\n        {\n            \"object\", {\n                {\"currency\", \"USD\"},\n                {\"value\", 42.99}\n            }\n        }\n    };\n\n    // add new values\n    j[\"new\"][\"key\"][\"value\"] = {\"another\", \"list\"};\n\n    // count elements\n    auto s = j.size();\n    j[\"size\"] = s;\n\n    // pretty print with indent of 4 spaces\n    std::cout << std::setw(4) << j << '\\n';\n}\n

Output:

{\n    \"answer\": {\n        \"everything\": 42\n    },\n    \"happy\": true,\n    \"list\": [\n        1,\n        0,\n        2\n    ],\n    \"name\": \"Niels\",\n    \"new\": {\n        \"key\": {\n            \"value\": [\n                \"another\",\n                \"list\"\n            ]\n        }\n    },\n    \"nothing\": null,\n    \"object\": {\n        \"currency\": \"USD\",\n        \"value\": 42.99\n    },\n    \"pi\": 3.141,\n    \"size\": 8\n}\n
"},{"location":"api/basic_json/#see-also","title":"See also","text":""},{"location":"api/basic_json/#version-history","title":"Version history","text":""},{"location":"api/basic_json/accept/","title":"nlohmann::basic_json::accept","text":"
// (1)\ntemplate<typename InputType>\nstatic bool accept(InputType&& i,\n                   const bool ignore_comments = false,\n                   const bool ignore_trailing_commas = false);\n\n// (2)\ntemplate<typename IteratorType, typename SentinelType = IteratorType>\nstatic bool accept(IteratorType first, SentinelType last,\n                   const bool ignore_comments = false,\n                   const bool ignore_trailing_commas = false);\n

Checks whether the input is valid JSON.

  1. Reads from a compatible input.
  2. Reads from a pair of character iterators, or an iterator and a sentinel of a different type (C++20 ranges support)

    The value_type of the iterator must be an integral type with a size of 1, 2, or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16, and UTF-32. If SentinelType differs from IteratorType, it must be comparable to the iterator type with operator!=.

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

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

A compatible input, for instance:

IteratorType

a compatible iterator type, for instance.

SentinelType

defaults to IteratorType; may be a different type comparable to IteratorType via operator!=, for instance.

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

Whether the input is valid JSON.

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

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

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

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

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

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

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

A UTF-8 byte order mark is silently ignored.

By default, a '\\0' (NUL) byte anywhere in the input is treated as end of input, rather than as an ordinary (and, outside of a string, invalid) byte; see the FAQ entry for details and the JSON_STRICT_NUL_HANDLING macro to opt into rejecting it instead.

"},{"location":"api/basic_json/accept/#examples","title":"Examples","text":"Example: (1) reading from a string

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // a valid JSON text\n    auto valid_text = R\"(\n    {\n        \"numbers\": [1, 2, 3]\n    }\n    )\";\n\n    // an invalid JSON text\n    auto invalid_text = R\"(\n    {\n        \"strings\": [\"extra\", \"comma\", ]\n    }\n    )\";\n\n    std::cout << std::boolalpha\n              << json::accept(valid_text) << ' '\n              << json::accept(invalid_text) << '\\n';\n}\n

Output:

true false\n
Example: (2) reading from an iterator pair

The example below demonstrates the accept() function reading from an iterator pair. Only the first call covers exactly the JSON text; the second one also covers the trailing bytes and is therefore rejected.

#include <iostream>\n#include <vector>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // a buffer containing a JSON text followed by more data\n    std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'};\n\n    std::cout << std::boolalpha\n              << json::accept(input.begin(), input.begin() + 7) << ' '\n              << json::accept(input.begin(), input.end()) << '\\n';\n}\n

Output:

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

Deprecation

Overload (2) replaces calls to accept with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like accept({ptr, ptr+len}, ...); with accept(ptr, ptr+len, ...);.

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

See the migration guide for how to update existing code.

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

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

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

JSON array value

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

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

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

Linear in the size of init.

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

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

  1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys
  2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
"},{"location":"api/basic_json/array/#examples","title":"Examples","text":"Example

The following code shows an example for the array function.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON arrays\n    json j_no_init_list = json::array();\n    json j_empty_init_list = json::array({});\n    json j_nonempty_init_list = json::array({1, 2, 3, 4});\n    json j_list_of_pairs = json::array({ {\"one\", 1}, {\"two\", 2} });\n\n    // serialize the JSON arrays\n    std::cout << j_no_init_list << '\\n';\n    std::cout << j_empty_init_list << '\\n';\n    std::cout << j_nonempty_init_list << '\\n';\n    std::cout << j_list_of_pairs << '\\n';\n}\n

Output:

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

The type used to store JSON arrays.

RFC 8259 describes JSON arrays as follows:

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

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

"},{"location":"api/basic_json/array_t/#template-parameters","title":"Template parameters","text":"ArrayType container type to store arrays. It must be a vector-like container: the library uses operator[], at(), and resize(), and requires random-access iterators. std::vector and std::deque qualify; std::list does not. See Template Parameter Requirements for the full list of requirements. AllocatorType the allocator to use for objects (e.g., std::allocator)"},{"location":"api/basic_json/array_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/array_t/#default-type","title":"Default type","text":"

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

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

RFC 8259 specifies:

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

In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.

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

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

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    std::cout << std::boolalpha << std::is_same<std::vector<json>, json::array_t>::value << std::endl;\n}\n

Output:

true\n
"},{"location":"api/basic_json/array_t/#see-also","title":"See also","text":""},{"location":"api/basic_json/array_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/as_base_class/","title":"nlohmann::basic_json::as_base_class","text":"
json_base_class_t& as_base_class() noexcept;\nconst json_base_class_t& as_base_class() const noexcept;\n

Returns a reference to this object as its custom base class json_base_class_t. No copy is made.

Since basic_json derives from json_base_class_t, a member of basic_json hides any member of the custom base class with the same name. This function makes such hidden members accessible again.

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

reference to this object as json_base_class_t

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

No-throw guarantee: this function never throws exceptions.

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

Constant.

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

The function is equivalent to static_cast<json_base_class_t&>(j) (or static_cast<const json_base_class_t&>(j)).

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

The example shows how to use as_base_class to access members of the custom base class that are hidden by members of basic_json.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nclass base_class_with_hidden_members\n{\n  public:\n    const char* type_name() const noexcept\n    {\n        return \"my_type_name\";\n    }\n\n    std::size_t size() const noexcept\n    {\n        return 42;\n    }\n};\n\nusing json = nlohmann::basic_json <\n             std::map,\n             std::vector,\n             std::string,\n             bool,\n             std::int64_t,\n             std::uint64_t,\n             double,\n             std::allocator,\n             nlohmann::adl_serializer,\n             std::vector<std::uint8_t>,\n             base_class_with_hidden_members\n             >;\n\nint main()\n{\n    json j = {1, 2, 3};\n\n    // the members of basic_json hide the members of the base class\n    std::cout << j.type_name() << ' ' << j.size() << '\\n';\n\n    // access the hidden members of the base class\n    std::cout << j.as_base_class().type_name() << ' ' << j.as_base_class().size() << '\\n';\n}\n

Output:

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

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

"},{"location":"api/basic_json/at/#exceptions","title":"Exceptions","text":"
  1. The function can throw the following exceptions:
    • Throws type_error.304 if the JSON value is not an array; in this case, calling at with an index makes no sense. See the example below.
    • Throws out_of_range.401 if the index idx is out of range of the array; that is, idx >= size(). See the example below.
  2. The function can throw the following exceptions:
    • Throws type_error.304 if the JSON value is not an object; in this case, calling at with a key makes no sense. See the example below.
    • Throws out_of_range.403 if the key key is not stored in the object; that is, find(key) == end(). See the example below.
  3. See 2.
  4. The function can throw the following exceptions:
    • Throws parse_error.106 if an array index in the passed JSON pointer ptr begins with '0'. See the example below.
    • Throws parse_error.109 if an array index in the passed JSON pointer ptr is not a number. See the example below.
    • Throws out_of_range.401 if an array index in the passed JSON pointer ptr is out of range. See the 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 the example below.
    • Throws out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See the example below.
    • Throws out_of_range.404 if the JSON pointer ptr can not be resolved. See the example below.
    • Throws out_of_range.410 if an array index in the passed JSON pointer ptr exceeds the range of size_type (e.g., on 32-bit platforms).
"},{"location":"api/basic_json/at/#complexity","title":"Complexity","text":"
  1. Constant.
  2. Logarithmic in the size of the container.
  3. Logarithmic in the size of the container.
  4. Logarithmic in the size of the container.
"},{"location":"api/basic_json/at/#notes","title":"Notes","text":"

Deprecation

Overload (4) also accepts a json_pointer whose template argument is a basic_json specialization (e.g., nlohmann::json_pointer<nlohmann::json>) instead of a string type. This is deprecated since version 3.11.0 and will be removed in a future major version; use basic_json::json_pointer (for json, nlohmann::json_pointer<std::string>) instead.

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

See the migration guide for how to update existing code.

"},{"location":"api/basic_json/at/#examples","title":"Examples","text":"Example: (1) access specified array element with bounds checking

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON array\n    json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n    // output element at index 2 (third element)\n    std::cout << array.at(2) << '\\n';\n\n    // change element at index 1 (second element) to \"second\"\n    array.at(1) = \"second\";\n\n    // output changed array\n    std::cout << array << '\\n';\n\n    // exception type_error.304\n    try\n    {\n        // use at() on a non-array type\n        json str = \"I am a string\";\n        str.at(0) = \"Another string\";\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // exception out_of_range.401\n    try\n    {\n        // try to write beyond the array limit\n        array.at(5) = \"sixth\";\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

\"third\"\n[\"first\",\"second\",\"third\",\"fourth\"]\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n
Example: (1) access specified array element with bounds checking

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON array\n    const json array = {\"first\", \"2nd\", \"third\", \"fourth\"};\n\n    // output element at index 2 (third element)\n    std::cout << array.at(2) << '\\n';\n\n    // exception type_error.304\n    try\n    {\n        // use at() on a non-array type\n        const json str = \"I am a string\";\n        std::cout << str.at(0) << '\\n';\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // exception out_of_range.401\n    try\n    {\n        // try to read beyond the array limit\n        std::cout << array.at(5) << '\\n';\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

\"third\"\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.401] array index 5 is out of range\n
Example: (2) access specified object element with bounds checking

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON object\n    json object =\n    {\n        {\"the good\", \"il buono\"},\n        {\"the bad\", \"il cattivo\"},\n        {\"the ugly\", \"il brutto\"}\n    };\n\n    // output element with key \"the ugly\"\n    std::cout << object.at(\"the ugly\") << '\\n';\n\n    // change element with key \"the bad\"\n    object.at(\"the bad\") = \"il cattivo\";\n\n    // output changed array\n    std::cout << object << '\\n';\n\n    // exception type_error.304\n    try\n    {\n        // use at() on a non-object type\n        json str = \"I am a string\";\n        str.at(\"the good\") = \"Another string\";\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // exception out_of_range.401\n    try\n    {\n        // try to write at a nonexisting key\n        object.at(\"the fast\") = \"il rapido\";\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

\"il brutto\"\n{\"the bad\":\"il cattivo\",\"the good\":\"il buono\",\"the ugly\":\"il brutto\"}\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.403] key 'the fast' not found\n
Example: (2) access specified object element with bounds checking

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON object\n    const json object =\n    {\n        {\"the good\", \"il buono\"},\n        {\"the bad\", \"il cattivo\"},\n        {\"the ugly\", \"il brutto\"}\n    };\n\n    // output element with key \"the ugly\"\n    std::cout << object.at(\"the ugly\") << '\\n';\n\n    // exception type_error.304\n    try\n    {\n        // use at() on a non-object type\n        const json str = \"I am a string\";\n        std::cout << str.at(\"the good\") << '\\n';\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // exception out_of_range.401\n    try\n    {\n        // try to read from a nonexisting key\n        std::cout << object.at(\"the fast\") << '\\n';\n    }\n    catch (const json::out_of_range)\n    {\n        std::cout << \"out of range\" << '\\n';\n    }\n}\n

Output:

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

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

#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON object\n    json object =\n    {\n        {\"the good\", \"il buono\"},\n        {\"the bad\", \"il cattivo\"},\n        {\"the ugly\", \"il brutto\"}\n    };\n\n    // output element with key \"the ugly\" using string_view\n    std::cout << object.at(\"the ugly\"sv) << '\\n';\n\n    // change element with key \"the bad\" using string_view\n    object.at(\"the bad\"sv) = \"il cattivo\";\n\n    // output changed array\n    std::cout << object << '\\n';\n\n    // exception type_error.304\n    try\n    {\n        // use at() with string_view on a non-object type\n        json str = \"I am a string\";\n        str.at(\"the good\"sv) = \"Another string\";\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // exception out_of_range.401\n    try\n    {\n        // try to write at a nonexisting key using string_view\n        object.at(\"the fast\"sv) = \"il rapido\";\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

\"il brutto\"\n{\"the bad\":\"il cattivo\",\"the good\":\"il buono\",\"the ugly\":\"il brutto\"}\n[json.exception.type_error.304] cannot use at() with string\n[json.exception.out_of_range.403] key 'the fast' not found\n
Example: (3) access specified object element using string_view with bounds checking

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

#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON object\n    const json object =\n    {\n        {\"the good\", \"il buono\"},\n        {\"the bad\", \"il cattivo\"},\n        {\"the ugly\", \"il brutto\"}\n    };\n\n    // output element with key \"the ugly\" using string_view\n    std::cout << object.at(\"the ugly\"sv) << '\\n';\n\n    // exception type_error.304\n    try\n    {\n        // use at() with string_view on a non-object type\n        const json str = \"I am a string\";\n        std::cout << str.at(\"the good\"sv) << '\\n';\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // exception out_of_range.401\n    try\n    {\n        // try to read from a nonexisting key using string_view\n        std::cout << object.at(\"the fast\"sv) << '\\n';\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << \"out of range\" << '\\n';\n    }\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    // create a JSON value\n    json j =\n    {\n        {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n    };\n\n    // read-only access\n\n    // output element with JSON pointer \"/number\"\n    std::cout << j.at(\"/number\"_json_pointer) << '\\n';\n    // output element with JSON pointer \"/string\"\n    std::cout << j.at(\"/string\"_json_pointer) << '\\n';\n    // output element with JSON pointer \"/array\"\n    std::cout << j.at(\"/array\"_json_pointer) << '\\n';\n    // output element with JSON pointer \"/array/1\"\n    std::cout << j.at(\"/array/1\"_json_pointer) << '\\n';\n\n    // writing access\n\n    // change the string\n    j.at(\"/string\"_json_pointer) = \"bar\";\n    // output the changed string\n    std::cout << j[\"string\"] << '\\n';\n\n    // change an array element\n    j.at(\"/array/1\"_json_pointer) = 21;\n    // output the changed array\n    std::cout << j[\"array\"] << '\\n';\n\n    // out_of_range.106\n    try\n    {\n        // try to use an array index with leading '0'\n        json::reference ref = j.at(\"/array/01\"_json_pointer);\n    }\n    catch (const json::parse_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.109\n    try\n    {\n        // try to use an array index that is not a number\n        json::reference ref = j.at(\"/array/one\"_json_pointer);\n    }\n    catch (const json::parse_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.401\n    try\n    {\n        // try to use an invalid array index\n        json::reference ref = j.at(\"/array/4\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.402\n    try\n    {\n        // try to use the array index '-'\n        json::reference ref = j.at(\"/array/-\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.403\n    try\n    {\n        // try to use a JSON pointer to a nonexistent object key\n        json::const_reference ref = j.at(\"/foo\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.404\n    try\n    {\n        // try to use a JSON pointer that cannot be resolved\n        json::reference ref = j.at(\"/number/foo\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

1\n\"foo\"\n[1,2]\n2\n\"bar\"\n[1,21]\n[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'\n[json.exception.parse_error.109] parse error: array index 'one' is not a number\n[json.exception.out_of_range.401] array index 4 is out of range\n[json.exception.out_of_range.402] array index '-' (2) is out of range\n[json.exception.out_of_range.403] key 'foo' not found\n[json.exception.out_of_range.404] unresolved reference token 'foo'\n
Example: (4) access specified element via JSON Pointer

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    // create a JSON value\n    const json j =\n    {\n        {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n    };\n\n    // read-only access\n\n    // output element with JSON pointer \"/number\"\n    std::cout << j.at(\"/number\"_json_pointer) << '\\n';\n    // output element with JSON pointer \"/string\"\n    std::cout << j.at(\"/string\"_json_pointer) << '\\n';\n    // output element with JSON pointer \"/array\"\n    std::cout << j.at(\"/array\"_json_pointer) << '\\n';\n    // output element with JSON pointer \"/array/1\"\n    std::cout << j.at(\"/array/1\"_json_pointer) << '\\n';\n\n    // out_of_range.109\n    try\n    {\n        // try to use an array index that is not a number\n        json::const_reference ref = j.at(\"/array/one\"_json_pointer);\n    }\n    catch (const json::parse_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.401\n    try\n    {\n        // try to use an invalid array index\n        json::const_reference ref = j.at(\"/array/4\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.402\n    try\n    {\n        // try to use the array index '-'\n        json::const_reference ref = j.at(\"/array/-\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.403\n    try\n    {\n        // try to use a JSON pointer to a nonexistent object key\n        json::const_reference ref = j.at(\"/foo\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    // out_of_range.404\n    try\n    {\n        // try to use a JSON pointer that cannot be resolved\n        json::const_reference ref = j.at(\"/number/foo\"_json_pointer);\n    }\n    catch (const json::out_of_range& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

1\n\"foo\"\n[1,2]\n2\n[json.exception.parse_error.109] parse error: array index 'one' is not a number\n[json.exception.out_of_range.401] array index 4 is out of range\n[json.exception.out_of_range.402] array index '-' (2) is out of range\n[json.exception.out_of_range.403] key 'foo' not found\n[json.exception.out_of_range.404] unresolved reference token 'foo'\n
"},{"location":"api/basic_json/at/#see-also","title":"See also","text":""},{"location":"api/basic_json/at/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0.
  2. Added in version 1.0.0.
  3. Added in version 3.11.0. Fixed in version 3.13.0 unreleased to consistently accept std::string_view-convertible keys, as already supported by operator[], value, find, and other lookup functions.
  4. Added in version 2.0.0.
"},{"location":"api/basic_json/back/","title":"nlohmann::basic_json::back","text":"
reference back();\n\nconst_reference back() const;\n

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

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

In the case of a structured type (array or object), a reference to the last element is returned. In the case of number, string, boolean, or binary values, a reference to the value is returned.

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

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

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

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

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

Constant.

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

Precondition

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

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

The following code shows an example for back().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_boolean = true;\n    json j_number_integer = 17;\n    json j_number_float = 23.42;\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_object_empty(json::value_t::object);\n    json j_array = {1, 2, 4, 8, 16};\n    json j_array_empty(json::value_t::array);\n    json j_string = \"Hello, world\";\n\n    // call back()\n    std::cout << j_boolean.back() << '\\n';\n    std::cout << j_number_integer.back() << '\\n';\n    std::cout << j_number_float.back() << '\\n';\n    std::cout << j_object.back() << '\\n';\n    //std::cout << j_object_empty.back() << '\\n';  // undefined behavior\n    std::cout << j_array.back() << '\\n';\n    //std::cout << j_array_empty.back() << '\\n';   // undefined behavior\n    std::cout << j_string.back() << '\\n';\n\n    // back() called on a null value\n    try\n    {\n        json j_null;\n        j_null.back();\n    }\n    catch (const json::invalid_iterator& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

true\n17\n23.42\n2\n16\n\"Hello, world\"\n[json.exception.invalid_iterator.214] cannot get value\n
"},{"location":"api/basic_json/back/#see-also","title":"See also","text":""},{"location":"api/basic_json/back/#version-history","title":"Version history","text":""},{"location":"api/basic_json/basic_json/","title":"nlohmann::basic_json::basic_json","text":"
// (1)\nbasic_json(const value_t v);\n\n// (2)\nbasic_json(std::nullptr_t = nullptr) noexcept;\n\n// (3)\ntemplate<typename CompatibleType>\nbasic_json(CompatibleType&& val) noexcept(noexcept(\n           JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),\n                                      std::forward<CompatibleType>(val))));\n\n// (4)\ntemplate<typename BasicJsonType>\nbasic_json(const BasicJsonType& val);\n\n// (5)\nbasic_json(initializer_list_t init,\n           bool type_deduction = true,\n           value_t manual_type = value_t::array);\n\n// (6)\nbasic_json(size_type cnt, const basic_json& val);\n\n// (7)\nbasic_json(iterator first, iterator last);\nbasic_json(const_iterator first, const_iterator last);\n\n// (8)\nbasic_json(const basic_json& other);\n\n// (9)\nbasic_json(basic_json&& other) noexcept;\n
  1. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:

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

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

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

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

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

    • arrays: array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::valarray, std::set, std::unordered_set, std::multiset, and std::unordered_multiset with a value_type from which a basic_json value can be constructed.
    • objects: object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to string_t and a value_type from which a basic_json value can be constructed.
    • strings: string_t, string literals, and all compatible string containers can be used.
    • numbers: number_integer_t, number_unsigned_t, number_float_t, and all convertible number types such as int, size_t, int64_t, float or double can be used.
    • boolean: boolean_t / bool can be used.
    • binary: binary_t / std::vector<uint8_t> may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with const char* will be directed to the string constructor instead. This is both for backwards compatibility and due to the fact that a binary type is not a standard JSON type.

    See the examples below.

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

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

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

    1. If the list is empty, an empty JSON object value {} is created.
    2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values.
    3. In all other cases, an array is created.

    The following flowchart also takes into account what happens when type_deduction is false, in which case manual_type decides between object and array, and an object can only be forced if init actually matches rule 2 (or is empty):

    flowchart TD\n    A([\"initializer_list init\"]) --> B{\"empty, or every element is a 2-element<br/>array whose first element is a string?\"}\n    B -->|\"yes\"| C{\"type_deduction\"}\n    B -->|\"no\"| D{\"type_deduction\"}\n    C -->|\"true\"| OBJ[\"create object\"]\n    C -->|\"false\"| E{\"manual_type\"}\n    E -->|\"object\"| OBJ\n    E -->|\"array\"| ARR[\"create array\"]\n    D -->|\"true\"| ARR\n    D -->|\"false\"| F{\"manual_type\"}\n    F -->|\"array\"| ARR\n    F -->|\"object\"| ERR[\"throw type_error.301\"]

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

    1. The empty initializer list is written as {} which is exactly an empty JSON object.
    2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object.
    3. In all other cases, the initializer list could not be interpreted as a JSON object type, so interpreting it as a JSON array type is safe.

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

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

    Brace initialization yields arrays

    Because this constructor takes an initializer_list_t, brace-initializing a json/ordered_json from another json value wraps it in a single-element array rather than copying it:

    json j1 = \"hello\";\njson j2{j1};   // [!] j2 is [\"hello\"], NOT a copy of j1\njson j3(j1);   // j3 is \"hello\" -- parentheses copy as expected\n

    See the FAQ entry on brace initialization for the full explanation, an opt-in macro to change this behavior, and how to explicitly create a single-element array (json::array({value})) if that is what you want.

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

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

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

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

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

a type such that:

BasicJsonType:

a type such that:

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

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

The following code shows the constructor for different value_t values.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create the different JSON values with default values\n    json j_null(json::value_t::null);\n    json j_boolean(json::value_t::boolean);\n    json j_number_integer(json::value_t::number_integer);\n    json j_number_float(json::value_t::number_float);\n    json j_object(json::value_t::object);\n    json j_array(json::value_t::array);\n    json j_string(json::value_t::string);\n\n    // serialize the JSON values\n    std::cout << j_null << '\\n';\n    std::cout << j_boolean << '\\n';\n    std::cout << j_number_integer << '\\n';\n    std::cout << j_number_float << '\\n';\n    std::cout << j_object << '\\n';\n    std::cout << j_array << '\\n';\n    std::cout << j_string << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // implicitly create a JSON null value\n    json j1;\n\n    // explicitly create a JSON null value\n    json j2(nullptr);\n\n    // serialize the JSON null value\n    std::cout << j1 << '\\n' << j2 << '\\n';\n}\n

Output:

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

The following code shows the constructor with several compatible types.

#include <iostream>\n#include <deque>\n#include <list>\n#include <forward_list>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <valarray>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // ============\n    // object types\n    // ============\n\n    // create an object from an object_t value\n    json::object_t object_value = { {\"one\", 1}, {\"two\", 2} };\n    json j_object_t(object_value);\n\n    // create an object from std::map\n    std::map<std::string, int> c_map\n    {\n        {\"one\", 1}, {\"two\", 2}, {\"three\", 3}\n    };\n    json j_map(c_map);\n\n    // create an object from std::unordered_map\n    std::unordered_map<const char*, double> c_umap\n    {\n        {\"one\", 1.2}, {\"two\", 2.3}, {\"three\", 3.4}\n    };\n    json j_umap(c_umap);\n\n    // create an object from std::multimap\n    std::multimap<std::string, bool> c_mmap\n    {\n        {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", true}\n    };\n    json j_mmap(c_mmap); // only one entry for key \"three\" is used\n\n    // create an object from std::unordered_multimap\n    std::unordered_multimap<std::string, bool> c_ummap\n    {\n        {\"one\", true}, {\"two\", true}, {\"three\", false}, {\"three\", false}\n    };\n    json j_ummap(c_ummap); // only one entry for key \"three\" is used\n\n    // serialize the JSON objects\n    std::cout << j_object_t << '\\n';\n    std::cout << j_map << '\\n';\n    std::cout << j_umap << '\\n';\n    std::cout << j_mmap << '\\n';\n    std::cout << j_ummap << \"\\n\\n\";\n\n    // ===========\n    // array types\n    // ===========\n\n    // create an array from an array_t value\n    json::array_t array_value = {\"one\", \"two\", 3, 4.5, false};\n    json j_array_t(array_value);\n\n    // create an array from std::vector\n    std::vector<int> c_vector {1, 2, 3, 4};\n    json j_vec(c_vector);\n\n    // create an array from std::valarray\n    std::valarray<short> c_valarray {10, 9, 8, 7};\n    json j_valarray(c_valarray);\n\n    // create an array from std::deque\n    std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};\n    json j_deque(c_deque);\n\n    // create an array from std::list\n    std::list<bool> c_list {true, true, false, true};\n    json j_list(c_list);\n\n    // create an array from std::forward_list\n    std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};\n    json j_flist(c_flist);\n\n    // create an array from std::array\n    std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};\n    json j_array(c_array);\n\n    // create an array from std::set\n    std::set<std::string> c_set {\"one\", \"two\", \"three\", \"four\", \"one\"};\n    json j_set(c_set); // only one entry for \"one\" is used\n\n    // create an array from std::unordered_set\n    std::unordered_set<std::string> c_uset {\"one\", \"one\"};\n    json j_uset(c_uset); // only one entry for \"one\" is used\n\n    // create an array from std::multiset\n    std::multiset<std::string> c_mset {\"one\", \"two\", \"one\", \"four\"};\n    json j_mset(c_mset); // both entries for \"one\" are used\n\n    // create an array from std::unordered_multiset\n    std::unordered_multiset<std::string> c_umset {\"one\", \"one\"};\n    json j_umset(c_umset); // both entries for \"one\" are used\n\n    // serialize the JSON arrays\n    std::cout << j_array_t << '\\n';\n    std::cout << j_vec << '\\n';\n    std::cout << j_valarray << '\\n';\n    std::cout << j_deque << '\\n';\n    std::cout << j_list << '\\n';\n    std::cout << j_flist << '\\n';\n    std::cout << j_array << '\\n';\n    std::cout << j_set << '\\n';\n    std::cout << j_uset << '\\n';\n    std::cout << j_mset << '\\n';\n    std::cout << j_umset << \"\\n\\n\";\n\n    // ============\n    // string types\n    // ============\n\n    // create string from a string_t value\n    json::string_t string_value = \"The quick brown fox jumps over the lazy dog.\";\n    json j_string_t(string_value);\n\n    // create a JSON string directly from a string literal\n    json j_string_literal(\"The quick brown fox jumps over the lazy dog.\");\n\n    // create string from std::string\n    std::string s_stdstring = \"The quick brown fox jumps over the lazy dog.\";\n    json j_stdstring(s_stdstring);\n\n    // serialize the JSON strings\n    std::cout << j_string_t << '\\n';\n    std::cout << j_string_literal << '\\n';\n    std::cout << j_stdstring << \"\\n\\n\";\n\n    // ============\n    // number types\n    // ============\n\n    // create a JSON number from number_integer_t\n    json::number_integer_t value_integer_t = -42;\n    json j_integer_t(value_integer_t);\n\n    // create a JSON number from number_unsigned_t\n    json::number_integer_t value_unsigned_t = 17;\n    json j_unsigned_t(value_unsigned_t);\n\n    // create a JSON number from an anonymous enum\n    enum { enum_value = 17 };\n    json j_enum(enum_value);\n\n    // create values of different integer types\n    short n_short = 42;\n    int n_int = -23;\n    long n_long = 1024;\n    int_least32_t n_int_least32_t = -17;\n    uint8_t n_uint8_t = 8;\n\n    // create (integer) JSON numbers\n    json j_short(n_short);\n    json j_int(n_int);\n    json j_long(n_long);\n    json j_int_least32_t(n_int_least32_t);\n    json j_uint8_t(n_uint8_t);\n\n    // create values of different floating-point types\n    json::number_float_t v_ok = 3.141592653589793;\n    json::number_float_t v_nan = NAN;\n    json::number_float_t v_infinity = INFINITY;\n\n    // create values of different floating-point types\n    float n_float = 42.23;\n    float n_float_nan = 1.0f / 0.0f;\n    double n_double = 23.42;\n\n    // create (floating point) JSON numbers\n    json j_ok(v_ok);\n    json j_nan(v_nan);\n    json j_infinity(v_infinity);\n    json j_float(n_float);\n    json j_float_nan(n_float_nan);\n    json j_double(n_double);\n\n    // serialize the JSON numbers\n    std::cout << j_integer_t << '\\n';\n    std::cout << j_unsigned_t << '\\n';\n    std::cout << j_enum << '\\n';\n    std::cout << j_short << '\\n';\n    std::cout << j_int << '\\n';\n    std::cout << j_long << '\\n';\n    std::cout << j_int_least32_t << '\\n';\n    std::cout << j_uint8_t << '\\n';\n    std::cout << j_ok << '\\n';\n    std::cout << j_nan << '\\n';\n    std::cout << j_infinity << '\\n';\n    std::cout << j_float << '\\n';\n    std::cout << j_float_nan << '\\n';\n    std::cout << j_double << \"\\n\\n\";\n\n    // =============\n    // boolean types\n    // =============\n\n    // create boolean values\n    json j_truth = true;\n    json j_falsity = false;\n\n    // serialize the JSON booleans\n    std::cout << j_truth << '\\n';\n    std::cout << j_falsity << '\\n';\n}\n

Output:

{\"one\":1,\"two\":2}\n{\"one\":1,\"three\":3,\"two\":2}\n{\"one\":1.2,\"three\":3.4,\"two\":2.3}\n{\"one\":true,\"three\":false,\"two\":true}\n{\"one\":true,\"three\":false,\"two\":true}\n\n[\"one\",\"two\",3,4.5,false]\n[1,2,3,4]\n[10,9,8,7]\n[1.2,2.3,3.4,5.6]\n[true,true,false,true]\n[12345678909876,23456789098765,34567890987654,45678909876543]\n[1,2,3,4]\n[\"four\",\"one\",\"three\",\"two\"]\n[\"one\"]\n[\"four\",\"one\",\"one\",\"two\"]\n[\"one\",\"one\"]\n\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\"The quick brown fox jumps over the lazy dog.\"\n\n-42\n17\n17\n42\n-23\n1024\n-17\n8\n3.141592653589793\nnull\nnull\n42.22999954223633\nnull\n23.42\n\ntrue\nfalse\n

Note the output is platform-dependent.

Example: (4) create a JSON value from another basic_json specialization

The example below shows how a json value is converted to an ordered_json value and back using the converting constructor. Note how the original insertion order of oj is not restored, because it was already given up when converting to json, whose object_t sorts by key.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing ordered_json = nlohmann::ordered_json;\n\nint main()\n{\n    // create an ordered_json value; insertion order is preserved\n    ordered_json oj = {{\"c\", 3}, {\"a\", 1}, {\"b\", 2}};\n\n    // convert to json -- overload (4) is used; keys end up sorted\n    json j(oj);\n\n    // convert back to ordered_json -- the original insertion order is lost,\n    // because it was already given up when converting to json\n    ordered_json oj2(j);\n\n    std::cout << oj << '\\n';\n    std::cout << j << '\\n';\n    std::cout << oj2 << '\\n';\n}\n

Output:

{\"c\":3,\"a\":1,\"b\":2}\n{\"a\":1,\"b\":2,\"c\":3}\n{\"a\":1,\"b\":2,\"c\":3}\n
Example: (5) create a container (array or object) from an initializer list

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_empty_init_list = json({});\n    json j_object = { {\"one\", 1}, {\"two\", 2} };\n    json j_array = {1, 2, 3, 4};\n    json j_nested_object = { {\"one\", {1}}, {\"two\", {1, 2}} };\n    json j_nested_array = { {{1}, \"one\"}, {{1, 2}, \"two\"} };\n\n    // serialize the JSON value\n    std::cout << j_empty_init_list << '\\n';\n    std::cout << j_object << '\\n';\n    std::cout << j_array << '\\n';\n    std::cout << j_nested_object << '\\n';\n    std::cout << j_nested_array << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array by creating copies of a JSON value\n    json value = \"Hello\";\n    json array_0 = json(0, value);\n    json array_1 = json(1, value);\n    json array_5 = json(5, value);\n\n    // serialize the JSON arrays\n    std::cout << array_0 << '\\n';\n    std::cout << array_1 << '\\n';\n    std::cout << array_5 << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_array = {\"alpha\", \"bravo\", \"charly\", \"delta\", \"easy\"};\n    json j_number = 42;\n    json j_object = {{\"one\", \"eins\"}, {\"two\", \"zwei\"}};\n\n    // create copies using iterators\n    json j_array_range(j_array.begin() + 1, j_array.end() - 2);\n    json j_number_range(j_number.begin(), j_number.end());\n    json j_object_range(j_object.begin(), j_object.find(\"two\"));\n\n    // serialize the values\n    std::cout << j_array_range << '\\n';\n    std::cout << j_number_range << '\\n';\n    std::cout << j_object_range << '\\n';\n\n    // example for an exception\n    try\n    {\n        json j_invalid(j_number.begin() + 1, j_number.end());\n    }\n    catch (const json::invalid_iterator& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

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

The following code shows an example for the copy constructor.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON array\n    json j1 = {\"one\", \"two\", 3, 4.5, false};\n\n    // create a copy\n    json j2(j1);\n\n    // serialize the JSON array\n    std::cout << j1 << \" = \" << j2 << '\\n';\n    std::cout << std::boolalpha << (j1 == j2) << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON value\n    json a = 23;\n\n    // move contents of a to b\n    json b(std::move(a));\n\n    // serialize the JSON arrays\n    std::cout << a << '\\n';\n    std::cout << b << '\\n';\n}\n

Output:

null\n23\n
"},{"location":"api/basic_json/basic_json/#see-also","title":"See also","text":""},{"location":"api/basic_json/basic_json/#version-history","title":"Version history","text":"
  1. Since version 1.0.0.
  2. Since version 1.0.0.
  3. Since version 2.1.0.
  4. Since version 3.2.0. Explicit for different string types if JSON_USE_IMPLICIT_CONVERSIONS is 0 since version 3.13.0 unreleased.
  5. Since version 1.0.0.
  6. Since version 1.0.0.
  7. Since version 1.0.0. Fixed in version 3.13.0 unreleased to also check the iterator range for binary values; before, a range that did not cover the whole value (such as (end(), end())) was accepted and the whole binary value was copied, unlike the other primitive types.
  8. Since version 1.0.0.
  9. Since version 1.0.0.
"},{"location":"api/basic_json/begin/","title":"nlohmann::basic_json::begin","text":"
iterator begin() noexcept;\nconst_iterator begin() const noexcept;\n

Returns an iterator to the first element.

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

iterator to the first element

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

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

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

Constant.

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

The following code shows an example for begin().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array value\n    json array = {1, 2, 3, 4, 5};\n\n    // get an iterator to the first element\n    json::iterator it = array.begin();\n\n    // serialize the element that the iterator points to\n    std::cout << *it << '\\n';\n}\n

Output:

1\n
"},{"location":"api/basic_json/begin/#see-also","title":"See also","text":""},{"location":"api/basic_json/begin/#version-history","title":"Version history","text":""},{"location":"api/basic_json/binary/","title":"nlohmann::basic_json::binary","text":"
// (1)\nstatic basic_json binary(const typename binary_t::container_type& init);\nstatic basic_json binary(typename binary_t::container_type&& init);\n\n// (2)\nstatic basic_json binary(const typename binary_t::container_type& init,\n                         typename binary_t::subtype_type subtype);\nstatic basic_json binary(typename binary_t::container_type&& init,\n                         typename binary_t::subtype_type subtype);\n
  1. Creates a JSON binary array value from a given binary container.
  2. Creates a JSON binary array value from a given binary container with subtype.

Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.

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

JSON binary array value

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

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

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

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

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

Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a std::vector. Because JSON binary arrays are a non-standard extension, it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.

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

The following code shows how to create a binary value.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a binary vector\n    std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};\n\n    // create a binary JSON value with subtype 42\n    json j = json::binary(vec, 42);\n\n    // output type and subtype\n    std::cout << \"type: \" << j.type_name() << \", subtype: \" << j.get_binary().subtype() << std::endl;\n}\n

Output:

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

This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.

Additionally, as an implementation detail, the subtype of the binary data is carried around as a std::uint64_t, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to BinaryType via the helper type byte_container_with_subtype.

CBOR's RFC 8949 describes this type as:

Major type 2: A byte string. The number of bytes in the string is equal to the argument.

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

Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.

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

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

None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.

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

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

container type to store arrays

Although not formally expressed as a C++ concept, BinaryType must be default-constructible, copy/move-constructible, and support push_back(), .data(), and .size(), because byte_container_with_subtype derives directly from it. Its value_type must additionally be exactly one byte wide (e.g., std::uint8_t/char/std::byte): the binary serializers (CBOR, MessagePack, BSON, UBJSON) read and write the container's raw bytes via reinterpret_cast, which is only correct for byte-sized elements -- a container like std::vector<std::intptr_t> will not work as BinaryType. The elements must be stored contiguously, and the binary readers additionally require resize() and operator[]. See Template Parameter Requirements for the full list.

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

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

"},{"location":"api/basic_json/binary_t/#supported-byte-types","title":"Supported byte types","text":"

std::vector<std::uint8_t>, std::vector<char>, and std::vector<std::byte> are supported. Regardless of which of them is configured, dump writes the bytes as the numbers 0..255.

"},{"location":"api/basic_json/binary_t/#custom-binarytype-behavior","title":"Custom BinaryType behavior","text":"

When a custom BinaryType is configured (other than the default std::vector<std::uint8_t>), you can assign values of that type directly to a basic_json instance, and they will automatically be recognized as binary values rather than arrays:

using custom_json = nlohmann::basic_json<\n    nlohmann::ordered_map,  // ObjectType\n    std::vector,            // ArrayType\n    std::string,            // StringType\n    bool,                   // BooleanType\n    std::int64_t,           // NumberIntegerType\n    std::uint64_t,          // NumberUnsignedType\n    double,                 // NumberFloatType\n    std::allocator,         // AllocatorType\n    nlohmann::adl_serializer,\n    std::vector<std::byte>  // Custom BinaryType\n>;\n\nstd::vector<std::byte> data{std::byte{1}, std::byte{2}, std::byte{3}};\ncustom_json j = data;  // Creates a binary value, not an array\nassert(j.is_binary());\n\n// Round-tripping works seamlessly\nauto extracted = j.get<std::vector<std::byte>>();\nassert(extracted == data);\n

This automatic type detection is a convenience feature that only applies to custom (non-default) BinaryType configurations. The default nlohmann::json continues to treat std::vector<std::uint8_t> as arrays for backward compatibility.

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

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

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    std::cout << std::boolalpha << std::is_same<nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>, json::binary_t>::value << std::endl;\n}\n

Output:

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

The type used to store JSON booleans.

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

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

"},{"location":"api/basic_json/boolean_t/#template-parameters","title":"Template parameters","text":"BooleanType the type to store booleans. As it is stored directly inside a basic_json value (in a union), it must be a trivially default-constructible, trivially copyable, and trivially destructible type that is convertible to and from bool. See Template Parameter Requirements."},{"location":"api/basic_json/boolean_t/#notes","title":"Notes","text":""},{"location":"api/basic_json/boolean_t/#default-type","title":"Default type","text":"

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

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

Boolean values are stored directly inside a basic_json type.

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    std::cout << std::boolalpha << std::is_same<bool, json::boolean_t>::value << std::endl;\n}\n

Output:

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

Returns an iterator to the first element.

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

iterator to the first element

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

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

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

Constant.

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

The following code shows an example for cbegin().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array value\n    const json array = {1, 2, 3, 4, 5};\n\n    // get an iterator to the first element\n    json::const_iterator it = array.cbegin();\n\n    // serialize the element that the iterator points to\n    std::cout << *it << '\\n';\n}\n

Output:

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

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

error throw a parse_error exception in case of a tag ignore ignore tags store store tagged byte strings (for bytes 0xd8..0xdb) as binary values with the tag as subtype; other tagged values are read as if the tag were ignored. If several tags precede a byte string, only the innermost one is stored."},{"location":"api/basic_json/cbor_tag_handler_t/#examples","title":"Examples","text":"Example

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // tagged byte string\n    std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};\n\n    // cbor_tag_handler_t::error throws\n    try\n    {\n        auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);\n    }\n    catch (const json::parse_error& e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n\n    // cbor_tag_handler_t::ignore ignores the tag\n    auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);\n    std::cout << b_ignore_tag << std::endl;\n\n    // cbor_tag_handler_t::store stores the tag as binary subtype\n    auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);\n    std::cout << b_store_tag << std::endl;\n}\n

Output:

[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xD8\n{\"bytes\":[202,254,186,190],\"subtype\":null}\n{\"bytes\":[202,254,186,190],\"subtype\":66}\n
"},{"location":"api/basic_json/cbor_tag_handler_t/#see-also","title":"See also","text":""},{"location":"api/basic_json/cbor_tag_handler_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/cend/","title":"nlohmann::basic_json::cend","text":"
const_iterator cend() const noexcept;\n

Returns an iterator to one past the last element.

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

iterator one past the last element

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

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

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

Constant.

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

The following code shows an example for cend().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array value\n    json array = {1, 2, 3, 4, 5};\n\n    // get an iterator to one past the last element\n    json::const_iterator it = array.cend();\n\n    // decrement the iterator to point to the last element\n    --it;\n\n    // serialize the element that the iterator points to\n    std::cout << *it << '\\n';\n}\n

Output:

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

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

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

Has the same effect as calling

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

No-throw guarantee: this function never throws exceptions.

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

Linear in the size of the JSON value.

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

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

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_null;\n    json j_boolean = true;\n    json j_number_integer = 17;\n    json j_number_float = 23.42;\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_array = {1, 2, 4, 8, 16};\n    json j_string = \"Hello, world\";\n\n    // call clear()\n    j_null.clear();\n    j_boolean.clear();\n    j_number_integer.clear();\n    j_number_float.clear();\n    j_object.clear();\n    j_array.clear();\n    j_string.clear();\n\n    // serialize the cleared values()\n    std::cout << j_null << '\\n';\n    std::cout << j_boolean << '\\n';\n    std::cout << j_number_integer << '\\n';\n    std::cout << j_number_float << '\\n';\n    std::cout << j_object << '\\n';\n    std::cout << j_array << '\\n';\n    std::cout << j_string << '\\n';\n}\n

Output:

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

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

"},{"location":"api/basic_json/contains/#exceptions","title":"Exceptions","text":"
  1. The function does not throw exceptions.
  2. The function does not throw exceptions.
  3. The function does not throw exceptions.
"},{"location":"api/basic_json/contains/#complexity","title":"Complexity","text":"

Logarithmic in the size of the JSON object.

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

Postconditions

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

Deprecation

Overload (3) also accepts a json_pointer whose template argument is a basic_json specialization (e.g., nlohmann::json_pointer<nlohmann::json>) instead of a string type. This is deprecated since version 3.11.0 and will be removed in a future major version; use basic_json::json_pointer (for json, nlohmann::json_pointer<std::string>) instead.

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

See the migration guide for how to update existing code.

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

The example shows how contains() is used.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    // create some JSON values\n    json j_object = R\"( {\"key\": \"value\"} )\"_json;\n    json j_array = R\"( [1, 2, 3] )\"_json;\n\n    // call contains\n    std::cout << std::boolalpha <<\n              \"j_object contains 'key': \" << j_object.contains(\"key\") << '\\n' <<\n              \"j_object contains 'another': \" << j_object.contains(\"another\") << '\\n' <<\n              \"j_array contains 'key': \" << j_array.contains(\"key\") << std::endl;\n}\n

Output:

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

The example shows how contains() is used.

#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    // create some JSON values\n    json j_object = R\"( {\"key\": \"value\"} )\"_json;\n    json j_array = R\"( [1, 2, 3] )\"_json;\n\n    // call contains\n    std::cout << std::boolalpha <<\n              \"j_object contains 'key': \" << j_object.contains(\"key\"sv) << '\\n' <<\n              \"j_object contains 'another': \" << j_object.contains(\"another\"sv) << '\\n' <<\n              \"j_array contains 'key': \" << j_array.contains(\"key\"sv) << std::endl;\n}\n

Output:

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

The example shows how contains() is used.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    // create a JSON value\n    json j =\n    {\n        {\"number\", 1}, {\"string\", \"foo\"}, {\"array\", {1, 2}}\n    };\n\n    std::cout << std::boolalpha\n              << j.contains(\"/number\"_json_pointer) << '\\n'\n              << j.contains(\"/string\"_json_pointer) << '\\n'\n              << j.contains(\"/array\"_json_pointer) << '\\n'\n              << j.contains(\"/array/1\"_json_pointer) << '\\n'\n              << j.contains(\"/array/-\"_json_pointer) << '\\n'\n              << j.contains(\"/array/4\"_json_pointer) << '\\n'\n              << j.contains(\"/baz\"_json_pointer) << std::endl;\n\n    try\n    {\n        // try to use an array index with leading '0'\n        j.contains(\"/array/01\"_json_pointer);\n    }\n    catch (const json::parse_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n\n    try\n    {\n        // try to use an array index that is not a number\n        j.contains(\"/array/one\"_json_pointer);\n    }\n    catch (const json::parse_error& e)\n    {\n        std::cout << e.what() << '\\n';\n    }\n}\n

Output:

true\ntrue\ntrue\ntrue\nfalse\nfalse\nfalse\n
"},{"location":"api/basic_json/contains/#see-also","title":"See also","text":""},{"location":"api/basic_json/contains/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 3.6.0. Extended template KeyType to support comparable types in version 3.11.0. Fixed in version 3.13.0 unreleased to consistently accept std::string_view-convertible keys, as already supported by operator[], at, value, and other lookup functions.
  3. Added in version 3.7.0.
  4. Deleted overloads for integral key types added in version 3.13.0 unreleased to reject such calls at compile time instead of causing undefined behavior at runtime.
"},{"location":"api/basic_json/count/","title":"nlohmann::basic_json::count","text":"
// (1)\nsize_type count(const typename object_t::key_type& key) const;\n\n// (2)\ntemplate<typename KeyType>\nsize_type count(KeyType&& key) const;\n
  1. Returns the number of elements with key key. If ObjectType is the default std::map type, the return value will always be 0 (key was not found) or 1 (key was found).
  2. See 1. This overload is only available if KeyType is comparable with typename object_t::key_type and typename object_comparator_t::is_transparent denotes a type.
"},{"location":"api/basic_json/count/#template-parameters","title":"Template parameters","text":"KeyType A type for an object key other than json_pointer that is comparable with string_t using object_comparator_t. This can also be a string view (C++17)."},{"location":"api/basic_json/count/#parameters","title":"Parameters","text":"key (in) key value of the element to count."},{"location":"api/basic_json/count/#return-value","title":"Return value","text":"

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

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

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

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

Logarithmic in the size of the JSON object.

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

The example shows how count() is used.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n    // call count()\n    auto count_two = j_object.count(\"two\");\n    auto count_three = j_object.count(\"three\");\n\n    // print values\n    std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n    std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n

Output:

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

The example shows how count() is used.

#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n    // call count()\n    auto count_two = j_object.count(\"two\"sv);\n    auto count_three = j_object.count(\"three\"sv);\n\n    // print values\n    std::cout << \"number of elements with key \\\"two\\\": \" << count_two << '\\n';\n    std::cout << \"number of elements with key \\\"three\\\": \" << count_three << '\\n';\n}\n

Output:

number of elements with key \"two\": 1\nnumber of elements with key \"three\": 0\n
"},{"location":"api/basic_json/count/#see-also","title":"See also","text":""},{"location":"api/basic_json/count/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 1.0.0. Changed parameter key type to KeyType&& in version 3.11.0. Fixed in version 3.13.0 unreleased to consistently accept std::string_view-convertible keys, as already supported by operator[], at, value, and other lookup functions.
  3. Deleted overload for integral key types added in version 3.13.0 unreleased to reject such calls at compile time instead of causing undefined behavior at runtime.
"},{"location":"api/basic_json/crbegin/","title":"nlohmann::basic_json::crbegin","text":"
const_reverse_iterator crbegin() const noexcept;\n

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

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

reverse iterator to the last element

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

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

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

Constant.

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

The following code shows an example for crbegin().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array value\n    json array = {1, 2, 3, 4, 5};\n\n    // get an iterator to the reverse-beginning\n    json::const_reverse_iterator it = array.crbegin();\n\n    // serialize the element that the iterator points to\n    std::cout << *it << '\\n';\n}\n

Output:

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

Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.

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

reverse iterator to the element following the last element

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

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

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

Constant.

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

The following code shows an example for crend().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array value\n    json array = {1, 2, 3, 4, 5};\n\n    // get an iterator to the reverse-end\n    json::const_reverse_iterator it = array.crend();\n\n    // increment the iterator to point to the first element\n    --it;\n\n    // serialize the element that the iterator points to\n    std::cout << *it << '\\n';\n}\n

Output:

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

The default comparator used by object_t.

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

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

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

The example below demonstrates the default comparator.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    std::cout << std::boolalpha\n              << \"one < two : \" << json::default_object_comparator_t{}(\"one\", \"two\") << \"\\n\"\n              << \"three < four : \" << json::default_object_comparator_t{}(\"three\", \"four\") << std::endl;\n}\n

Output:

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

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

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

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

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

a JSON patch to convert the source to target

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

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

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

Linear in the lengths of source and target.

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

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

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n    // the source document\n    json source = R\"(\n        {\n            \"baz\": \"qux\",\n            \"foo\": \"bar\"\n        }\n    )\"_json;\n\n    // the target document\n    json target = R\"(\n        {\n            \"baz\": \"boo\",\n            \"hello\": [\n                \"world\"\n            ]\n        }\n    )\"_json;\n\n    // create the patch\n    json patch = json::diff(source, target);\n\n    // roundtrip\n    json patched_source = source.patch(patch);\n\n    // output patch and roundtrip result\n    std::cout << std::setw(4) << patch << \"\\n\\n\"\n              << std::setw(4) << patched_source << std::endl;\n}\n

Output:

[\n    {\n        \"op\": \"replace\",\n        \"path\": \"/baz\",\n        \"value\": \"boo\"\n    },\n    {\n        \"op\": \"remove\",\n        \"path\": \"/foo\"\n    },\n    {\n        \"op\": \"add\",\n        \"path\": \"/hello\",\n        \"value\": [\n            \"world\"\n        ]\n    }\n]\n\n{\n    \"baz\": \"boo\",\n    \"hello\": [\n        \"world\"\n    ]\n}\n
"},{"location":"api/basic_json/diff/#see-also","title":"See also","text":""},{"location":"api/basic_json/diff/#version-history","title":"Version history","text":""},{"location":"api/basic_json/dump/","title":"nlohmann::basic_json::dump","text":"
string_t dump(const int indent = -1,\n              const char indent_char = ' ',\n              const bool ensure_ascii = false,\n              const error_handler_t error_handler = error_handler_t::strict) const;\n

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

"},{"location":"api/basic_json/dump/#parameters","title":"Parameters","text":"indent (in) If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation. indent_char (in) The character to use for indentation if indent is greater than 0. The default is (space). ensure_ascii (in) If ensure_ascii is true, all non-ASCII characters in the output are escaped with \\uXXXX sequences, and the result consists of ASCII characters only. error_handler (in) how to react on decoding errors; there are four possible values (see error_handler_t: strict (throws an exception in case a decoding error occurs; default), replace (replace invalid UTF-8 sequences with U+FFFD), ignore (ignore invalid UTF-8 sequences during serialization; all valid bytes are copied to the output unchanged, and invalid bytes are dropped), and keep (write the ill-formed bytes to the output as is, without escaping them, even if ensure_ascii is true; the result is then not valid UTF-8, but equals the input bytes exactly, and well-formed characters around the ill-formed bytes are still escaped as usual))."},{"location":"api/basic_json/dump/#return-value","title":"Return value","text":"

string containing the serialization of the JSON value

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

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

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

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

Serializing untrusted input

When serializing values that may contain invalid or untrusted UTF-8 (e.g., bytes taken directly from network input), dump() throws type_error.316 in the default strict mode. To serialize such data without throwing, pass error_handler_t::replace (substitutes U+FFFD) or error_handler_t::ignore. Callers that serialize untrusted input on a crash-sensitive path should either choose a non-strict error handler or wrap dump() in a try/catch.

See the FAQ for details.

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

Linear.

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

Binary values are serialized as an object containing two keys:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_array = {1, 2, 4, 8, 16};\n    json j_string = \"Hell\u00f6 \ud83d\ude00!\";\n\n    // call dump()\n    std::cout << \"objects:\" << '\\n'\n              << j_object.dump() << \"\\n\\n\"\n              << j_object.dump(-1) << \"\\n\\n\"\n              << j_object.dump(0) << \"\\n\\n\"\n              << j_object.dump(4) << \"\\n\\n\"\n              << j_object.dump(1, '\\t') << \"\\n\\n\";\n\n    std::cout << \"arrays:\" << '\\n'\n              << j_array.dump() << \"\\n\\n\"\n              << j_array.dump(-1) << \"\\n\\n\"\n              << j_array.dump(0) << \"\\n\\n\"\n              << j_array.dump(4) << \"\\n\\n\"\n              << j_array.dump(1, '\\t') << \"\\n\\n\";\n\n    std::cout << \"strings:\" << '\\n'\n              << j_string.dump() << '\\n'\n              << j_string.dump(-1, ' ', true) << '\\n';\n\n    // create JSON value with invalid UTF-8 byte sequence\n    json j_invalid = \"\u00e4\\xA9\u00fc\";\n    try\n    {\n        std::cout << j_invalid.dump() << std::endl;\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n\n    std::cout << \"string with replaced invalid characters: \"\n              << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n              << \"\\nstring with ignored invalid characters: \"\n              << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n              << '\\n';\n}\n

Output:

objects:\n{\"one\":1,\"two\":2}\n\n{\"one\":1,\"two\":2}\n\n{\n\"one\": 1,\n\"two\": 2\n}\n\n{\n    \"one\": 1,\n    \"two\": 2\n}\n\n{\n    \"one\": 1,\n    \"two\": 2\n}\n\narrays:\n[1,2,4,8,16]\n\n[1,2,4,8,16]\n\n[\n1,\n2,\n4,\n8,\n16\n]\n\n[\n    1,\n    2,\n    4,\n    8,\n    16\n]\n\n[\n    1,\n    2,\n    4,\n    8,\n    16\n]\n\nstrings:\n\"Hell\u00f6 \ud83d\ude00!\"\n\"Hell\\u00f6 \\ud83d\\ude00!\"\n[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\n
"},{"location":"api/basic_json/dump/#see-also","title":"See also","text":""},{"location":"api/basic_json/dump/#version-history","title":"Version history","text":""},{"location":"api/basic_json/emplace/","title":"nlohmann::basic_json::emplace","text":"
template<class... Args>\nstd::pair<iterator, bool> emplace(Args&& ... args);\n

Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.

"},{"location":"api/basic_json/emplace/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace/#iterator-invalidation","title":"Iterator invalidation","text":"

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

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

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

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

Strong guarantee: if an exception is thrown, there are no changes to any JSON value. As an exception, a null value is converted to an empty object before the element is added and keeps that type if adding the element throws.

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

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

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

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

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

The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json object = {{\"one\", 1}, {\"two\", 2}};\n    json null;\n\n    // print values\n    std::cout << object << '\\n';\n    std::cout << null << '\\n';\n\n    // add values\n    auto res1 = object.emplace(\"three\", 3);\n    null.emplace(\"A\", \"a\");\n    null.emplace(\"B\", \"b\");\n\n    // the following call will not add an object, because there is already\n    // a value stored at key \"B\"\n    auto res2 = null.emplace(\"B\", \"c\");\n\n    // print values\n    std::cout << object << '\\n';\n    std::cout << *res1.first << \" \" << std::boolalpha << res1.second << '\\n';\n\n    std::cout << null << '\\n';\n    std::cout << *res2.first << \" \" << std::boolalpha << res2.second << '\\n';\n}\n

Output:

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

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

"},{"location":"api/basic_json/emplace_back/#template-parameters","title":"Template parameters","text":"Args compatible types to create a basic_json object"},{"location":"api/basic_json/emplace_back/#iterator-invalidation","title":"Iterator invalidation","text":"

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

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

reference to the inserted element

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

Strong guarantee: if an exception is thrown, there are no changes to any JSON value. As an exception, a null value is converted to an empty array before the element is added and keeps that type if adding the element throws.

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

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

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

Amortized constant.

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json array = {1, 2, 3, 4, 5};\n    json null;\n\n    // print values\n    std::cout << array << '\\n';\n    std::cout << null << '\\n';\n\n    // add values\n    array.emplace_back(6);\n    null.emplace_back(\"first\");\n    null.emplace_back(3, \"second\");\n\n    // print values\n    std::cout << array << '\\n';\n    std::cout << null << '\\n';\n}\n

Output:

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

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

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

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

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

No-throw guarantee: this function never throws exceptions.

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

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

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

This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is false in the case of a string.

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_null;\n    json j_boolean = true;\n    json j_number_integer = 17;\n    json j_number_float = 23.42;\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_object_empty(json::value_t::object);\n    json j_array = {1, 2, 4, 8, 16};\n    json j_array_empty(json::value_t::array);\n    json j_string = \"Hello, world\";\n\n    // call empty()\n    std::cout << std::boolalpha;\n    std::cout << j_null.empty() << '\\n';\n    std::cout << j_boolean.empty() << '\\n';\n    std::cout << j_number_integer.empty() << '\\n';\n    std::cout << j_number_float.empty() << '\\n';\n    std::cout << j_object.empty() << '\\n';\n    std::cout << j_object_empty.empty() << '\\n';\n    std::cout << j_array.empty() << '\\n';\n    std::cout << j_array_empty.empty() << '\\n';\n    std::cout << j_string.empty() << '\\n';\n}\n

Output:

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

Returns an iterator to one past the last element.

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

iterator one past the last element

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

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

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

Constant.

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

The following code shows an example for end().

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create an array value\n    json array = {1, 2, 3, 4, 5};\n\n    // get an iterator to one past the last element\n    json::iterator it = array.end();\n\n    // decrement the iterator to point to the last element\n    --it;\n\n    // serialize the element that the iterator points to\n    std::cout << *it << '\\n';\n}\n

Output:

5\n
"},{"location":"api/basic_json/end/#see-also","title":"See also","text":""},{"location":"api/basic_json/end/#version-history","title":"Version history","text":""},{"location":"api/basic_json/end_pos/","title":"nlohmann::basic_json::end_pos","text":"
#if JSON_DIAGNOSTIC_POSITIONS\nconstexpr std::size_t end_pos() const noexcept;\n#endif\n

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

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

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

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

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

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

Constant.

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

Note

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

Invalidation

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

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

Output:

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

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

"},{"location":"api/basic_json/end_pos/#see-also","title":"See also","text":""},{"location":"api/basic_json/end_pos/#version-history","title":"Version history","text":""},{"location":"api/basic_json/erase/","title":"nlohmann::basic_json::erase","text":"
// (1)\niterator erase(iterator pos);\nconst_iterator erase(const_iterator pos);\n\n// (2)\niterator erase(iterator first, iterator last);\nconst_iterator erase(const_iterator first, const_iterator last);\n\n// (3)\nsize_type erase(const typename object_t::key_type& key);\n\n// (4)\ntemplate<typename KeyType>\nsize_type erase(KeyType&& key);\n\n// (5)\nvoid erase(const size_type idx);\n
  1. Removes an element from a JSON value specified by iterator pos. The iterator pos must be valid and dereferenceable. Thus, the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

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

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

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

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

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

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

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

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

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_boolean = true;\n    json j_number_integer = 17;\n    json j_number_float = 23.42;\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_array = {1, 2, 4, 8, 16};\n    json j_string = \"Hello, world\";\n\n    // call erase()\n    j_boolean.erase(j_boolean.begin());\n    j_number_integer.erase(j_number_integer.begin());\n    j_number_float.erase(j_number_float.begin());\n    j_object.erase(j_object.find(\"two\"));\n    j_array.erase(j_array.begin() + 2);\n    j_string.erase(j_string.begin());\n\n    // print values\n    std::cout << j_boolean << '\\n';\n    std::cout << j_number_integer << '\\n';\n    std::cout << j_number_float << '\\n';\n    std::cout << j_object << '\\n';\n    std::cout << j_array << '\\n';\n    std::cout << j_string << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON values\n    json j_boolean = true;\n    json j_number_integer = 17;\n    json j_number_float = 23.42;\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n    json j_array = {1, 2, 4, 8, 16};\n    json j_string = \"Hello, world\";\n\n    // call erase()\n    j_boolean.erase(j_boolean.begin(), j_boolean.end());\n    j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());\n    j_number_float.erase(j_number_float.begin(), j_number_float.end());\n    j_object.erase(j_object.find(\"two\"), j_object.end());\n    j_array.erase(j_array.begin() + 1, j_array.begin() + 3);\n    j_string.erase(j_string.begin(), j_string.end());\n\n    // print values\n    std::cout << j_boolean << '\\n';\n    std::cout << j_number_integer << '\\n';\n    std::cout << j_number_float << '\\n';\n    std::cout << j_object << '\\n';\n    std::cout << j_array << '\\n';\n    std::cout << j_string << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n    // call erase()\n    auto count_one = j_object.erase(\"one\");\n    auto count_three = j_object.erase(\"three\");\n\n    // print values\n    std::cout << j_object << '\\n';\n    std::cout << count_one << \" \" << count_three << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n    // call erase()\n    auto count_one = j_object.erase(\"one\"sv);\n    auto count_three = j_object.erase(\"three\"sv);\n\n    // print values\n    std::cout << j_object << '\\n';\n    std::cout << count_one << \" \" << count_three << '\\n';\n}\n

Output:

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON array\n    json j_array = {0, 1, 2, 3, 4, 5};\n\n    // call erase()\n    j_array.erase(2);\n\n    // print values\n    std::cout << j_array << '\\n';\n}\n

Output:

[0,1,3,4,5]\n
"},{"location":"api/basic_json/erase/#see-also","title":"See also","text":""},{"location":"api/basic_json/erase/#version-history","title":"Version history","text":"
  1. Added in version 1.0.0. Added support for binary types in version 3.8.0.
  2. Added in version 1.0.0. Added support for binary types in version 3.8.0.
  3. Added in version 1.0.0.
  4. Added in version 3.11.0. Fixed in version 3.13.0 unreleased to consistently accept std::string_view-convertible keys, as already supported by operator[], at, value, and other lookup functions.
  5. Added in version 1.0.0.
"},{"location":"api/basic_json/error_handler_t/","title":"nlohmann::basic_json::error_handler_t","text":"
enum class error_handler_t {\n    strict,\n    replace,\n    ignore,\n    keep\n};\n

This enumeration is used to choose how to treat ill-formed UTF-8 in a string value or object key:

Four values are differentiated:

strict throw a type_error/parse_error exception in case of invalid UTF-8 replace replace invalid UTF-8 sequences with U+FFFD (\ufffd REPLACEMENT CHARACTER) ignore ignore invalid UTF-8 sequences; all valid bytes are copied to the output unchanged, and invalid bytes are dropped keep keep invalid UTF-8 sequences unchanged; only meaningful for the binary formats mentioned above, since [dump] (dump.md) itself must produce text, and keep there writes the ill-formed bytes to the output as is, so the result is then not valid UTF-8 (but still equals the input bytes exactly, including around any well-formed characters, which are still escaped as usual)"},{"location":"api/basic_json/error_handler_t/#examples","title":"Examples","text":"Example

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON value with invalid UTF-8 byte sequence\n    json j_invalid = \"\u00e4\\xA9\u00fc\";\n    try\n    {\n        std::cout << j_invalid.dump() << std::endl;\n    }\n    catch (const json::type_error& e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n\n    std::cout << \"string with replaced invalid characters: \"\n              << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n              << \"\\nstring with ignored invalid characters: \"\n              << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n              << \"\\nstring with the invalid byte kept as is (\" << j_invalid.dump(-1, ' ', false, json::error_handler_t::keep).size()\n              << \" bytes, not valid UTF-8 itself)\\n\";\n}\n

Output:

[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9\nstring with replaced invalid characters: \"\u00e4\ufffd\u00fc\"\nstring with ignored invalid characters: \"\u00e4\u00fc\"\nstring with the invalid byte kept as is (7 bytes, not valid UTF-8 itself)\n
"},{"location":"api/basic_json/error_handler_t/#see-also","title":"See also","text":""},{"location":"api/basic_json/error_handler_t/#version-history","title":"Version history","text":""},{"location":"api/basic_json/exception/","title":"nlohmann::basic_json::exception","text":"
class exception : public std::exception;\n

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

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

Subclasses:

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

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

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

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

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    try\n    {\n        // calling at() for a non-existing key\n        json j = {{\"foo\", \"bar\"}};\n        json k = j.at(\"non-existing\");\n    }\n    catch (const json::exception& e)\n    {\n        // output exception information\n        std::cout << \"message: \" << e.what() << '\\n'\n                  << \"exception id: \" << e.id << std::endl;\n    }\n}\n

Output:

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

List of exceptions

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

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

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

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

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

Logarithmic in the size of the JSON object.

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

The example shows how find() is used.

#include <iostream>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n    // call find\n    auto it_two = j_object.find(\"two\");\n    auto it_three = j_object.find(\"three\");\n\n    // print values\n    std::cout << std::boolalpha;\n    std::cout << \"\\\"two\\\" was found: \" << (it_two != j_object.end()) << '\\n';\n    std::cout << \"value at key \\\"two\\\": \" << *it_two << '\\n';\n    std::cout << \"\\\"three\\\" was found: \" << (it_three != j_object.end()) << '\\n';\n}\n

Output:

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

The example shows how find() is used.

#include <iostream>\n#include <string_view>\n#include <nlohmann/json.hpp>\n\nusing namespace std::string_view_literals;\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON object\n    json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n    // call find\n    auto it_two = j_object.find(\"two\"sv);\n    auto it_three = j_object.find(\"three\"sv);\n\n    // print values\n    std::cout << std::boolalpha;\n    std::cout << \"\\\"two\\\" was found: \" << (it_two != j_object.end()) << '\\n';\n    std::cout << \"value at key \\\"two\\\": \" << *it_two << '\\n';\n    std::cout << \"\\\"three\\\" was found: \" << (it_three != j_object.end()) << '\\n';\n}\n

Output:

\"two\" was found: true\nvalue at key \"two\": 2\n\"three\" was found: false\n
"},{"location":"api/basic_json/find/#see-also","title":"See also","text":""},{"location":"api/basic_json/find/#version-history","title":"Version history","text":"
  1. Added in version 3.11.0.
  2. Added in version 1.0.0. Changed to support comparable types in version 3.11.0. Fixed in version 3.13.0 unreleased to consistently accept std::string_view-convertible keys, as already supported by operator[], at, value, and other lookup functions.
  3. Deleted overloads for integral key types added in version 3.13.0 unreleased to reject such calls at compile time instead of causing undefined behavior at runtime.
"},{"location":"api/basic_json/flatten/","title":"nlohmann::basic_json::flatten","text":"
basic_json flatten() const;\n

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

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

an object that maps JSON pointers to primitive values

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

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

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

Linear in the size of the JSON value.

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

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

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

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

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create JSON value\n    json j =\n    {\n        {\"pi\", 3.141},\n        {\"happy\", true},\n        {\"name\", \"Niels\"},\n        {\"nothing\", nullptr},\n        {\n            \"answer\", {\n                {\"everything\", 42}\n            }\n        },\n        {\"list\", {1, 0, 2}},\n        {\n            \"object\", {\n                {\"currency\", \"USD\"},\n                {\"value\", 42.99}\n            }\n        }\n    };\n\n    // call flatten()\n    std::cout << std::setw(4) << j.flatten() << '\\n';\n}\n

Output:

{\n    \"/answer/everything\": 42,\n    \"/happy\": true,\n    \"/list/0\": 1,\n    \"/list/1\": 0,\n    \"/list/2\": 2,\n    \"/name\": \"Niels\",\n    \"/nothing\": null,\n    \"/object/currency\": \"USD\",\n    \"/object/value\": 42.99,\n    \"/pi\": 3.141\n}\n
Example: empty objects and arrays are flattened to null

The following code shows that an empty object and an empty array are both flattened to null, and that unflatten() restores them as null rather than as empty containers.

#include <iostream>\n#include <iomanip>\n#include <nlohmann/json.hpp>\n\nusing json = nlohmann::json;\n\nint main()\n{\n    // create a JSON value with an empty object and an empty array\n    json j =\n    {\n        {\"empty_object\", json::object()},\n        {\"empty_array\", json::array()},\n        {\"name\", \"Niels\"}\n    };\n\n    // call flatten()\n    json flattened = j.flatten();\n    std::cout << std::setw(4) << flattened << \"\\n\\n\";\n\n    // the empty containers cannot be restored by unflatten()\n    std::cout << std::setw(4) << flattened.unflatten() << '\\n';\n}\n

Output:

{\n    \"/empty_array\": null,\n    \"/empty_object\": null,\n    \"/name\": \"Niels\"\n}\n\n{\n    \"empty_array\": null,\n    \"empty_object\": null,\n    \"name\": \"Niels\"\n}\n
"},{"location":"api/basic_json/flatten/#see-also","title":"See also","text":""},{"location":"api/basic_json/flatten/#version-history","title":"Version history","text":""},{"location":"api/basic_json/format_as/","title":"format_as(basic_json)","text":"
template <typename BasicJsonType>\nstd::string format_as(const BasicJsonType& j);\n

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

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

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

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

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

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

Throws type_error.316 if a string stored inside the JSON value is not UTF-8 encoded

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

Linear.

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

Version-dependent effect on fmt

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

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

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

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

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

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

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

Output:

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