This commit is contained in:
nlohmann
2026-07-08 18:19:46 +00:00
parent 9a231845c2
commit 279d757031
758 changed files with 56489 additions and 503 deletions
+3
View File
@@ -0,0 +1,3 @@
# JSON for Modern C++
![](images/json.gif)
+35
View File
@@ -0,0 +1,35 @@
# <small>nlohmann::</small>adl_serializer
```cpp
template<typename, typename>
struct adl_serializer;
```
Serializer that uses ADL ([Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)) to choose
`to_json`/`from_json` functions from the types' namespaces.
It is implemented similarly to
```cpp
template<typename ValueType>
struct adl_serializer {
template<typename BasicJsonType>
static void to_json(BasicJsonType& j, const T& value) {
// calls the "to_json" method in T's namespace
}
template<typename BasicJsonType>
static void from_json(const BasicJsonType& j, T& value) {
// same thing, but with the "from_json" method
}
};
```
## Member functions
- [**from_json**](from_json.md) - convert a JSON value to any value type
- [**to_json**](to_json.md) - convert any value type to a JSON value
## Version history
- Added in version 2.1.0.
+74
View File
@@ -0,0 +1,74 @@
# <small>nlohmann::adl_serializer::</small>from_json
```cpp
// (1)
template<typename BasicJsonType, typename TargetType = ValueType>
static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
// (2)
template<typename BasicJsonType, typename TargetType = ValueType>
static auto from_json(BasicJsonType && j) noexcept(
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
```
This function is usually called by the [`get()`](../basic_json/get.md) function of the [basic_json](../basic_json/index.md)
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.
## Parameters
`j` (in)
: JSON value to read from
`val` (out)
: value to write to
## Return value
1. (none) -- the converted value is written to the output parameter `val`.
2. the JSON value `j` converted to `TargetType`
## Examples
??? example "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.
```cpp
--8<-- "examples/from_json__default_constructible.cpp"
```
Output:
```json
--8<-- "examples/from_json__default_constructible.output"
```
??? example "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.
```cpp
--8<-- "examples/from_json__non_default_constructible.cpp"
```
Output:
```json
--8<-- "examples/from_json__non_default_constructible.output"
```
## See also
- [to_json](to_json.md)
## Version history
- Added in version 2.1.0.
File diff suppressed because one or more lines are too long
+157
View File
@@ -0,0 +1,157 @@
# nlohmann::adl_serializer::from_json
```
// (1)
template<typename BasicJsonType, typename TargetType = ValueType>
static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
// (2)
template<typename BasicJsonType, typename TargetType = ValueType>
static auto from_json(BasicJsonType && j) noexcept(
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
```
This function is usually called by the [`get()`](https://json.nlohmann.me/api/basic_json/get/index.md) function of the [basic_json](https://json.nlohmann.me/api/basic_json/index.md) class (either explicitly or via the conversion operators).
1. This function is chosen for default-constructible value types.
1. This function is chosen for value types which are not default-constructible.
## Parameters
`j` (in) : JSON value to read from
`val` (out) : value to write to
## Return value
1. (none) -- the converted value is written to the output parameter `val`.
1. the JSON value `j` converted to `TargetType`
## Examples
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace ns
{
// a simple struct to model a person
struct person
{
std::string name;
std::string address;
int age;
};
} // namespace ns
namespace ns
{
void from_json(const json& j, person& p)
{
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
} // namespace ns
int main()
{
json j;
j["name"] = "Ned Flanders";
j["address"] = "744 Evergreen Terrace";
j["age"] = 60;
auto p = j.get<ns::person>();
std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
}
```
Output:
```
Ned Flanders (60) lives in 744 Evergreen Terrace
```
Example: (2) Non-default-constructible type
The example below shows how a `from_json` is implemented as part of a specialization of the `adl_serializer` to realize the conversion of a non-default-constructible type.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace ns
{
// a simple struct to model a person (not default constructible)
struct person
{
person(std::string n, std::string a, int aa)
: name(std::move(n)), address(std::move(a)), age(aa)
{}
std::string name;
std::string address;
int age;
};
} // namespace ns
namespace nlohmann
{
template <>
struct adl_serializer<ns::person>
{
static ns::person from_json(const json& j)
{
return {j.at("name"), j.at("address"), j.at("age")};
}
// Here's the catch! You must provide a to_json method! Otherwise, you
// will not be able to convert person to json, since you fully
// specialized adl_serializer on that type
static void to_json(json& j, ns::person p)
{
j["name"] = p.name;
j["address"] = p.address;
j["age"] = p.age;
}
};
} // namespace nlohmann
int main()
{
json j;
j["name"] = "Ned Flanders";
j["address"] = "744 Evergreen Terrace";
j["age"] = 60;
auto p = j.get<ns::person>();
std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
}
```
Output:
```
Ned Flanders (60) lives in 744 Evergreen Terrace
```
## See also
- [to_json](https://json.nlohmann.me/api/adl_serializer/to_json/index.md)
## Version history
- Added in version 2.1.0.
File diff suppressed because one or more lines are too long
+34
View File
@@ -0,0 +1,34 @@
# nlohmann::adl_serializer
```
template<typename, typename>
struct adl_serializer;
```
Serializer that uses ADL ([Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)) to choose `to_json`/`from_json` functions from the types' namespaces.
It is implemented similarly to
```
template<typename ValueType>
struct adl_serializer {
template<typename BasicJsonType>
static void to_json(BasicJsonType& j, const T& value) {
// calls the "to_json" method in T's namespace
}
template<typename BasicJsonType>
static void from_json(const BasicJsonType& j, T& value) {
// same thing, but with the "from_json" method
}
};
```
## Member functions
- [**from_json**](https://json.nlohmann.me/api/adl_serializer/from_json/index.md) - convert a JSON value to any value type
- [**to_json**](https://json.nlohmann.me/api/adl_serializer/to_json/index.md) - convert any value type to a JSON value
## Version history
- Added in version 2.1.0.
+43
View File
@@ -0,0 +1,43 @@
# <small>nlohmann::adl_serializer::</small>to_json
```cpp
template<typename BasicJsonType, typename TargetType = ValueType>
static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
```
This function is usually called by the constructors of the [basic_json](../basic_json/index.md) class.
## Parameters
`j` (out)
: JSON value to write to
`val` (in)
: value to read from
## Examples
??? 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.
```cpp
--8<-- "examples/to_json.cpp"
```
Output:
```json
--8<-- "examples/to_json.output"
```
## See also
- [from_json](from_json.md)
## Version history
- Added in version 2.1.0.
File diff suppressed because one or more lines are too long
+71
View File
@@ -0,0 +1,71 @@
# nlohmann::adl_serializer::to_json
```
template<typename BasicJsonType, typename TargetType = ValueType>
static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
```
This function is usually called by the constructors of the [basic_json](https://json.nlohmann.me/api/basic_json/index.md) class.
## Parameters
`j` (out) : JSON value to write to
`val` (in) : value to read from
## Examples
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace ns
{
// a simple struct to model a person
struct person
{
std::string name;
std::string address;
int age;
};
} // namespace ns
namespace ns
{
void to_json(json& j, const person& p)
{
j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
}
} // namespace ns
int main()
{
ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
json j = p;
std::cout << j << std::endl;
}
```
Output:
```
{"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
```
## See also
- [from_json](https://json.nlohmann.me/api/adl_serializer/from_json/index.md)
## Version history
- Added in version 2.1.0.
+338
View File
@@ -0,0 +1,338 @@
# <small>nlohmann::</small>basic_json
<small>Defined in header `<nlohmann/json.hpp>`</small>
```cpp
template<
template<typename U, typename V, typename... Args> class ObjectType = std::map,
template<typename U, typename... Args> class ArrayType = std::vector,
class StringType = std::string,
class BooleanType = bool,
class NumberIntegerType = std::int64_t,
class NumberUnsignedType = std::uint64_t,
class NumberFloatType = double,
template<typename U> class AllocatorType = std::allocator,
template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,
class BinaryType = std::vector<std::uint8_t>,
class CustomBaseClass = void
>
class basic_json;
```
## Template parameters
| Template parameter | Description | Derived type |
|----------------------|---------------------------------------------------------------------------|---------------------------------------------|
| `ObjectType` | type for JSON objects | [`object_t`](object_t.md) |
| `ArrayType` | type for JSON arrays | [`array_t`](array_t.md) |
| `StringType` | type for JSON strings and object keys | [`string_t`](string_t.md) |
| `BooleanType` | type for JSON booleans | [`boolean_t`](boolean_t.md) |
| `NumberIntegerType` | type for JSON integer numbers | [`number_integer_t`](number_integer_t.md) |
| `NumberUnsignedType` | type for JSON unsigned integer numbers | [`number_unsigned_t`](number_unsigned_t.md) |
| `NumberFloatType` | type for JSON floating-point numbers | [`number_float_t`](number_float_t.md) |
| `AllocatorType` | type of the allocator to use | |
| `JSONSerializer` | the serializer to resolve internal calls to `to_json()` and `from_json()` | [`json_serializer`](json_serializer.md) |
| `BinaryType` | type for binary arrays | [`binary_t`](binary_t.md) |
| `CustomBaseClass` | extension point for user code | [`json_base_class_t`](json_base_class_t.md) |
## Specializations
- [**json**](../json.md) - default specialization
- [**ordered_json**](../ordered_json.md) - a specialization that maintains the insertion order of object keys
## Iterator invalidation
All operations that add values to an **array** ([`push_back`](push_back.md) , [`operator+=`](operator+=.md),
[`emplace_back`](emplace_back.md), [`insert`](insert.md), and [`operator[]`](operator%5B%5D.md) for a non-existing
index) can yield a reallocation, in which case all iterators (including the [`end()`](end.md) iterator) and all
references to the elements are invalidated.
For [`ordered_json`](../ordered_json.md), also all operations that add a value to an **object**
([`push_back`](push_back.md), [`operator+=`](operator+=.md), [`emplace`](emplace.md), [`insert`](insert.md),
[`update`](update.md), and [`operator[]`](operator%5B%5D.md) for a non-existing key) can yield a reallocation, in
which case all iterators (including the [`end()`](end.md) iterator) and all references to the elements are invalidated.
## Requirements
The class satisfies the following concept requirements:
### Basic
- [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): JSON values can be
default-constructed. The result will be a JSON null value.
- [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): A JSON value can be constructed
from an rvalue argument.
- [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): A JSON value can be
copy-constructed from an lvalue expression.
- [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): A JSON value can be assigned from an
rvalue argument.
- [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): A JSON value can be copy-assigned from
an lvalue expression.
- [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): JSON values can be destructed.
### Layout
- [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): JSON values have
[standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data
members are private and standard layout types, the class has no virtual functions or (virtual) base classes.
### Library-wide
- [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): JSON values can be compared with
`==`, see [`operator==`](operator_eq.md).
- [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): JSON values can be compared with
`<`, see [`operator<`](operator_le.md).
- [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): Any JSON lvalue or rvalue of can be swapped with
any lvalue or rvalue of other compatible types, using unqualified function `swap`.
- [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): JSON values can be compared against
`std::nullptr_t` objects which are used to model the `null` value.
### Container
- [Container](https://en.cppreference.com/w/cpp/named_req/Container): JSON values can be used like STL containers and
provide iterator access.
- [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer): JSON values can be used like
STL containers and provide reverse iterator access.
## Member types
- [**adl_serializer**](../adl_serializer/index.md) - the default serializer
- [**value_t**](value_t.md) - the JSON type enumeration
- [**json_pointer**](../json_pointer/index.md) - JSON Pointer implementation
- [**json_serializer**](json_serializer.md) - type of the serializer to for conversions from/to JSON
- [**error_handler_t**](error_handler_t.md) - type to choose behavior on decoding errors
- [**cbor_tag_handler_t**](cbor_tag_handler_t.md) - type to choose how to handle CBOR tags
- **initializer_list_t** - type for initializer lists of `basic_json` values
- [**input_format_t**](input_format_t.md) - type to choose the format to parse
- [**json_sax_t**](../json_sax/index.md) - type for SAX events
### Exceptions
- [**exception**](exception.md) - general exception of the `basic_json` class
- [**parse_error**](parse_error.md) - exception indicating a parse error
- [**invalid_iterator**](invalid_iterator.md) - exception indicating errors with iterators
- [**type_error**](type_error.md) - exception indicating executing a member function with a wrong type
- [**out_of_range**](out_of_range.md) - exception indicating access out of the defined range
- [**other_error**](other_error.md) - exception indicating other library errors
### Container types
| Type | Definition |
|--------------------------|-----------------------------------------------------------------------------------------------------------|
| `value_type` | `#!cpp basic_json` |
| `reference` | `#!cpp value_type&` |
| `const_reference` | `#!cpp const value_type&` |
| `difference_type` | `#!cpp std::ptrdiff_t` |
| `size_type` | `#!cpp std::size_t` |
| `allocator_type` | `#!cpp AllocatorType<basic_json>` |
| `pointer` | `#!cpp std::allocator_traits<allocator_type>::pointer` |
| `const_pointer` | `#!cpp std::allocator_traits<allocator_type>::const_pointer` |
| `iterator` | [LegacyBidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator) |
| `const_iterator` | constant [LegacyBidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator) |
| `reverse_iterator` | reverse iterator, derived from `iterator` |
| `const_reverse_iterator` | reverse iterator, derived from `const_iterator` |
| `iteration_proxy` | helper type for [`items`](items.md) function |
### JSON value data types
- [**array_t**](array_t.md) - type for arrays
- [**binary_t**](binary_t.md) - type for binary arrays
- [**boolean_t**](boolean_t.md) - type for booleans
- [**default_object_comparator_t**](default_object_comparator_t.md) - default comparator for objects
- [**number_float_t**](number_float_t.md) - type for numbers (floating-point)
- [**number_integer_t**](number_integer_t.md) - type for numbers (integer)
- [**number_unsigned_t**](number_unsigned_t.md) - type for numbers (unsigned)
- [**object_comparator_t**](object_comparator_t.md) - comparator for objects
- [**object_t**](object_t.md) - type for objects
- [**string_t**](string_t.md) - type for strings
### Parser callback
- [**parse_event_t**](parse_event_t.md) - parser event types
- [**parser_callback_t**](parser_callback_t.md) - per-element parser callback type
## Member functions
- [(constructor)](basic_json.md)
- [(destructor)](~basic_json.md)
- [**operator=**](operator=.md) - copy assignment
- [**array**](array.md) (_static_) - explicitly create an array
- [**binary**](binary.md) (_static_) - explicitly create a binary array
- [**object**](object.md) (_static_) - explicitly create an object
### Object inspection
Functions to inspect the type of a JSON value.
- [**type**](type.md) - return the type of the JSON value
- [**operator value_t**](operator_value_t.md) - return the type of the JSON value
- [**type_name**](type_name.md) - return the type as string
- [**is_primitive**](is_primitive.md) - return whether the type is primitive
- [**is_structured**](is_structured.md) - return whether the type is structured
- [**is_null**](is_null.md) - return whether the value is null
- [**is_boolean**](is_boolean.md) - return whether the value is a boolean
- [**is_number**](is_number.md) - return whether the value is a number
- [**is_number_integer**](is_number_integer.md) - return whether the value is an integer number
- [**is_number_unsigned**](is_number_unsigned.md) - return whether the value is an unsigned integer number
- [**is_number_float**](is_number_float.md) - return whether the value is a floating-point number
- [**is_object**](is_object.md) - return whether the value is an object
- [**is_array**](is_array.md) - return whether the value is an array
- [**is_string**](is_string.md) - return whether the value is a string
- [**is_binary**](is_binary.md) - return whether the value is a binary array
- [**is_discarded**](is_discarded.md) - return whether the value is discarded
Optional functions to access the [diagnostic positions](../macros/json_diagnostic_positions.md).
- [**start_pos**](start_pos.md) - return the start position of the value
- [**end_pos**](end_pos.md) - return the one past the end position of the value
### Value access
Direct access to the stored value of a JSON value.
- [**get**](get.md) - get a value
- [**get_to**](get_to.md) - get a value and write it to a destination
- [**get_ptr**](get_ptr.md) - get a pointer value
- [**get_ref**](get_ref.md) - get a reference value
- [**operator ValueType**](operator_ValueType.md) - get a value
- [**get_binary**](get_binary.md) - get a binary value
### Element access
Access to the JSON value
- [**at**](at.md) - access specified element with bounds checking
- [**operator[]**](operator[].md) - access specified element
- [**value**](value.md) - access specified object element with default value
- [**front**](front.md) - access the first element
- [**back**](back.md) - access the last element
### Lookup
- [**find**](find.md) - find an element in a JSON object
- [**count**](count.md) - returns the number of occurrences of a key in a JSON object
- [**contains**](contains.md) - check the existence of an element in a JSON object
### Iterators
- [**begin**](begin.md) - returns an iterator to the first element
- [**cbegin**](cbegin.md) - returns a const iterator to the first element
- [**end**](end.md) - returns an iterator to one past the last element
- [**cend**](cend.md) - returns a const iterator to one past the last element
- [**rbegin**](rbegin.md) - returns an iterator to the reverse-beginning
- [**rend**](rend.md) - returns an iterator to the reverse-end
- [**crbegin**](crbegin.md) - returns a const iterator to the reverse-beginning
- [**crend**](crend.md) - returns a const iterator to the reverse-end
- [**items**](items.md) - wrapper to access iterator member functions in range-based for
### Capacity
- [**empty**](empty.md) - checks whether the container is empty
- [**size**](size.md) - returns the number of elements
- [**max_size**](max_size.md) - returns the maximum possible number of elements
### Modifiers
- [**clear**](clear.md) - clears the contents
- [**push_back**](push_back.md) - add a value to an array/object
- [**operator+=**](operator+=.md) - add a value to an array/object
- [**emplace_back**](emplace_back.md) - add a value to an array
- [**emplace**](emplace.md) - add a value to an object if a key does not exist
- [**erase**](erase.md) - remove elements
- [**insert**](insert.md) - inserts elements
- [**update**](update.md) - updates a JSON object from another object, overwriting existing keys
- [**swap**](swap.md) - exchanges the values
### Lexicographical comparison operators
- [**operator==**](operator_eq.md) - comparison: equal
- [**operator!=**](operator_ne.md) - comparison: not equal
- [**operator<**](operator_lt.md) - comparison: less than
- [**operator>**](operator_gt.md) - comparison: greater than
- [**operator<=**](operator_le.md) - comparison: less than or equal
- [**operator>=**](operator_ge.md) - comparison: greater than or equal
- [**operator<=>**](operator_spaceship.md) - comparison: 3-way
### Serialization / Dumping
- [**dump**](dump.md) - serialization
### Deserialization / Parsing
- [**parse**](parse.md) (_static_) - deserialize from a compatible input
- [**accept**](accept.md) (_static_) - check if the input is valid JSON
- [**sax_parse**](sax_parse.md) (_static_) - generate SAX events
### JSON Pointer functions
- [**flatten**](flatten.md) - return flattened JSON value
- [**unflatten**](unflatten.md) - unflatten a previously flattened JSON value
### JSON Patch functions
- [**patch**](patch.md) - applies a JSON patch
- [**patch_inplace**](patch_inplace.md) - applies a JSON patch in place
- [**diff**](diff.md) (_static_) - creates a diff as a JSON patch
### JSON Merge Patch functions
- [**merge_patch**](merge_patch.md) - applies a JSON Merge Patch
## Static functions
- [**meta**](meta.md) - returns version information on the library
- [**get_allocator**](get_allocator.md) - returns the allocator associated with the container
### Binary formats
- [**from_bjdata**](from_bjdata.md) (_static_) - create a JSON value from an input in BJData format
- [**from_bson**](from_bson.md) (_static_) - create a JSON value from an input in BSON format
- [**from_cbor**](from_cbor.md) (_static_) - create a JSON value from an input in CBOR format
- [**from_msgpack**](from_msgpack.md) (_static_) - create a JSON value from an input in MessagePack format
- [**from_ubjson**](from_ubjson.md) (_static_) - create a JSON value from an input in UBJSON format
- [**to_bjdata**](to_bjdata.md) (_static_) - create a BJData serialization of a given JSON value
- [**to_bson**](to_bson.md) (_static_) - create a BSON serialization of a given JSON value
- [**to_cbor**](to_cbor.md) (_static_) - create a CBOR serialization of a given JSON value
- [**to_msgpack**](to_msgpack.md) (_static_) - create a MessagePack serialization of a given JSON value
- [**to_ubjson**](to_ubjson.md) (_static_) - create a UBJSON serialization of a given JSON value
## Non-member functions
- [**operator<<(std::ostream&)**](../operator_ltlt.md) - serialize to stream
- [**operator>>(std::istream&)**](../operator_gtgt.md) - deserialize from stream
- [**to_string**](to_string.md) - user-defined `to_string` function for JSON values
- [**format_as**](format_as.md) - user-defined `format_as` function for JSON values (fmt support)
## Literals
- [**operator""_json**](../operator_literal_json.md) - user-defined string literal for JSON values
## Helper classes
- [**std::formatter&lt;basic_json&gt;**](std_formatter.md) - make JSON values formattable with `std::format`
- [**std::hash&lt;basic_json&gt;**](std_hash.md) - return a hash value for a JSON object
- [**std::swap&lt;basic_json&gt;**](std_swap.md) - exchanges the values of two JSON objects
## Examples
??? example
The example shows how the library is used.
```cpp
--8<-- "examples/README.cpp"
```
Output:
```json
--8<-- "examples/README.output"
```
## See also
- [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc8259)
## Version history
- Added in version 1.0.0.
+121
View File
@@ -0,0 +1,121 @@
# <small>nlohmann::basic_json::</small>accept
```cpp
// (1)
template<typename InputType>
static bool accept(InputType&& i,
const bool ignore_comments = false,
const bool ignore_trailing_commas = false);
// (2)
template<typename IteratorType>
static bool accept(IteratorType first, IteratorType last,
const bool ignore_comments = false,
const bool ignore_trailing_commas = false);
```
Checks whether the input is valid JSON.
1. Reads from a compatible input.
2. Reads from a pair of character iterators
The value_type of the iterator must be an integral type with a size of 1, 2, or 4 bytes, which will be interpreted
respectively as UTF-8, UTF-16, and UTF-32.
Unlike the [`parse()`](parse.md) function, this function neither throws an exception in case of invalid JSON input
(i.e., a parse error) nor creates diagnostic information.
## Template parameters
`InputType`
: A compatible input, for instance:
- an `std::istream` object
- a `#!c FILE` pointer (throws if null)
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters (throws if null)
- a `std::string`
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators.
`IteratorType`
: a compatible iterator type, for instance.
- a pair of `std::string::iterator` or `std::vector<std::uint8_t>::iterator`
- a pair of pointers such as `ptr` and `ptr + len`
## Parameters
`i` (in)
: Input to parse from.
`ignore_comments` (in)
: whether comments should be ignored and treated like whitespace (`#!cpp true`) or yield a parse error
(`#!cpp false`); (optional, `#!cpp false` by default)
`ignore_trailing_commas` (in)
: whether trailing commas in arrays or objects should be ignored and treated like whitespace (`#!cpp true`) or yield a parse error
(`#!cpp false`); (optional, `#!cpp false` by default)
`first` (in)
: iterator to the start of the character range
`last` (in)
: iterator to the end of the character range
## Return value
Whether the input is valid JSON.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Exceptions
Throws [`parse_error.101`](../../home/exceptions.md#jsonexceptionparse_error101) in case of an empty input like a null `#!c FILE*` or `#!c char*` pointer.
## Complexity
Linear in the length of the input. The parser is a predictive LL(1) parser.
## Notes
A UTF-8 byte order mark is silently ignored.
## Examples
??? example
The example below demonstrates the `accept()` function reading from a string.
```cpp
--8<-- "examples/accept__string.cpp"
```
Output:
```json
--8<-- "examples/accept__string.output"
```
## See also
- [parse](parse.md) - deserialize from a compatible input
- [sax_parse](sax_parse.md) - parse input using the SAX interface
- [operator>>](../operator_gtgt.md) - deserialize from stream
## Version history
- Added in version 3.0.0.
- Ignoring comments via `ignore_comments` added in version 3.9.0.
- Changed [runtime assertion](../../features/assertions.md) in case of `FILE*` null pointers to exception in version 3.12.0.
- Added `ignore_trailing_commas` in version 3.12.x.
!!! warning "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
`#!cpp accept({ptr, ptr+len}, ...);` with `#!cpp accept(ptr, ptr+len, ...);`.
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
function.
File diff suppressed because one or more lines are too long
+137
View File
@@ -0,0 +1,137 @@
# nlohmann::basic_json::accept
```
// (1)
template<typename InputType>
static bool accept(InputType&& i,
const bool ignore_comments = false,
const bool ignore_trailing_commas = false);
// (2)
template<typename IteratorType>
static bool accept(IteratorType first, IteratorType last,
const bool ignore_comments = false,
const bool ignore_trailing_commas = false);
```
Checks whether the input is valid JSON.
1. Reads from a compatible input.
1. Reads from a pair of character iterators
The value_type of the iterator must be an integral type with a size of 1, 2, or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16, and UTF-32.
Unlike the [`parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md) function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.
## Template parameters
`InputType` : A compatible input, for instance:
```
- an `std::istream` object
- a `FILE` pointer (throws if null)
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters (throws if null)
- a `std::string`
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators.
```
`IteratorType` : a compatible iterator type, for instance.
```
- a pair of `std::string::iterator` or `std::vector<std::uint8_t>::iterator`
- a pair of pointers such as `ptr` and `ptr + len`
```
## Parameters
`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
## Return value
Whether the input is valid JSON.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Exceptions
Throws [`parse_error.101`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error101) in case of an empty input like a null `FILE*` or `char*` pointer.
## Complexity
Linear in the length of the input. The parser is a predictive LL(1) parser.
## Notes
A UTF-8 byte order mark is silently ignored.
## Examples
Example
The example below demonstrates the `accept()` function reading from a string.
```
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// a valid JSON text
auto valid_text = R"(
{
"numbers": [1, 2, 3]
}
)";
// an invalid JSON text
auto invalid_text = R"(
{
"strings": ["extra", "comma", ]
}
)";
std::cout << std::boolalpha
<< json::accept(valid_text) << ' '
<< json::accept(invalid_text) << '\n';
}
```
Output:
```
true false
```
## See also
- [parse](https://json.nlohmann.me/api/basic_json/parse/index.md) - deserialize from a compatible input
- [sax_parse](https://json.nlohmann.me/api/basic_json/sax_parse/index.md) - parse input using the SAX interface
- [operator>>](https://json.nlohmann.me/api/operator_gtgt/index.md) - deserialize from stream
## Version history
- Added in version 3.0.0.
- Ignoring comments via `ignore_comments` added in version 3.9.0.
- Changed [runtime assertion](https://json.nlohmann.me/features/assertions/index.md) in case of `FILE*` null pointers to exception in version 3.12.0.
- Added `ignore_trailing_commas` in version 3.12.x.
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.
+61
View File
@@ -0,0 +1,61 @@
# <small>nlohmann::basic_json::</small>array
```cpp
static basic_json array(initializer_list_t init = {});
```
Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON
value `#!json [a, b, c]`. If the initializer list is empty, the empty array `#!json []` is created.
## Parameters
`init` (in)
: initializer list with JSON values to create an array from (optional)
## Return value
JSON array value
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the size of `init`.
## Notes
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)`](basic_json.md)). 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
## Examples
??? example
The following code shows an example for the `array` function.
```cpp
--8<-- "examples/array.cpp"
```
Output:
```json
--8<-- "examples/array.output"
```
## See also
- [`basic_json(initializer_list_t)`](basic_json.md) - create a JSON value from an initializer list
- [`object`](object.md) - create a JSON object value from an initializer list
- [Creating JSON values](../../features/creating_values.md) - the article on creating JSON values
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+77
View File
@@ -0,0 +1,77 @@
# nlohmann::basic_json::array
```
static basic_json array(initializer_list_t init = {});
```
Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created.
## Parameters
`init` (in) : initializer list with JSON values to create an array from (optional)
## Return value
JSON array value
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the size of `init`.
## Notes
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)`](https://json.nlohmann.me/api/basic_json/basic_json/index.md)). 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
1. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
## Examples
Example
The following code shows an example for the `array` function.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON arrays
json j_no_init_list = json::array();
json j_empty_init_list = json::array({});
json j_nonempty_init_list = json::array({1, 2, 3, 4});
json j_list_of_pairs = json::array({ {"one", 1}, {"two", 2} });
// serialize the JSON arrays
std::cout << j_no_init_list << '\n';
std::cout << j_empty_init_list << '\n';
std::cout << j_nonempty_init_list << '\n';
std::cout << j_list_of_pairs << '\n';
}
```
Output:
```
[]
[]
[1,2,3,4]
[["one",1],["two",2]]
```
## See also
- [`basic_json(initializer_list_t)`](https://json.nlohmann.me/api/basic_json/basic_json/index.md) - create a JSON value from an initializer list
- [`object`](https://json.nlohmann.me/api/basic_json/object/index.md) - create a JSON object value from an initializer list
- [Creating JSON values](https://json.nlohmann.me/features/creating_values/index.md) - the article on creating JSON values
## Version history
- Added in version 1.0.0.
+68
View File
@@ -0,0 +1,68 @@
# <small>nlohmann::basic_json::</small>array_t
```cpp
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
```
The type used to store JSON arrays.
[RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
> An array is an ordered sequence of zero or more values.
To store objects in C++, a type is defined by the template parameters explained below.
## Template parameters
`ArrayType`
: container type to store arrays (e.g., `std::vector` or `std::list`)
`AllocatorType`
: the allocator to use for objects (e.g., `std::allocator`)
## Notes
#### Default type
With the default values for `ArrayType` (`std::vector`) and `AllocatorType` (`std::allocator`), the default value for
`array_t` is:
```cpp
std::vector<
basic_json, // value_type
std::allocator<basic_json> // allocator_type
>
```
#### Limits
[RFC 8259](https://tools.ietf.org/html/rfc8259) 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`](max_size.md) function of a JSON array.
#### Storage
Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of type
`#!cpp array_t*` must be dereferenced.
## Examples
??? example
The following code shows that `array_t` is by default, a typedef to `#!cpp std::vector<nlohmann::json>`.
```cpp
--8<-- "examples/array_t.cpp"
```
Output:
```json
--8<-- "examples/array_t.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+73
View File
@@ -0,0 +1,73 @@
# nlohmann::basic_json::array_t
```
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
```
The type used to store JSON arrays.
[RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
> An array is an ordered sequence of zero or more values.
To store objects in C++, a type is defined by the template parameters explained below.
## Template parameters
`ArrayType` : container type to store arrays (e.g., `std::vector` or `std::list`)
`AllocatorType` : the allocator to use for objects (e.g., `std::allocator`)
## Notes
#### Default type
With the default values for `ArrayType` (`std::vector`) and `AllocatorType` (`std::allocator`), the default value for `array_t` is:
```
std::vector<
basic_json, // value_type
std::allocator<basic_json> // allocator_type
>
```
#### Limits
[RFC 8259](https://tools.ietf.org/html/rfc8259) 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`](https://json.nlohmann.me/api/basic_json/max_size/index.md) function of a JSON array.
#### Storage
Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced.
## Examples
Example
The following code shows that `array_t` is by default, a typedef to `std::vector<nlohmann::json>`.
```
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << std::boolalpha << std::is_same<std::vector<json>, json::array_t>::value << std::endl;
}
```
Output:
```
true
```
## Version history
- Added in version 1.0.0.
+228
View File
@@ -0,0 +1,228 @@
# <small>nlohmann::basic_json::</small>at
```cpp
// (1)
reference at(size_type idx);
const_reference at(size_type idx) const;
// (2)
reference at(const typename object_t::key_type& key);
const_reference at(const typename object_t::key_type& key) const;
// (3)
template<typename KeyType>
reference at(KeyType&& key);
template<typename KeyType>
const_reference at(KeyType&& key) const;
// (4)
reference at(const json_pointer& ptr);
const_reference at(const json_pointer& ptr) const;
```
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 `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
4. Returns a reference to the element at specified JSON pointer `ptr`, with bounds checking.
## Template parameters
`KeyType`
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
This can also be a string view (C++17).
## Parameters
`idx` (in)
: index of the element to access
`key` (in)
: object key of the elements to access
`ptr` (in)
: JSON pointer to the desired element
## Return value
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`
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.304`](../../home/exceptions.md#jsonexceptiontype_error304) 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`](../../home/exceptions.md#jsonexceptionout_of_range401) 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`](../../home/exceptions.md#jsonexceptiontype_error304) 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`](../../home/exceptions.md#jsonexceptionout_of_range403) 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`](../../home/exceptions.md#jsonexceptionparse_error106) if an array index in the passed
JSON pointer `ptr` begins with '0'. See the example below.
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) if an array index in the passed
JSON pointer `ptr` is not a number. See the example below.
- Throws [`out_of_range.401`](../../home/exceptions.md#jsonexceptionout_of_range401) if an array index in the passed
JSON pointer `ptr` is out of range. See the example below.
- Throws [`out_of_range.402`](../../home/exceptions.md#jsonexceptionout_of_range402) 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`](../../home/exceptions.md#jsonexceptionout_of_range403) if the JSON pointer describes a
key of an object which cannot be found. See the example below.
- Throws [`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) if the JSON pointer `ptr` can
not be resolved. See the example below.
- Throws [`out_of_range.410`](../../home/exceptions.md#jsonexceptionout_of_range410) if an array index in the passed
JSON pointer `ptr` exceeds the range of `size_type` (e.g., on 32-bit platforms).
## Complexity
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.
## Examples
??? example "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.
```cpp
--8<-- "examples/at__size_type.cpp"
```
Output:
```json
--8<-- "examples/at__size_type.output"
```
??? example "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.
```cpp
--8<-- "examples/at__size_type_const.cpp"
```
Output:
```json
--8<-- "examples/at__size_type_const.output"
```
??? example "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.
```cpp
--8<-- "examples/at__object_t_key_type.cpp"
```
Output:
```json
--8<-- "examples/at__object_t_key_type.output"
```
??? example "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.
```cpp
--8<-- "examples/at__object_t_key_type_const.cpp"
```
Output:
```json
--8<-- "examples/at__object_t_key_type_const.output"
```
??? example "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.
```cpp
--8<-- "examples/at__keytype.c++17.cpp"
```
Output:
```json
--8<-- "examples/at__keytype.c++17.output"
```
??? example "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.
```cpp
--8<-- "examples/at__keytype_const.c++17.cpp"
```
Output:
```json
--8<-- "examples/at__keytype_const.c++17.output"
```
??? example "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.
```cpp
--8<-- "examples/at__json_pointer.cpp"
```
Output:
```json
--8<-- "examples/at__json_pointer.output"
```
??? example "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.
```cpp
--8<-- "examples/at__json_pointer_const.cpp"
```
Output:
```json
--8<-- "examples/at__json_pointer_const.output"
```
## See also
- documentation on [checked access](../../features/element_access/checked_access.md)
- [`operator[]`](operator%5B%5D.md) for unchecked access by reference
- [`value`](value.md) for access with default value
## Version history
1. Added in version 1.0.0.
2. Added in version 1.0.0.
3. Added in version 3.11.0.
4. Added in version 2.0.0.
File diff suppressed because one or more lines are too long
+668
View File
@@ -0,0 +1,668 @@
# nlohmann::basic_json::at
```
// (1)
reference at(size_type idx);
const_reference at(size_type idx) const;
// (2)
reference at(const typename object_t::key_type& key);
const_reference at(const typename object_t::key_type& key) const;
// (3)
template<typename KeyType>
reference at(KeyType&& key);
template<typename KeyType>
const_reference at(KeyType&& key) const;
// (4)
reference at(const json_pointer& ptr);
const_reference at(const json_pointer& ptr) const;
```
1. Returns a reference to the array element at specified location `idx`, with bounds checking.
1. Returns a reference to the object element with specified key `key`, with bounds checking.
1. 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.
1. Returns a reference to the element at specified JSON pointer `ptr`, with bounds checking.
## Template parameters
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
## Parameters
`idx` (in) : index of the element to access
`key` (in) : object key of the elements to access
`ptr` (in) : JSON pointer to the desired element
## Return value
1. reference to the element at index `idx`
1. reference to the element at key `key`
1. reference to the element at key `key`
1. reference to the element pointed to by `ptr`
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.304`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error304) 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`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) if the index `idx` is out of range of the array; that is, `idx >= size()`. See the example below.
1. The function can throw the following exceptions:
- Throws [`type_error.304`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error304) 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`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range403) if the key `key` is not stored in the object; that is, `find(key) == end()`. See the example below.
1. See 2.
1. The function can throw the following exceptions:
- Throws [`parse_error.106`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error106) if an array index in the passed JSON pointer `ptr` begins with '0'. See the example below.
- Throws [`parse_error.109`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error109) if an array index in the passed JSON pointer `ptr` is not a number. See the example below.
- Throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) if an array index in the passed JSON pointer `ptr` is out of range. See the example below.
- Throws [`out_of_range.402`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range402) 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`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range403) if the JSON pointer describes a key of an object which cannot be found. See the example below.
- Throws [`out_of_range.404`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range404) if the JSON pointer `ptr` can not be resolved. See the example below.
- Throws [`out_of_range.410`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range410) if an array index in the passed JSON pointer `ptr` exceeds the range of `size_type` (e.g., on 32-bit platforms).
## Complexity
1. Constant.
1. Logarithmic in the size of the container.
1. Logarithmic in the size of the container.
1. Logarithmic in the size of the container.
## Examples
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON array
json array = {"first", "2nd", "third", "fourth"};
// output element at index 2 (third element)
std::cout << array.at(2) << '\n';
// change element at index 1 (second element) to "second"
array.at(1) = "second";
// output changed array
std::cout << array << '\n';
// exception type_error.304
try
{
// use at() on a non-array type
json str = "I am a string";
str.at(0) = "Another string";
}
catch (const json::type_error& e)
{
std::cout << e.what() << '\n';
}
// exception out_of_range.401
try
{
// try to write beyond the array limit
array.at(5) = "sixth";
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
"third"
["first","second","third","fourth"]
[json.exception.type_error.304] cannot use at() with string
[json.exception.out_of_range.401] array index 5 is out of range
```
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON array
const json array = {"first", "2nd", "third", "fourth"};
// output element at index 2 (third element)
std::cout << array.at(2) << '\n';
// exception type_error.304
try
{
// use at() on a non-array type
const json str = "I am a string";
std::cout << str.at(0) << '\n';
}
catch (const json::type_error& e)
{
std::cout << e.what() << '\n';
}
// exception out_of_range.401
try
{
// try to read beyond the array limit
std::cout << array.at(5) << '\n';
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
"third"
[json.exception.type_error.304] cannot use at() with string
[json.exception.out_of_range.401] array index 5 is out of range
```
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON object
json object =
{
{"the good", "il buono"},
{"the bad", "il cattivo"},
{"the ugly", "il brutto"}
};
// output element with key "the ugly"
std::cout << object.at("the ugly") << '\n';
// change element with key "the bad"
object.at("the bad") = "il cattivo";
// output changed array
std::cout << object << '\n';
// exception type_error.304
try
{
// use at() on a non-object type
json str = "I am a string";
str.at("the good") = "Another string";
}
catch (const json::type_error& e)
{
std::cout << e.what() << '\n';
}
// exception out_of_range.401
try
{
// try to write at a nonexisting key
object.at("the fast") = "il rapido";
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
"il brutto"
{"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"}
[json.exception.type_error.304] cannot use at() with string
[json.exception.out_of_range.403] key 'the fast' not found
```
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON object
const json object =
{
{"the good", "il buono"},
{"the bad", "il cattivo"},
{"the ugly", "il brutto"}
};
// output element with key "the ugly"
std::cout << object.at("the ugly") << '\n';
// exception type_error.304
try
{
// use at() on a non-object type
const json str = "I am a string";
std::cout << str.at("the good") << '\n';
}
catch (const json::type_error& e)
{
std::cout << e.what() << '\n';
}
// exception out_of_range.401
try
{
// try to read from a nonexisting key
std::cout << object.at("the fast") << '\n';
}
catch (const json::out_of_range)
{
std::cout << "out of range" << '\n';
}
}
```
Output:
```
"il brutto"
[json.exception.type_error.304] cannot use at() with string
out of range
```
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>
#include <string_view>
#include <nlohmann/json.hpp>
using namespace std::string_view_literals;
using json = nlohmann::json;
int main()
{
// create JSON object
json object =
{
{"the good", "il buono"},
{"the bad", "il cattivo"},
{"the ugly", "il brutto"}
};
// output element with key "the ugly" using string_view
std::cout << object.at("the ugly"sv) << '\n';
// change element with key "the bad" using string_view
object.at("the bad"sv) = "il cattivo";
// output changed array
std::cout << object << '\n';
// exception type_error.304
try
{
// use at() with string_view on a non-object type
json str = "I am a string";
str.at("the good"sv) = "Another string";
}
catch (const json::type_error& e)
{
std::cout << e.what() << '\n';
}
// exception out_of_range.401
try
{
// try to write at a nonexisting key using string_view
object.at("the fast"sv) = "il rapido";
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
"il brutto"
{"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"}
[json.exception.type_error.304] cannot use at() with string
[json.exception.out_of_range.403] key 'the fast' not found
```
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>
#include <string_view>
#include <nlohmann/json.hpp>
using namespace std::string_view_literals;
using json = nlohmann::json;
int main()
{
// create JSON object
const json object =
{
{"the good", "il buono"},
{"the bad", "il cattivo"},
{"the ugly", "il brutto"}
};
// output element with key "the ugly" using string_view
std::cout << object.at("the ugly"sv) << '\n';
// exception type_error.304
try
{
// use at() with string_view on a non-object type
const json str = "I am a string";
std::cout << str.at("the good"sv) << '\n';
}
catch (const json::type_error& e)
{
std::cout << e.what() << '\n';
}
// exception out_of_range.401
try
{
// try to read from a nonexisting key using string_view
std::cout << object.at("the fast"sv) << '\n';
}
catch (const json::out_of_range& e)
{
std::cout << "out of range" << '\n';
}
}
```
Output:
```
"il brutto"
[json.exception.type_error.304] cannot use at() with string
out of range
```
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
// create a JSON value
json j =
{
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
};
// read-only access
// output element with JSON pointer "/number"
std::cout << j.at("/number"_json_pointer) << '\n';
// output element with JSON pointer "/string"
std::cout << j.at("/string"_json_pointer) << '\n';
// output element with JSON pointer "/array"
std::cout << j.at("/array"_json_pointer) << '\n';
// output element with JSON pointer "/array/1"
std::cout << j.at("/array/1"_json_pointer) << '\n';
// writing access
// change the string
j.at("/string"_json_pointer) = "bar";
// output the changed string
std::cout << j["string"] << '\n';
// change an array element
j.at("/array/1"_json_pointer) = 21;
// output the changed array
std::cout << j["array"] << '\n';
// out_of_range.106
try
{
// try to use an array index with leading '0'
json::reference ref = j.at("/array/01"_json_pointer);
}
catch (const json::parse_error& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.109
try
{
// try to use an array index that is not a number
json::reference ref = j.at("/array/one"_json_pointer);
}
catch (const json::parse_error& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.401
try
{
// try to use an invalid array index
json::reference ref = j.at("/array/4"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.402
try
{
// try to use the array index '-'
json::reference ref = j.at("/array/-"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.403
try
{
// try to use a JSON pointer to a nonexistent object key
json::const_reference ref = j.at("/foo"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.404
try
{
// try to use a JSON pointer that cannot be resolved
json::reference ref = j.at("/number/foo"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
1
"foo"
[1,2]
2
"bar"
[1,21]
[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'
[json.exception.parse_error.109] parse error: array index 'one' is not a number
[json.exception.out_of_range.401] array index 4 is out of range
[json.exception.out_of_range.402] array index '-' (2) is out of range
[json.exception.out_of_range.403] key 'foo' not found
[json.exception.out_of_range.404] unresolved reference token 'foo'
```
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
// create a JSON value
const json j =
{
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
};
// read-only access
// output element with JSON pointer "/number"
std::cout << j.at("/number"_json_pointer) << '\n';
// output element with JSON pointer "/string"
std::cout << j.at("/string"_json_pointer) << '\n';
// output element with JSON pointer "/array"
std::cout << j.at("/array"_json_pointer) << '\n';
// output element with JSON pointer "/array/1"
std::cout << j.at("/array/1"_json_pointer) << '\n';
// out_of_range.109
try
{
// try to use an array index that is not a number
json::const_reference ref = j.at("/array/one"_json_pointer);
}
catch (const json::parse_error& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.401
try
{
// try to use an invalid array index
json::const_reference ref = j.at("/array/4"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.402
try
{
// try to use the array index '-'
json::const_reference ref = j.at("/array/-"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.403
try
{
// try to use a JSON pointer to a nonexistent object key
json::const_reference ref = j.at("/foo"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.404
try
{
// try to use a JSON pointer that cannot be resolved
json::const_reference ref = j.at("/number/foo"_json_pointer);
}
catch (const json::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
1
"foo"
[1,2]
2
[json.exception.parse_error.109] parse error: array index 'one' is not a number
[json.exception.out_of_range.401] array index 4 is out of range
[json.exception.out_of_range.402] array index '-' (2) is out of range
[json.exception.out_of_range.403] key 'foo' not found
[json.exception.out_of_range.404] unresolved reference token 'foo'
```
## See also
- documentation on [checked access](https://json.nlohmann.me/features/element_access/checked_access/index.md)
- [`operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) for unchecked access by reference
- [`value`](https://json.nlohmann.me/api/basic_json/value/index.md) for access with default value
## Version history
1. Added in version 1.0.0.
1. Added in version 1.0.0.
1. Added in version 3.11.0.
1. Added in version 2.0.0.
+65
View File
@@ -0,0 +1,65 @@
# <small>nlohmann::basic_json::</small>back
```cpp
reference back();
const_reference back() const;
```
Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is
equivalent to
```cpp
auto tmp = c.end();
--tmp;
return *tmp;
```
## Return value
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.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Exceptions
If the JSON value is `#!json null`, exception
[`invalid_iterator.214`](../../home/exceptions.md#jsonexceptioninvalid_iterator214) is thrown.
## Complexity
Constant.
## Notes
!!! info "Precondition"
The array or object must not be empty. Calling `back` on an empty array or object yields undefined behavior.
## Examples
??? example
The following code shows an example for `back()`.
```cpp
--8<-- "examples/back.cpp"
```
Output:
```json
--8<-- "examples/back.output"
```
## See also
- [front](front.md) to access the first element
## Version history
- Added in version 1.0.0.
- Adjusted code to return reference to binary values in version 3.8.0.
File diff suppressed because one or more lines are too long
+105
View File
@@ -0,0 +1,105 @@
# nlohmann::basic_json::back
```
reference back();
const_reference back() const;
```
Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to
```
auto tmp = c.end();
--tmp;
return *tmp;
```
## Return value
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.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Exceptions
If the JSON value is `null`, exception [`invalid_iterator.214`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator214) is thrown.
## Complexity
Constant.
## Notes
Precondition
The array or object must not be empty. Calling `back` on an empty array or object yields undefined behavior.
## Examples
Example
The following code shows an example for `back()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_boolean = true;
json j_number_integer = 17;
json j_number_float = 23.42;
json j_object = {{"one", 1}, {"two", 2}};
json j_object_empty(json::value_t::object);
json j_array = {1, 2, 4, 8, 16};
json j_array_empty(json::value_t::array);
json j_string = "Hello, world";
// call back()
std::cout << j_boolean.back() << '\n';
std::cout << j_number_integer.back() << '\n';
std::cout << j_number_float.back() << '\n';
std::cout << j_object.back() << '\n';
//std::cout << j_object_empty.back() << '\n'; // undefined behavior
std::cout << j_array.back() << '\n';
//std::cout << j_array_empty.back() << '\n'; // undefined behavior
std::cout << j_string.back() << '\n';
// back() called on a null value
try
{
json j_null;
j_null.back();
}
catch (const json::invalid_iterator& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
true
17
23.42
2
16
"Hello, world"
[json.exception.invalid_iterator.214] cannot get value
```
## See also
- [front](https://json.nlohmann.me/api/basic_json/front/index.md) to access the first element
## Version history
- Added in version 1.0.0.
- Adjusted code to return reference to binary values in version 3.8.0.
+402
View File
@@ -0,0 +1,402 @@
# <small>nlohmann::basic_json::</small>basic_json
```cpp
// (1)
basic_json(const value_t v);
// (2)
basic_json(std::nullptr_t = nullptr) noexcept;
// (3)
template<typename CompatibleType>
basic_json(CompatibleType&& val) noexcept(noexcept(
JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
std::forward<CompatibleType>(val))));
// (4)
template<typename BasicJsonType>
basic_json(const BasicJsonType& val);
// (5)
basic_json(initializer_list_t init,
bool type_deduction = true,
value_t manual_type = value_t::array);
// (6)
basic_json(size_type cnt, const basic_json& val);
// (7)
basic_json(iterator first, iterator last);
basic_json(const_iterator first, const_iterator last);
// (8)
basic_json(const basic_json& other);
// (9)
basic_json(basic_json&& other) noexcept;
```
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 | `#!json null` |
| boolean | `#!json false` |
| string | `#!json ""` |
| number | `#!json 0` |
| object | `#!json {}` |
| array | `#!json []` |
| binary | empty array |
The postcondition of this constructor can be restored by calling [`clear()`](clear.md).
2. Create a `#!json null` JSON value. It either takes a null pointer as parameter (explicitly creating `#!json null`)
or no parameter (implicitly creating `#!json 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`](array_t.md) 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`](object_t.md) 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_integer_t.md), [`number_unsigned_t`](number_unsigned_t.md),
[`number_float_t`](number_float_t.md), 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.
5. Creates a JSON value of type array or object from the passed initializer list `init`. In case `type_deduction` is
`#!cpp true` (default), the type of the JSON value to be created is deducted from the initializer list `init`
according to the following rules:
1. If the list is empty, an empty JSON object value `{}` is created.
2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first
elements of the pairs are treated as keys and the second elements are as values.
3. In all other cases, an array is created.
The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
1. The empty initializer list is written as `#!cpp {}` 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 (`#!json []`): 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()`](array.md) and [`object()`](object.md) force array and object creation from initializer lists,
respectively.
6. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is
created.
7. Constructs the JSON value with the contents of the range `[first, last)`. The semantics depend on the different
types a JSON value can have:
- In case of a `#!json null` type, [invalid_iterator.206](../../home/exceptions.md#jsonexceptioninvalid_iterator206)
is thrown.
- In case of other primitive types (number, boolean, or string), `first` must be `begin()` and `last` must be
`end()`. In this case, the value is copied. Otherwise,
[`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) 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 `#!json null` value.
## Template parameters
`CompatibleType`
: a type such that:
- `CompatibleType` is not derived from `std::istream`,
- `CompatibleType` is not `basic_json` (to avoid hijacking copy/move constructors),
- `CompatibleType` is not a different `basic_json` type (i.e. with different template arguments)
- `CompatibleType` is not a `basic_json` nested type (e.g., `json_pointer`, `iterator`, etc.)
- `json_serializer<U>` (with `U = uncvref_t<CompatibleType>`) has a `to_json(basic_json_t&, CompatibleType&&)`
method
`BasicJsonType`:
: a type such that:
- `BasicJsonType` is a `basic_json` type.
- `BasicJsonType` has different template arguments than `basic_json_t`.
`U`:
: `uncvref_t<CompatibleType>`
## Parameters
`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 `#!cpp true`, the type of the JSON value is deducted from the initializer list
`init`; when set to `#!cpp 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 `#!cpp 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 `#!cpp 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
## Exception safety
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.
## Exceptions
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`](../../home/exceptions.md#jsonexceptiontype_error301) if `type_deduction` is
`#!cpp 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
`#!cpp 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`](../../home/exceptions.md#jsonexceptioninvalid_iterator201) 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`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) if iterators `first`
and `last` belong to a primitive type (number, boolean, or string), but `first` does not point to the first
element anymore. In this case, the range `[first, last)` is undefined. See the example code below.
- Throws [`invalid_iterator.206`](../../home/exceptions.md#jsonexceptioninvalid_iterator206) if iterators `first`
and `last` belong to a `#!json null` value. In this case, the range `[first, last)` is undefined.
8. (none)
9. The function does not throw exceptions.
## Complexity
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.
## Notes
- Overload 5:
!!! note "Empty initializer list"
When used without parentheses around an empty initializer list, `basic_json()` is called instead of this
function, yielding the JSON `#!json null` value.
- Overload 7:
!!! info "Preconditions"
- Iterators `first` and `last` must be initialized. **This precondition is enforced with a
[runtime assertion](../../features/assertions.md).
- Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge
cases are detected; see the description of the exceptions above. A violation of this precondition yields
undefined behavior.
!!! danger "Runtime assertion"
A precondition is enforced with a [runtime assertion](../../features/assertions.md).
- Overload 8:
!!! info "Postcondition"
`#!cpp *this == other`
- Overload 9:
!!! info "Postconditions"
- `#!cpp `*this` has the same value as `other` before the call.
- `other` is a JSON `#!json null` value
## Examples
??? example "Example: (1) create an empty value with a given type"
The following code shows the constructor for different `value_t` values.
```cpp
--8<-- "examples/basic_json__value_t.cpp"
```
Output:
```json
--8<-- "examples/basic_json__value_t.output"
```
??? example "Example: (2) create a `#!json null` object"
The following code shows the constructor with and without a null pointer parameter.
```cpp
--8<-- "examples/basic_json__nullptr_t.cpp"
```
Output:
```json
--8<-- "examples/basic_json__nullptr_t.output"
```
??? example "Example: (3) create a JSON value from compatible types"
The following code shows the constructor with several compatible types.
```cpp
--8<-- "examples/basic_json__CompatibleType.cpp"
```
Output:
```json
--8<-- "examples/basic_json__CompatibleType.output"
```
Note the output is platform-dependent.
??? example "Example: (5) create a container (array or object) from an initializer list"
The example below shows how JSON values are created from initializer lists.
```cpp
--8<-- "examples/basic_json__list_init_t.cpp"
```
Output:
```json
--8<-- "examples/basic_json__list_init_t.output"
```
??? example "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.
```cpp
--8<-- "examples/basic_json__size_type_basic_json.cpp"
```
Output:
```json
--8<-- "examples/basic_json__size_type_basic_json.output"
```
??? example "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.
```cpp
--8<-- "examples/basic_json__InputIt_InputIt.cpp"
```
Output:
```json
--8<-- "examples/basic_json__InputIt_InputIt.output"
```
??? example "Example: (8) copy constructor"
The following code shows an example for the copy constructor.
```cpp
--8<-- "examples/basic_json__basic_json.cpp"
```
Output:
```json
--8<-- "examples/basic_json__basic_json.output"
```
??? example "Example: (9) move constructor"
The code below shows the move constructor explicitly called via `std::move`.
```cpp
--8<-- "examples/basic_json__moveconstructor.cpp"
```
Output:
```json
--8<-- "examples/basic_json__moveconstructor.output"
```
## Version history
1. Since version 1.0.0.
2. Since version 1.0.0.
3. Since version 2.1.0.
4. Since version 3.2.0.
5. Since version 1.0.0.
6. Since version 1.0.0.
7. Since version 1.0.0.
8. Since version 1.0.0.
9. Since version 1.0.0.
File diff suppressed because one or more lines are too long
+751
View File
@@ -0,0 +1,751 @@
# nlohmann::basic_json::basic_json
```
// (1)
basic_json(const value_t v);
// (2)
basic_json(std::nullptr_t = nullptr) noexcept;
// (3)
template<typename CompatibleType>
basic_json(CompatibleType&& val) noexcept(noexcept(
JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
std::forward<CompatibleType>(val))));
// (4)
template<typename BasicJsonType>
basic_json(const BasicJsonType& val);
// (5)
basic_json(initializer_list_t init,
bool type_deduction = true,
value_t manual_type = value_t::array);
// (6)
basic_json(size_type cnt, const basic_json& val);
// (7)
basic_json(iterator first, iterator last);
basic_json(const_iterator first, const_iterator last);
// (8)
basic_json(const basic_json& other);
// (9)
basic_json(basic_json&& other) noexcept;
```
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()`](https://json.nlohmann.me/api/basic_json/clear/index.md).
1. 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.
1. 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`](https://json.nlohmann.me/api/basic_json/array_t/index.md) 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`](https://json.nlohmann.me/api/basic_json/object_t/index.md) 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`](https://json.nlohmann.me/api/basic_json/number_integer_t/index.md), [`number_unsigned_t`](https://json.nlohmann.me/api/basic_json/number_unsigned_t/index.md), [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md), 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.
1. 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.
1. 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.
1. 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.
1. In all other cases, an array is created.
The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
1. The empty initializer list is written as `{}` which is exactly an empty JSON object.
1. 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.
1. 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()`](https://json.nlohmann.me/api/basic_json/array/index.md) and [`object()`](https://json.nlohmann.me/api/basic_json/object/index.md) force array and object creation from initializer lists, respectively.
1. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is created.
1. 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](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator206) is thrown.
- In case of other primitive types (number, boolean, or string), `first` must be `begin()` and `last` must be `end()`. In this case, the value is copied. Otherwise, [`invalid_iterator.204`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator204) 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.
1. Creates a copy of a given JSON value.
1. Move constructor. Constructs a JSON value with the contents of the given value `other` using move semantics. It "steals" the resources from `other` and leaves it as JSON `null` value.
## Template parameters
`CompatibleType` : a type such that:
```
- `CompatibleType` is not derived from `std::istream`,
- `CompatibleType` is not `basic_json` (to avoid hijacking copy/move constructors),
- `CompatibleType` is not a different `basic_json` type (i.e. with different template arguments)
- `CompatibleType` is not a `basic_json` nested type (e.g., `json_pointer`, `iterator`, etc.)
- `json_serializer<U>` (with `U = uncvref_t<CompatibleType>`) has a `to_json(basic_json_t&, CompatibleType&&)`
method
```
`BasicJsonType`: : a type such that:
```
- `BasicJsonType` is a `basic_json` type.
- `BasicJsonType` has different template arguments than `basic_json_t`.
```
`U`: : `uncvref_t<CompatibleType>`
## Parameters
`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
## Exception safety
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
1. No-throw guarantee: this constructor never throws exceptions.
1. 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.
1. 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.
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
1. No-throw guarantee: this constructor never throws exceptions.
## Exceptions
1. (none)
1. The function does not throw exceptions.
1. (none)
1. (none)
1. The function can throw the following exceptions:
- Throws [`type_error.301`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error301) 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.
1. (none)
1. The function can throw the following exceptions:
- Throws [`invalid_iterator.201`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator201) 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`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator204) if iterators `first` and `last` belong to a primitive type (number, boolean, or string), but `first` does not point to the first element anymore. In this case, the range `[first, last)` is undefined. See the example code below.
- Throws [`invalid_iterator.206`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator206) if iterators `first` and `last` belong to a `null` value. In this case, the range `[first, last)` is undefined.
1. (none)
1. The function does not throw exceptions.
## Complexity
1. Constant.
1. Constant.
1. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()` method.
1. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()` method.
1. Linear in the size of the initializer list `init`.
1. Linear in `cnt`.
1. Linear in distance between `first` and `last`.
1. Linear in the size of `other`.
1. Constant.
## Notes
- Overload 5:
Empty initializer list
When used without parentheses around an empty initializer list, `basic_json()` is called instead of this function, yielding the JSON `null` value.
- Overload 7:
Preconditions
- Iterators `first` and `last` must be initialized. \*\*This precondition is enforced with a [runtime assertion](https://json.nlohmann.me/features/assertions/index.md).
- Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior.
Runtime assertion
A precondition is enforced with a [runtime assertion](https://json.nlohmann.me/features/assertions/index.md).
- Overload 8:
Postcondition
`*this == other`
- Overload 9:
Postconditions
- `` `*this `` has the same value as `other` before the call.
- `other` is a JSON `null` value
## Examples
Example: (1) create an empty value with a given type
The following code shows the constructor for different `value_t` values.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create the different JSON values with default values
json j_null(json::value_t::null);
json j_boolean(json::value_t::boolean);
json j_number_integer(json::value_t::number_integer);
json j_number_float(json::value_t::number_float);
json j_object(json::value_t::object);
json j_array(json::value_t::array);
json j_string(json::value_t::string);
// serialize the JSON values
std::cout << j_null << '\n';
std::cout << j_boolean << '\n';
std::cout << j_number_integer << '\n';
std::cout << j_number_float << '\n';
std::cout << j_object << '\n';
std::cout << j_array << '\n';
std::cout << j_string << '\n';
}
```
Output:
```
null
false
0
0.0
{}
[]
""
```
Example: (2) create a `null` object
The following code shows the constructor with and without a null pointer parameter.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// implicitly create a JSON null value
json j1;
// explicitly create a JSON null value
json j2(nullptr);
// serialize the JSON null value
std::cout << j1 << '\n' << j2 << '\n';
}
```
Output:
```
null
null
```
Example: (3) create a JSON value from compatible types
The following code shows the constructor with several compatible types.
```
#include <iostream>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <valarray>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// ============
// object types
// ============
// create an object from an object_t value
json::object_t object_value = { {"one", 1}, {"two", 2} };
json j_object_t(object_value);
// create an object from std::map
std::map<std::string, int> c_map
{
{"one", 1}, {"two", 2}, {"three", 3}
};
json j_map(c_map);
// create an object from std::unordered_map
std::unordered_map<const char*, double> c_umap
{
{"one", 1.2}, {"two", 2.3}, {"three", 3.4}
};
json j_umap(c_umap);
// create an object from std::multimap
std::multimap<std::string, bool> c_mmap
{
{"one", true}, {"two", true}, {"three", false}, {"three", true}
};
json j_mmap(c_mmap); // only one entry for key "three" is used
// create an object from std::unordered_multimap
std::unordered_multimap<std::string, bool> c_ummap
{
{"one", true}, {"two", true}, {"three", false}, {"three", true}
};
json j_ummap(c_ummap); // only one entry for key "three" is used
// serialize the JSON objects
std::cout << j_object_t << '\n';
std::cout << j_map << '\n';
std::cout << j_umap << '\n';
std::cout << j_mmap << '\n';
std::cout << j_ummap << "\n\n";
// ===========
// array types
// ===========
// create an array from an array_t value
json::array_t array_value = {"one", "two", 3, 4.5, false};
json j_array_t(array_value);
// create an array from std::vector
std::vector<int> c_vector {1, 2, 3, 4};
json j_vec(c_vector);
// create an array from std::valarray
std::valarray<short> c_valarray {10, 9, 8, 7};
json j_valarray(c_valarray);
// create an array from std::deque
std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
json j_deque(c_deque);
// create an array from std::list
std::list<bool> c_list {true, true, false, true};
json j_list(c_list);
// create an array from std::forward_list
std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
json j_flist(c_flist);
// create an array from std::array
std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
json j_array(c_array);
// create an array from std::set
std::set<std::string> c_set {"one", "two", "three", "four", "one"};
json j_set(c_set); // only one entry for "one" is used
// create an array from std::unordered_set
std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
json j_uset(c_uset); // only one entry for "one" is used
// create an array from std::multiset
std::multiset<std::string> c_mset {"one", "two", "one", "four"};
json j_mset(c_mset); // both entries for "one" are used
// create an array from std::unordered_multiset
std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
json j_umset(c_umset); // both entries for "one" are used
// serialize the JSON arrays
std::cout << j_array_t << '\n';
std::cout << j_vec << '\n';
std::cout << j_valarray << '\n';
std::cout << j_deque << '\n';
std::cout << j_list << '\n';
std::cout << j_flist << '\n';
std::cout << j_array << '\n';
std::cout << j_set << '\n';
std::cout << j_uset << '\n';
std::cout << j_mset << '\n';
std::cout << j_umset << "\n\n";
// ============
// string types
// ============
// create string from a string_t value
json::string_t string_value = "The quick brown fox jumps over the lazy dog.";
json j_string_t(string_value);
// create a JSON string directly from a string literal
json j_string_literal("The quick brown fox jumps over the lazy dog.");
// create string from std::string
std::string s_stdstring = "The quick brown fox jumps over the lazy dog.";
json j_stdstring(s_stdstring);
// serialize the JSON strings
std::cout << j_string_t << '\n';
std::cout << j_string_literal << '\n';
std::cout << j_stdstring << "\n\n";
// ============
// number types
// ============
// create a JSON number from number_integer_t
json::number_integer_t value_integer_t = -42;
json j_integer_t(value_integer_t);
// create a JSON number from number_unsigned_t
json::number_integer_t value_unsigned_t = 17;
json j_unsigned_t(value_unsigned_t);
// create a JSON number from an anonymous enum
enum { enum_value = 17 };
json j_enum(enum_value);
// create values of different integer types
short n_short = 42;
int n_int = -23;
long n_long = 1024;
int_least32_t n_int_least32_t = -17;
uint8_t n_uint8_t = 8;
// create (integer) JSON numbers
json j_short(n_short);
json j_int(n_int);
json j_long(n_long);
json j_int_least32_t(n_int_least32_t);
json j_uint8_t(n_uint8_t);
// create values of different floating-point types
json::number_float_t v_ok = 3.141592653589793;
json::number_float_t v_nan = NAN;
json::number_float_t v_infinity = INFINITY;
// create values of different floating-point types
float n_float = 42.23;
float n_float_nan = 1.0f / 0.0f;
double n_double = 23.42;
// create (floating point) JSON numbers
json j_ok(v_ok);
json j_nan(v_nan);
json j_infinity(v_infinity);
json j_float(n_float);
json j_float_nan(n_float_nan);
json j_double(n_double);
// serialize the JSON numbers
std::cout << j_integer_t << '\n';
std::cout << j_unsigned_t << '\n';
std::cout << j_enum << '\n';
std::cout << j_short << '\n';
std::cout << j_int << '\n';
std::cout << j_long << '\n';
std::cout << j_int_least32_t << '\n';
std::cout << j_uint8_t << '\n';
std::cout << j_ok << '\n';
std::cout << j_nan << '\n';
std::cout << j_infinity << '\n';
std::cout << j_float << '\n';
std::cout << j_float_nan << '\n';
std::cout << j_double << "\n\n";
// =============
// boolean types
// =============
// create boolean values
json j_truth = true;
json j_falsity = false;
// serialize the JSON booleans
std::cout << j_truth << '\n';
std::cout << j_falsity << '\n';
}
```
Output:
```
{"one":1,"two":2}
{"one":1,"three":3,"two":2}
{"one":1.2,"three":3.4,"two":2.3}
{"one":true,"three":false,"two":true}
{"one":true,"three":false,"two":true}
["one","two",3,4.5,false]
[1,2,3,4]
[10,9,8,7]
[1.2,2.3,3.4,5.6]
[true,true,false,true]
[12345678909876,23456789098765,34567890987654,45678909876543]
[1,2,3,4]
["four","one","three","two"]
["four","three","two","one"]
["four","one","one","two"]
["four","two","one","one"]
"The quick brown fox jumps over the lazy dog."
"The quick brown fox jumps over the lazy dog."
"The quick brown fox jumps over the lazy dog."
-42
17
17
42
-23
1024
-17
8
3.141592653589793
null
null
42.22999954223633
null
23.42
true
false
```
Note the output is platform-dependent.
Example: (5) create a container (array or object) from an initializer list
The example below shows how JSON values are created from initializer lists.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_empty_init_list = json({});
json j_object = { {"one", 1}, {"two", 2} };
json j_array = {1, 2, 3, 4};
json j_nested_object = { {"one", {1}}, {"two", {1, 2}} };
json j_nested_array = { {{1}, "one"}, {{1, 2}, "two"} };
// serialize the JSON value
std::cout << j_empty_init_list << '\n';
std::cout << j_object << '\n';
std::cout << j_array << '\n';
std::cout << j_nested_object << '\n';
std::cout << j_nested_array << '\n';
}
```
Output:
```
{}
{"one":1,"two":2}
[1,2,3,4]
{"one":[1],"two":[1,2]}
[[[1],"one"],[[1,2],"two"]]
```
Example: (6) construct an array with count copies of a given value
The following code shows examples for creating arrays with several copies of a given value.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array by creating copies of a JSON value
json value = "Hello";
json array_0 = json(0, value);
json array_1 = json(1, value);
json array_5 = json(5, value);
// serialize the JSON arrays
std::cout << array_0 << '\n';
std::cout << array_1 << '\n';
std::cout << array_5 << '\n';
}
```
Output:
```
[]
["Hello"]
["Hello","Hello","Hello","Hello","Hello"]
```
Example: (7) construct a JSON container given an iterator range
The example below shows several ways to create JSON values by specifying a subrange with iterators.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_array = {"alpha", "bravo", "charly", "delta", "easy"};
json j_number = 42;
json j_object = {{"one", "eins"}, {"two", "zwei"}};
// create copies using iterators
json j_array_range(j_array.begin() + 1, j_array.end() - 2);
json j_number_range(j_number.begin(), j_number.end());
json j_object_range(j_object.begin(), j_object.find("two"));
// serialize the values
std::cout << j_array_range << '\n';
std::cout << j_number_range << '\n';
std::cout << j_object_range << '\n';
// example for an exception
try
{
json j_invalid(j_number.begin() + 1, j_number.end());
}
catch (const json::invalid_iterator& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
["bravo","charly"]
42
{"one":"eins"}
[json.exception.invalid_iterator.204] iterators out of range
```
Example: (8) copy constructor
The following code shows an example for the copy constructor.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON array
json j1 = {"one", "two", 3, 4.5, false};
// create a copy
json j2(j1);
// serialize the JSON array
std::cout << j1 << " = " << j2 << '\n';
std::cout << std::boolalpha << (j1 == j2) << '\n';
}
```
Output:
```
["one","two",3,4.5,false] = ["one","two",3,4.5,false]
true
```
Example: (9) move constructor
The code below shows the move constructor explicitly called via `std::move`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON value
json a = 23;
// move contents of a to b
json b(std::move(a));
// serialize the JSON arrays
std::cout << a << '\n';
std::cout << b << '\n';
}
```
Output:
```
null
23
```
## Version history
1. Since version 1.0.0.
1. Since version 1.0.0.
1. Since version 2.1.0.
1. Since version 3.2.0.
1. Since version 1.0.0.
1. Since version 1.0.0.
1. Since version 1.0.0.
1. Since version 1.0.0.
1. Since version 1.0.0.
+42
View File
@@ -0,0 +1,42 @@
# <small>nlohmann::basic_json::</small>begin
```cpp
iterator begin() noexcept;
const_iterator begin() const noexcept;
```
Returns an iterator to the first element.
![Illustration from cppreference.com](../../images/range-begin-end.svg)
## Return value
iterator to the first element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
??? example
The following code shows an example for `begin()`.
```cpp
--8<-- "examples/begin.cpp"
```
Output:
```json
--8<-- "examples/begin.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+55
View File
@@ -0,0 +1,55 @@
# nlohmann::basic_json::begin
```
iterator begin() noexcept;
const_iterator begin() const noexcept;
```
Returns an iterator to the first element.
## Return value
iterator to the first element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
Example
The following code shows an example for `begin()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array value
json array = {1, 2, 3, 4, 5};
// get an iterator to the first element
json::iterator it = array.begin();
// serialize the element that the iterator points to
std::cout << *it << '\n';
}
```
Output:
```
1
```
## Version history
- Added in version 1.0.0.
+66
View File
@@ -0,0 +1,66 @@
# <small>nlohmann::basic_json::</small>binary
```cpp
// (1)
static basic_json binary(const typename binary_t::container_type& init);
static basic_json binary(typename binary_t::container_type&& init);
// (2)
static basic_json binary(const typename binary_t::container_type& init,
std::uint8_t subtype);
static basic_json binary(typename binary_t::container_type&& init,
std::uint8_t subtype);
```
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.
## Parameters
`init` (in)
: container containing bytes to use as a binary type
`subtype` (in)
: subtype to use in CBOR, MessagePack, and BSON
## Return value
JSON binary array value
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the size of `init`; constant for `typename binary_t::container_type&& init` versions.
## Notes
Note, this function exists because of the difficulty in correctly specifying the correct template overload in the
standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because
JSON binary arrays are a non-standard extension, it was decided that it would be best to prevent automatic
initialization of a binary array type, for backwards compatibility and so it does not happen on accident.
## Examples
??? example
The following code shows how to create a binary value.
```cpp
--8<-- "examples/binary.cpp"
```
Output:
```json
--8<-- "examples/binary.output"
```
## Version history
- Added in version 3.8.0.
File diff suppressed because one or more lines are too long
+75
View File
@@ -0,0 +1,75 @@
# nlohmann::basic_json::binary
```
// (1)
static basic_json binary(const typename binary_t::container_type& init);
static basic_json binary(typename binary_t::container_type&& init);
// (2)
static basic_json binary(const typename binary_t::container_type& init,
std::uint8_t subtype);
static basic_json binary(typename binary_t::container_type&& init,
std::uint8_t subtype);
```
1. Creates a JSON binary array value from a given binary container.
1. Creates a JSON binary array value from a given binary container with subtype.
Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
## Parameters
`init` (in) : container containing bytes to use as a binary type
`subtype` (in) : subtype to use in CBOR, MessagePack, and BSON
## Return value
JSON binary array value
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the size of `init`; constant for `typename binary_t::container_type&& init` versions.
## Notes
Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension, it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.
## Examples
Example
The following code shows how to create a binary value.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a binary vector
std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};
// create a binary JSON value with subtype 42
json j = json::binary(vec, 42);
// output type and subtype
std::cout << "type: " << j.type_name() << ", subtype: " << j.get_binary().subtype() << std::endl;
}
```
Output:
```
type: binary, subtype: 42
```
## Version history
- Added in version 3.8.0.
+89
View File
@@ -0,0 +1,89 @@
# <small>nlohmann::basic_json::</small>binary_t
```cpp
using binary_t = byte_container_with_subtype<BinaryType>;
```
This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type
2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for
compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint64_t`, which
is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is
incompatible with each other, and it is up to the user to translate between them). The subtype is added to `BinaryType`
via the helper type [byte_container_with_subtype](../byte_container_with_subtype/index.md).
[CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as:
> Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers
> (major type 0).
[MessagePack's documentation on the bin type
family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-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](http://bsonspec.org/spec.html) 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 `#!cpp std::vector<std::uint8_t>`, which is a very common way to
represent a byte array in modern C++.
## Template parameters
`BinaryType`
: container type to store arrays
## Notes
#### Default type
The default values for `BinaryType` is `#!cpp std::vector<std::uint8_t>`.
#### Storage
Binary Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of the
type `#!cpp binary_t*` must be dereferenced.
#### Notes on subtypes
- CBOR
- Binary values are represented as byte strings. Subtypes are written as tags.
- MessagePack
- If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1,
fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is
then added as a signed 8-bit integer.
- If no subtype is given, the bin family (bin8, bin16, bin32) is used.
- BSON
- If a subtype is given, it is used and added as an unsigned 8-bit integer.
- If no subtype is given, the generic binary subtype 0x00 is used.
## Examples
??? example
The following code shows that `binary_t` is by default, a typedef to
`#!cpp nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>`.
```cpp
--8<-- "examples/binary_t.cpp"
```
Output:
```json
--8<-- "examples/binary_t.output"
```
## See also
- [byte_container_with_subtype](../byte_container_with_subtype/index.md)
## Version history
- Added in version 3.8.0. Changed the type of subtype to `std::uint64_t` in version 3.10.0.
File diff suppressed because one or more lines are too long
+88
View File
@@ -0,0 +1,88 @@
# nlohmann::basic_json::binary_t
```
using binary_t = byte_container_with_subtype<BinaryType>;
```
This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint64_t`, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to `BinaryType` via the helper type [byte_container_with_subtype](https://json.nlohmann.me/api/byte_container_with_subtype/index.md).
[CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as:
> Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).
[MessagePack's documentation on the bin type family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-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](http://bsonspec.org/spec.html) describe several binary types; however, this type is intended to represent the generic binary type which has the description:
> Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.
None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.
The default representation of this binary format is a `std::vector<std::uint8_t>`, which is a very common way to represent a byte array in modern C++.
## Template parameters
`BinaryType` : container type to store arrays
## Notes
#### Default type
The default values for `BinaryType` is `std::vector<std::uint8_t>`.
#### Storage
Binary Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of the type `binary_t*` must be dereferenced.
#### Notes on subtypes
- CBOR
- Binary values are represented as byte strings. Subtypes are written as tags.
- MessagePack
- If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as a signed 8-bit integer.
- If no subtype is given, the bin family (bin8, bin16, bin32) is used.
- BSON
- If a subtype is given, it is used and added as an unsigned 8-bit integer.
- If no subtype is given, the generic binary subtype 0x00 is used.
## Examples
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>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << std::boolalpha << std::is_same<nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>, json::binary_t>::value << std::endl;
}
```
Output:
```
true
```
## See also
- [byte_container_with_subtype](https://json.nlohmann.me/api/byte_container_with_subtype/index.md)
## Version history
- Added in version 3.8.0. Changed the type of subtype to `std::uint64_t` in version 3.10.0.
+42
View File
@@ -0,0 +1,42 @@
# <small>nlohmann::basic_json::</small>boolean_t
```cpp
using boolean_t = BooleanType;
```
The type used to store JSON booleans.
[RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a type which differentiates the two
literals `#!json true` and `#!json false`.
To store boolean values in C++, a type is defined by the template parameter `BooleanType` which chooses the type to use.
## Notes
#### Default type
With the default values for `BooleanType` (`#!cpp bool`), the default value for `boolean_t` is `#!cpp bool`.
#### Storage
Boolean values are stored directly inside a `basic_json` type.
## Examples
??? example
The following code shows that `boolean_t` is by default, a typedef to `#!cpp bool`.
```cpp
--8<-- "examples/boolean_t.cpp"
```
Output:
```json
--8<-- "examples/boolean_t.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+50
View File
@@ -0,0 +1,50 @@
# nlohmann::basic_json::boolean_t
```
using boolean_t = BooleanType;
```
The type used to store JSON booleans.
[RFC 8259](https://tools.ietf.org/html/rfc8259) 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.
## Notes
#### Default type
With the default values for `BooleanType` (`bool`), the default value for `boolean_t` is `bool`.
#### Storage
Boolean values are stored directly inside a `basic_json` type.
## Examples
Example
The following code shows that `boolean_t` is by default, a typedef to `bool`.
```
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << std::boolalpha << std::is_same<bool, json::boolean_t>::value << std::endl;
}
```
Output:
```
true
```
## Version history
- Added in version 1.0.0.
+41
View File
@@ -0,0 +1,41 @@
# <small>nlohmann::basic_json::</small>cbegin
```cpp
const_iterator cbegin() const noexcept;
```
Returns an iterator to the first element.
![Illustration from cppreference.com](../../images/range-begin-end.svg)
## Return value
iterator to the first element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
??? example
The following code shows an example for `cbegin()`.
```cpp
--8<-- "examples/cbegin.cpp"
```
Output:
```json
--8<-- "examples/cbegin.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+54
View File
@@ -0,0 +1,54 @@
# nlohmann::basic_json::cbegin
```
const_iterator cbegin() const noexcept;
```
Returns an iterator to the first element.
## Return value
iterator to the first element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
Example
The following code shows an example for `cbegin()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array value
const json array = {1, 2, 3, 4, 5};
// get an iterator to the first element
json::const_iterator it = array.cbegin();
// serialize the element that the iterator points to
std::cout << *it << '\n';
}
```
Output:
```
1
```
## Version history
- Added in version 1.0.0.
+42
View File
@@ -0,0 +1,42 @@
# <small>nlohmann::basic_json::</small>cbor_tag_handler_t
```cpp
enum class cbor_tag_handler_t
{
error,
ignore,
store
};
```
This enumeration is used in the [`from_cbor`](from_cbor.md) function to choose how to treat tags:
error
: throw a `parse_error` exception in case of a tag
ignore
: ignore tags
store
: store tagged values as binary container with subtype (for bytes 0xd8..0xdb)
## Examples
??? example
The example below shows how the different values of the `cbor_tag_handler_t` influence the behavior of
[`from_cbor`](from_cbor.md) when reading a tagged byte string.
```cpp
--8<-- "examples/cbor_tag_handler_t.cpp"
```
Output:
```json
--8<-- "examples/cbor_tag_handler_t.output"
```
## Version history
- Added in version 3.9.0. Added value `store` in 3.10.0.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,67 @@
# nlohmann::basic_json::cbor_tag_handler_t
```
enum class cbor_tag_handler_t
{
error,
ignore,
store
};
```
This enumeration is used in the [`from_cbor`](https://json.nlohmann.me/api/basic_json/from_cbor/index.md) function to choose how to treat tags:
error : throw a `parse_error` exception in case of a tag
ignore : ignore tags
store : store tagged values as binary container with subtype (for bytes 0xd8..0xdb)
## Examples
Example
The example below shows how the different values of the `cbor_tag_handler_t` influence the behavior of [`from_cbor`](https://json.nlohmann.me/api/basic_json/from_cbor/index.md) when reading a tagged byte string.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// tagged byte string
std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};
// cbor_tag_handler_t::error throws
try
{
auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);
}
catch (const json::parse_error& e)
{
std::cout << e.what() << std::endl;
}
// cbor_tag_handler_t::ignore ignores the tag
auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);
std::cout << b_ignore_tag << std::endl;
// cbor_tag_handler_t::store stores the tag as binary subtype
auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);
std::cout << b_store_tag << std::endl;
}
```
Output:
```
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xD8
{"bytes":[202,254,186,190],"subtype":null}
{"bytes":[202,254,186,190],"subtype":66}
```
## Version history
- Added in version 3.9.0. Added value `store` in 3.10.0.
+41
View File
@@ -0,0 +1,41 @@
# <small>nlohmann::basic_json::</small>cend
```cpp
const_iterator cend() const noexcept;
```
Returns an iterator to one past the last element.
![Illustration from cppreference.com](../../images/range-begin-end.svg)
## Return value
iterator one past the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
??? example
The following code shows an example for `cend()`.
```cpp
--8<-- "examples/cend.cpp"
```
Output:
```json
--8<-- "examples/cend.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+57
View File
@@ -0,0 +1,57 @@
# nlohmann::basic_json::cend
```
const_iterator cend() const noexcept;
```
Returns an iterator to one past the last element.
## Return value
iterator one past the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
Example
The following code shows an example for `cend()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array value
json array = {1, 2, 3, 4, 5};
// get an iterator to one past the last element
json::const_iterator it = array.cend();
// decrement the iterator to point to the last element
--it;
// serialize the element that the iterator points to
std::cout << *it << '\n';
}
```
Output:
```
5
```
## Version history
- Added in version 1.0.0.
+58
View File
@@ -0,0 +1,58 @@
# <small>nlohmann::basic_json::</small>clear
```cpp
void clear() noexcept;
```
Clears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](basic_json.md) would
have been called with the current value type from [`type()`](type.md):
| Value type | initial value |
|------------|----------------------|
| null | `null` |
| boolean | `false` |
| string | `""` |
| number | `0` |
| binary | An empty byte vector |
| object | `{}` |
| array | `[]` |
Has the same effect as calling
```.cpp
*this = basic_json(type());
```
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Linear in the size of the JSON value.
## Notes
All iterators, pointers, and references related to this container are invalidated.
## Examples
??? example
The example below shows the effect of `clear()` to different
JSON types.
```cpp
--8<-- "examples/clear.cpp"
```
Output:
```json
--8<-- "examples/clear.output"
```
## Version history
- Added in version 1.0.0.
- Added support for binary types in version 3.8.0.
File diff suppressed because one or more lines are too long
+95
View File
@@ -0,0 +1,95 @@
# nlohmann::basic_json::clear
```
void clear() noexcept;
```
Clears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](https://json.nlohmann.me/api/basic_json/basic_json/index.md) would have been called with the current value type from [`type()`](https://json.nlohmann.me/api/basic_json/type/index.md):
| Value type | initial value |
| ---------- | -------------------- |
| null | `null` |
| boolean | `false` |
| string | `""` |
| number | `0` |
| binary | An empty byte vector |
| object | `{}` |
| array | `[]` |
Has the same effect as calling
```
*this = basic_json(type());
```
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Linear in the size of the JSON value.
## Notes
All iterators, pointers, and references related to this container are invalidated.
## Examples
Example
The example below shows the effect of `clear()` to different JSON types.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_null;
json j_boolean = true;
json j_number_integer = 17;
json j_number_float = 23.42;
json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world";
// call clear()
j_null.clear();
j_boolean.clear();
j_number_integer.clear();
j_number_float.clear();
j_object.clear();
j_array.clear();
j_string.clear();
// serialize the cleared values()
std::cout << j_null << '\n';
std::cout << j_boolean << '\n';
std::cout << j_number_integer << '\n';
std::cout << j_number_float << '\n';
std::cout << j_object << '\n';
std::cout << j_array << '\n';
std::cout << j_string << '\n';
}
```
Output:
```
null
false
0
0.0
{}
[]
""
```
## Version history
- Added in version 1.0.0.
- Added support for binary types in version 3.8.0.
+119
View File
@@ -0,0 +1,119 @@
# <small>nlohmann::basic_json::</small>contains
```cpp
// (1)
bool contains(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
bool contains(KeyType&& key) const;
// (3)
bool contains(const json_pointer& ptr) const;
```
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, `#!cpp false` is returned.
2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
`#!cpp 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.
## Template parameters
`KeyType`
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
This can also be a string view (C++17).
## Parameters
`key` (in)
: key value to check its existence.
`ptr` (in)
: JSON pointer to check its existence.
## Return value
1. `#!cpp 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, `#!cpp false` is returned.
2. See 1.
3. `#!cpp true` if the JSON pointer can be resolved to a stored value, `#!cpp false` otherwise.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Exceptions
1. The function does not throw exceptions.
2. The function does not throw exceptions.
3. The function does not throw exceptions.
## Complexity
Logarithmic in the size of the JSON object.
## Notes
- This method always returns `#!cpp false` when executed on a JSON type that is not an object.
- This method can be executed on any JSON value type.
!!! info "Postconditions"
If `#!cpp j.contains(x)` returns `#!c true` for a key or JSON pointer `x`, then it is safe to call `j[x]`.
## Examples
??? example "Example: (1) check with key"
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains__object_t_key_type.cpp"
```
Output:
```json
--8<-- "examples/contains__object_t_key_type.output"
```
??? example "Example: (2) check with key using string_view"
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains__keytype.c++17.cpp"
```
Output:
```json
--8<-- "examples/contains__keytype.c++17.output"
```
??? example "Example: (3) check with JSON pointer"
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains__json_pointer.cpp"
```
Output:
```json
--8<-- "examples/contains__json_pointer.output"
```
## See also
- [find](find.md) find a value in an object
- [count](count.md) returns the number of occurrences of a key
## Version history
1. Added in version 3.11.0.
2. Added in version 3.6.0. Extended template `KeyType` to support comparable types in version 3.11.0.
3. Added in version 3.7.0.
File diff suppressed because one or more lines are too long
+199
View File
@@ -0,0 +1,199 @@
# nlohmann::basic_json::contains
```
// (1)
bool contains(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
bool contains(KeyType&& key) const;
// (3)
bool contains(const json_pointer& ptr) const;
```
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.
1. 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.
1. Check whether the given JSON pointer `ptr` can be resolved in the current JSON value.
## Template parameters
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
## Parameters
`key` (in) : key value to check its existence.
`ptr` (in) : JSON pointer to check its existence.
## Return value
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.
1. See 1.
1. `true` if the JSON pointer can be resolved to a stored value, `false` otherwise.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Exceptions
1. The function does not throw exceptions.
1. The function does not throw exceptions.
1. The function does not throw exceptions.
## Complexity
Logarithmic in the size of the JSON object.
## Notes
- This method always returns `false` when executed on a JSON type that is not an object.
- This method can be executed on any JSON value type.
Postconditions
If `j.contains(x)` returns `true` for a key or JSON pointer `x`, then it is safe to call `j[x]`.
## Examples
Example: (1) check with key
The example shows how `contains()` is used.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
// create some JSON values
json j_object = R"( {"key": "value"} )"_json;
json j_array = R"( [1, 2, 3] )"_json;
// call contains
std::cout << std::boolalpha <<
"j_object contains 'key': " << j_object.contains("key") << '\n' <<
"j_object contains 'another': " << j_object.contains("another") << '\n' <<
"j_array contains 'key': " << j_array.contains("key") << std::endl;
}
```
Output:
```
j_object contains 'key': true
j_object contains 'another': false
j_array contains 'key': false
```
Example: (2) check with key using string_view
The example shows how `contains()` is used.
```
#include <iostream>
#include <string_view>
#include <nlohmann/json.hpp>
using namespace std::string_view_literals;
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
// create some JSON values
json j_object = R"( {"key": "value"} )"_json;
json j_array = R"( [1, 2, 3] )"_json;
// call contains
std::cout << std::boolalpha <<
"j_object contains 'key': " << j_object.contains("key"sv) << '\n' <<
"j_object contains 'another': " << j_object.contains("another"sv) << '\n' <<
"j_array contains 'key': " << j_array.contains("key"sv) << std::endl;
}
```
Output:
```
j_object contains 'key': true
j_object contains 'another': false
j_array contains 'key': false
```
Example: (3) check with JSON pointer
The example shows how `contains()` is used.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
// create a JSON value
json j =
{
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
};
std::cout << std::boolalpha
<< j.contains("/number"_json_pointer) << '\n'
<< j.contains("/string"_json_pointer) << '\n'
<< j.contains("/array"_json_pointer) << '\n'
<< j.contains("/array/1"_json_pointer) << '\n'
<< j.contains("/array/-"_json_pointer) << '\n'
<< j.contains("/array/4"_json_pointer) << '\n'
<< j.contains("/baz"_json_pointer) << std::endl;
try
{
// try to use an array index with leading '0'
j.contains("/array/01"_json_pointer);
}
catch (const json::parse_error& e)
{
std::cout << e.what() << '\n';
}
try
{
// try to use an array index that is not a number
j.contains("/array/one"_json_pointer);
}
catch (const json::parse_error& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
true
true
true
true
false
false
false
```
## See also
- [find](https://json.nlohmann.me/api/basic_json/find/index.md) find a value in an object
- [count](https://json.nlohmann.me/api/basic_json/count/index.md) returns the number of occurrences of a key
## Version history
1. Added in version 3.11.0.
1. Added in version 3.6.0. Extended template `KeyType` to support comparable types in version 3.11.0.
1. Added in version 3.7.0.
+83
View File
@@ -0,0 +1,83 @@
# <small>nlohmann::basic_json::</small>count
```cpp
// (1)
size_type count(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
size_type count(KeyType&& key) const;
```
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 `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
## Template parameters
`KeyType`
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
This can also be a string view (C++17).
## Parameters
`key` (in)
: key value of the element to count.
## Return value
Number of elements with key `key`. If the JSON value is not an object, the return value will be `0`.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
Logarithmic in the size of the JSON object.
## Notes
This method always returns `0` when executed on a JSON type that is not an object.
## Examples
??? example "Example: (1) count number of elements"
The example shows how `count()` is used.
```cpp
--8<-- "examples/count__object_t_key_type.cpp"
```
Output:
```json
--8<-- "examples/count__object_t_key_type.output"
```
??? example "Example: (2) count number of elements using string_view"
The example shows how `count()` is used.
```cpp
--8<-- "examples/count__keytype.c++17.cpp"
```
Output:
```json
--8<-- "examples/count__keytype.c++17.output"
```
## See also
- [find](find.md) find a value in an object
- [contains](contains.md) checks whether a key exists
## Version history
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.
File diff suppressed because one or more lines are too long
+115
View File
@@ -0,0 +1,115 @@
# nlohmann::basic_json::count
```
// (1)
size_type count(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
size_type count(KeyType&& key) const;
```
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).
1. See 1. This overload is only available if `KeyType` is comparable with `typename object_t::key_type` and `typename object_comparator_t::is_transparent` denotes a type.
## Template parameters
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
## Parameters
`key` (in) : key value of the element to count.
## Return value
Number of elements with key `key`. If the JSON value is not an object, the return value will be `0`.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
Logarithmic in the size of the JSON object.
## Notes
This method always returns `0` when executed on a JSON type that is not an object.
## Examples
Example: (1) count number of elements
The example shows how `count()` is used.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON object
json j_object = {{"one", 1}, {"two", 2}};
// call count()
auto count_two = j_object.count("two");
auto count_three = j_object.count("three");
// print values
std::cout << "number of elements with key \"two\": " << count_two << '\n';
std::cout << "number of elements with key \"three\": " << count_three << '\n';
}
```
Output:
```
number of elements with key "two": 1
number of elements with key "three": 0
```
Example: (2) count number of elements using string_view
The example shows how `count()` is used.
```
#include <iostream>
#include <string_view>
#include <nlohmann/json.hpp>
using namespace std::string_view_literals;
using json = nlohmann::json;
int main()
{
// create a JSON object
json j_object = {{"one", 1}, {"two", 2}};
// call count()
auto count_two = j_object.count("two"sv);
auto count_three = j_object.count("three"sv);
// print values
std::cout << "number of elements with key \"two\": " << count_two << '\n';
std::cout << "number of elements with key \"three\": " << count_three << '\n';
}
```
Output:
```
number of elements with key "two": 1
number of elements with key "three": 0
```
## See also
- [find](https://json.nlohmann.me/api/basic_json/find/index.md) find a value in an object
- [contains](https://json.nlohmann.me/api/basic_json/contains/index.md) checks whether a key exists
## Version history
1. Added in version 3.11.0.
1. Added in version 1.0.0. Changed parameter `key` type to `KeyType&&` in version 3.11.0.
+41
View File
@@ -0,0 +1,41 @@
# <small>nlohmann::basic_json::</small>crbegin
```cpp
const_reverse_iterator crbegin() const noexcept;
```
Returns an iterator to the reverse-beginning; that is, the last element.
![Illustration from cppreference.com](../../images/range-rbegin-rend.svg)
## Return value
reverse iterator to the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
??? example
The following code shows an example for `crbegin()`.
```cpp
--8<-- "examples/crbegin.cpp"
```
Output:
```json
--8<-- "examples/crbegin.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+54
View File
@@ -0,0 +1,54 @@
# nlohmann::basic_json::crbegin
```
const_reverse_iterator crbegin() const noexcept;
```
Returns an iterator to the reverse-beginning; that is, the last element.
## Return value
reverse iterator to the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
Example
The following code shows an example for `crbegin()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array value
json array = {1, 2, 3, 4, 5};
// get an iterator to the reverse-beginning
json::const_reverse_iterator it = array.crbegin();
// serialize the element that the iterator points to
std::cout << *it << '\n';
}
```
Output:
```
5
```
## Version history
- Added in version 1.0.0.
+42
View File
@@ -0,0 +1,42 @@
# <small>nlohmann::basic_json::</small>crend
```cpp
const_reverse_iterator crend() const noexcept;
```
Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder,
attempting to access it results in undefined behavior.
![Illustration from cppreference.com](../../images/range-rbegin-rend.svg)
## Return value
reverse iterator to the element following the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
??? example
The following code shows an example for `crend()`.
```cpp
--8<-- "examples/crend.cpp"
```
Output:
```json
--8<-- "examples/crend.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+57
View File
@@ -0,0 +1,57 @@
# nlohmann::basic_json::crend
```
const_reverse_iterator crend() const noexcept;
```
Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.
## Return value
reverse iterator to the element following the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
Example
The following code shows an example for `crend()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array value
json array = {1, 2, 3, 4, 5};
// get an iterator to the reverse-end
json::const_reverse_iterator it = array.crend();
// increment the iterator to point to the first element
--it;
// serialize the element that the iterator points to
std::cout << *it << '\n';
}
```
Output:
```
1
```
## Version history
- Added in version 1.0.0.
@@ -0,0 +1,35 @@
# <small>nlohmann::basic_json::</small>default_object_comparator_t
```cpp
using default_object_comparator_t = std::less<StringType>; // until C++14
using default_object_comparator_t = std::less<>; // since C++14
```
The default comparator used by [`object_t`](object_t.md).
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`](object_t.md) and can be obtained via
[`object_comparator_t`](object_comparator_t.md).
## Examples
??? example
The example below demonstrates the default comparator.
```cpp
--8<-- "examples/default_object_comparator_t.cpp"
```
Output:
```json
--8<-- "examples/default_object_comparator_t.output"
```
## Version history
- Added in version 3.11.0.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,44 @@
# nlohmann::basic_json::default_object_comparator_t
```
using default_object_comparator_t = std::less<StringType>; // until C++14
using default_object_comparator_t = std::less<>; // since C++14
```
The default comparator used by [`object_t`](https://json.nlohmann.me/api/basic_json/object_t/index.md).
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`](https://json.nlohmann.me/api/basic_json/object_t/index.md) and can be obtained via [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md).
## Examples
Example
The example below demonstrates the default comparator.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << std::boolalpha
<< "one < two : " << json::default_object_comparator_t{}("one", "two") << "\n"
<< "three < four : " << json::default_object_comparator_t{}("three", "four") << std::endl;
}
```
Output:
```
one < two : true
three < four : false
```
## Version history
- Added in version 3.11.0.
+65
View File
@@ -0,0 +1,65 @@
# <small>nlohmann::basic_json::</small>diff
```cpp
static basic_json diff(const basic_json& source,
const basic_json& target);
```
Creates a [JSON Patch](http://jsonpatch.com) so that value `source` can be changed into the value `target` by calling
[`patch`](patch.md) function.
For two JSON values `source` and `target`, the following code yields always `#!cpp true`:
```cpp
source.patch(diff(source, target)) == target;
```
## Parameters
`source` (in)
: JSON value to compare from
`target` (in)
: JSON value to compare against
## Return value
a JSON patch to convert the `source` to `target`
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the lengths of `source` and `target`.
## Notes
Currently, only `remove`, `add`, and `replace` operations are generated.
## Examples
??? example
The following code shows how a JSON patch is created as a diff for two JSON values.
```cpp
--8<-- "examples/diff.cpp"
```
Output:
```json
--8<-- "examples/diff.output"
```
## See also
- [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
- [patch](patch.md) applies a JSON Patch
- [patch_inplace](patch_inplace.md) applies a JSON Patch in place
- [merge_patch](merge_patch.md) applies a JSON Merge Patch
## Version history
- Added in version 2.0.0.
File diff suppressed because one or more lines are too long
+123
View File
@@ -0,0 +1,123 @@
# nlohmann::basic_json::diff
```
static basic_json diff(const basic_json& source,
const basic_json& target);
```
Creates a [JSON Patch](http://jsonpatch.com) so that value `source` can be changed into the value `target` by calling [`patch`](https://json.nlohmann.me/api/basic_json/patch/index.md) function.
For two JSON values `source` and `target`, the following code yields always `true`:
```
source.patch(diff(source, target)) == target;
```
## Parameters
`source` (in) : JSON value to compare from
`target` (in) : JSON value to compare against
## Return value
a JSON patch to convert the `source` to `target`
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the lengths of `source` and `target`.
## Notes
Currently, only `remove`, `add`, and `replace` operations are generated.
## Examples
Example
The following code shows how a JSON patch is created as a diff for two JSON values.
```
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
// the source document
json source = R"(
{
"baz": "qux",
"foo": "bar"
}
)"_json;
// the target document
json target = R"(
{
"baz": "boo",
"hello": [
"world"
]
}
)"_json;
// create the patch
json patch = json::diff(source, target);
// roundtrip
json patched_source = source.patch(patch);
// output patch and roundtrip result
std::cout << std::setw(4) << patch << "\n\n"
<< std::setw(4) << patched_source << std::endl;
}
```
Output:
```
[
{
"op": "replace",
"path": "/baz",
"value": "boo"
},
{
"op": "remove",
"path": "/foo"
},
{
"op": "add",
"path": "/hello",
"value": [
"world"
]
}
]
{
"baz": "boo",
"hello": [
"world"
]
}
```
## See also
- [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
- [patch](https://json.nlohmann.me/api/basic_json/patch/index.md) applies a JSON Patch
- [patch_inplace](https://json.nlohmann.me/api/basic_json/patch_inplace/index.md) applies a JSON Patch in place
- [merge_patch](https://json.nlohmann.me/api/basic_json/merge_patch/index.md) applies a JSON Merge Patch
## Version history
- Added in version 2.0.0.
+85
View File
@@ -0,0 +1,85 @@
# <small>nlohmann::basic_json::</small>dump
```cpp
string_t dump(const int indent = -1,
const char indent_char = ' ',
const bool ensure_ascii = false,
const error_handler_t error_handler = error_handler_t::strict) const;
```
Serialization function for JSON values. The function tries to mimic Python's
[`json.dumps()` function](https://docs.python.org/2/library/json.html#json.dump), and currently supports its `indent`
and `ensure_ascii` parameters.
## Parameters
`indent` (in)
: If `indent` is nonnegative, then array elements and object members will be pretty-printed with that indent level. An
indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation.
`indent_char` (in)
: The character to use for indentation if `indent` is greater than `0`. The default is ` ` (space).
`ensure_ascii` (in)
: If `ensure_ascii` is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the
result consists of ASCII characters only.
`error_handler` (in)
: how to react on decoding errors; there are three possible values (see [`error_handler_t`](error_handler_t.md):
`strict` (throws an exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences
with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all valid bytes are copied to the
output unchanged, and invalid bytes are dropped)).
## Return value
string containing the serialization of the JSON value
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
## Exceptions
Throws [`type_error.316`](../../home/exceptions.md#jsonexceptiontype_error316) if a string stored inside the JSON value
is not UTF-8 encoded and `error_handler` is set to `strict`
## Complexity
Linear.
## Notes
Binary values are serialized as an object containing two keys:
- "bytes": an array of bytes as integers
- "subtype": the subtype as integer or `#!json null` if the binary has no subtype
## Examples
??? example
The following example shows the effect of different `indent`, `indent_char`, and `ensure_ascii` parameters to the
result of the serialization.
```cpp
--8<-- "examples/dump.cpp"
```
Output:
```json
--8<-- "examples/dump.output"
```
## See also
- [to_string](to_string.md) returns a string representation of a JSON value
- [operator<<](../operator_ltlt.md) serialize to stream
- [Serialization](../../features/serialization.md) - the serialization article
## Version history
- Added in version 1.0.0.
- Indentation character `indent_char`, option `ensure_ascii` and exceptions added in version 3.0.0.
- Error handlers added in version 3.4.0.
- Serialization of binary values added in version 3.8.0.
File diff suppressed because one or more lines are too long
+173
View File
@@ -0,0 +1,173 @@
# nlohmann::basic_json::dump
```
string_t dump(const int indent = -1,
const char indent_char = ' ',
const bool ensure_ascii = false,
const error_handler_t error_handler = error_handler_t::strict) const;
```
Serialization function for JSON values. The function tries to mimic Python's [`json.dumps()` function](https://docs.python.org/2/library/json.html#json.dump), and currently supports its `indent` and `ensure_ascii` parameters.
## Parameters
`indent` (in) : If `indent` is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation.
`indent_char` (in) : The character to use for indentation if `indent` is greater than `0`. The default is (space).
`ensure_ascii` (in) : If `ensure_ascii` is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only.
`error_handler` (in) : how to react on decoding errors; there are three possible values (see [`error_handler_t`](https://json.nlohmann.me/api/basic_json/error_handler_t/index.md): `strict` (throws an exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all valid bytes are copied to the output unchanged, and invalid bytes are dropped)).
## Return value
string containing the serialization of the JSON value
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
## Exceptions
Throws [`type_error.316`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error316) if a string stored inside the JSON value is not UTF-8 encoded and `error_handler` is set to `strict`
## Complexity
Linear.
## Notes
Binary values are serialized as an object containing two keys:
- "bytes": an array of bytes as integers
- "subtype": the subtype as integer or `null` if the binary has no subtype
## Examples
Example
The following example shows the effect of different `indent`, `indent_char`, and `ensure_ascii` parameters to the result of the serialization.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16};
json j_string = "Hellö 😀!";
// call dump()
std::cout << "objects:" << '\n'
<< j_object.dump() << "\n\n"
<< j_object.dump(-1) << "\n\n"
<< j_object.dump(0) << "\n\n"
<< j_object.dump(4) << "\n\n"
<< j_object.dump(1, '\t') << "\n\n";
std::cout << "arrays:" << '\n'
<< j_array.dump() << "\n\n"
<< j_array.dump(-1) << "\n\n"
<< j_array.dump(0) << "\n\n"
<< j_array.dump(4) << "\n\n"
<< j_array.dump(1, '\t') << "\n\n";
std::cout << "strings:" << '\n'
<< j_string.dump() << '\n'
<< j_string.dump(-1, ' ', true) << '\n';
// create JSON value with invalid UTF-8 byte sequence
json j_invalid = "ä\xA9ü";
try
{
std::cout << j_invalid.dump() << std::endl;
}
catch (const json::type_error& e)
{
std::cout << e.what() << std::endl;
}
std::cout << "string with replaced invalid characters: "
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
<< "\nstring with ignored invalid characters: "
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
<< '\n';
}
```
Output:
```
objects:
{"one":1,"two":2}
{"one":1,"two":2}
{
"one": 1,
"two": 2
}
{
"one": 1,
"two": 2
}
{
"one": 1,
"two": 2
}
arrays:
[1,2,4,8,16]
[1,2,4,8,16]
[
1,
2,
4,
8,
16
]
[
1,
2,
4,
8,
16
]
[
1,
2,
4,
8,
16
]
strings:
"Hellö 😀!"
"Hell\u00f6 \ud83d\ude00!"
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
string with replaced invalid characters: "äü"
string with ignored invalid characters: "äü"
```
## See also
- [to_string](https://json.nlohmann.me/api/basic_json/to_string/index.md) returns a string representation of a JSON value
- [operator\<<](https://json.nlohmann.me/api/operator_ltlt/index.md) serialize to stream
- [Serialization](https://json.nlohmann.me/features/serialization/index.md) - the serialization article
## Version history
- Added in version 1.0.0.
- Indentation character `indent_char`, option `ensure_ascii` and exceptions added in version 3.0.0.
- Error handlers added in version 3.4.0.
- Serialization of binary values added in version 3.8.0.
+71
View File
@@ -0,0 +1,71 @@
# <small>nlohmann::basic_json::</small>emplace
```cpp
template<class... Args>
std::pair<iterator, bool> emplace(Args&& ... args);
```
Inserts a new element into a JSON object constructed in-place with the given `args` if there is no element with the key
in the container. If the function is called on a JSON null value, an empty object is created before appending the value
created from `args`.
## Template parameters
`Args`
: compatible types to create a `basic_json` object
## Iterator invalidation
For [`ordered_json`](../ordered_json.md), 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.
## Parameters
`args` (in)
: arguments to forward to a constructor of `basic_json`
## Return value
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and
a `#!cpp bool` denoting whether the insertion took place.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
## Exceptions
Throws [`type_error.311`](../../home/exceptions.md#jsonexceptiontype_error311) when called on a type other than JSON
object or `#!json null`; example: `"cannot use emplace() with number"`
## Complexity
Logarithmic in the size of the container, O(log(`size()`)).
## Examples
??? example
The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `#!json 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.
```cpp
--8<-- "examples/emplace.cpp"
```
Output:
```json
--8<-- "examples/emplace.output"
```
## See also
- [emplace_back](emplace_back.md) add a value to an array
- [insert](insert.md) add values to an array/object
- [Modifying values](../../features/modifying_values.md) - the article on modifying values
## Version history
- Since version 2.0.8.
File diff suppressed because one or more lines are too long
+97
View File
@@ -0,0 +1,97 @@
# nlohmann::basic_json::emplace
```
template<class... Args>
std::pair<iterator, bool> emplace(Args&& ... args);
```
Inserts a new element into a JSON object constructed in-place with the given `args` if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from `args`.
## Template parameters
`Args` : compatible types to create a `basic_json` object
## Iterator invalidation
For [`ordered_json`](https://json.nlohmann.me/api/ordered_json/index.md), 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.
## Parameters
`args` (in) : arguments to forward to a constructor of `basic_json`
## Return value
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.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
## Exceptions
Throws [`type_error.311`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error311) when called on a type other than JSON object or `null`; example: `"cannot use emplace() with number"`
## Complexity
Logarithmic in the size of the container, O(log(`size()`)).
## Examples
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json object = {{"one", 1}, {"two", 2}};
json null;
// print values
std::cout << object << '\n';
std::cout << null << '\n';
// add values
auto res1 = object.emplace("three", 3);
null.emplace("A", "a");
null.emplace("B", "b");
// the following call will not add an object, because there is already
// a value stored at key "B"
auto res2 = null.emplace("B", "c");
// print values
std::cout << object << '\n';
std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';
std::cout << null << '\n';
std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';
}
```
Output:
```
{"one":1,"two":2}
null
{"one":1,"three":3,"two":2}
3 true
{"A":"a","B":"b"}
"b" false
```
## See also
- [emplace_back](https://json.nlohmann.me/api/basic_json/emplace_back/index.md) add a value to an array
- [insert](https://json.nlohmann.me/api/basic_json/insert/index.md) add values to an array/object
- [Modifying values](https://json.nlohmann.me/features/modifying_values/index.md) - the article on modifying values
## Version history
- Since version 2.0.8.
+66
View File
@@ -0,0 +1,66 @@
# <small>nlohmann::basic_json::</small>emplace_back
```cpp
template<class... Args>
reference emplace_back(Args&& ... args);
```
Creates a JSON value from the passed parameters `args` to the end of the JSON value. If the function is called on a JSON
`#!json null` value, an empty array is created before appending the value created from `args`.
## Template parameters
`Args`
: compatible types to create a `basic_json` object
## Iterator invalidation
By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the
[`end()`](end.md) iterator) and all references to the elements are invalidated. Otherwise, only the [`end()`](end.md)
iterator is invalidated.
## Parameters
`args` (in)
: arguments to forward to a constructor of `basic_json`
## Return value
reference to the inserted element
## Exceptions
Throws [`type_error.311`](../../home/exceptions.md#jsonexceptiontype_error311) when called on a type other than JSON
array or `#!json null`; example: `"cannot use emplace_back() with number"`
## Complexity
Amortized constant.
## Examples
??? 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.
```cpp
--8<-- "examples/emplace_back.cpp"
```
Output:
```json
--8<-- "examples/emplace_back.output"
```
## See also
- [operator+=](operator+=.md) add a value to an array/object
- [push_back](push_back.md) add a value to an array/object
- [Modifying values](../../features/modifying_values.md) - the article on modifying values
## Version history
- Since version 2.0.8.
- Returns reference since 3.7.0.
File diff suppressed because one or more lines are too long
+85
View File
@@ -0,0 +1,85 @@
# nlohmann::basic_json::emplace_back
```
template<class... Args>
reference emplace_back(Args&& ... args);
```
Creates a JSON value from the passed parameters `args` to the end of the JSON value. If the function is called on a JSON `null` value, an empty array is created before appending the value created from `args`.
## Template parameters
`Args` : compatible types to create a `basic_json` object
## Iterator invalidation
By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the [`end()`](https://json.nlohmann.me/api/basic_json/end/index.md) iterator) and all references to the elements are invalidated. Otherwise, only the [`end()`](https://json.nlohmann.me/api/basic_json/end/index.md) iterator is invalidated.
## Parameters
`args` (in) : arguments to forward to a constructor of `basic_json`
## Return value
reference to the inserted element
## Exceptions
Throws [`type_error.311`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error311) when called on a type other than JSON array or `null`; example: `"cannot use emplace_back() with number"`
## Complexity
Amortized constant.
## Examples
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>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json array = {1, 2, 3, 4, 5};
json null;
// print values
std::cout << array << '\n';
std::cout << null << '\n';
// add values
array.emplace_back(6);
null.emplace_back("first");
null.emplace_back(3, "second");
// print values
std::cout << array << '\n';
std::cout << null << '\n';
}
```
Output:
```
[1,2,3,4,5]
null
[1,2,3,4,5,6]
["first",["second","second","second"]]
```
## See also
- [operator+=](https://json.nlohmann.me/api/basic_json/operator%2B%3D/index.md) add a value to an array/object
- [push_back](https://json.nlohmann.me/api/basic_json/push_back/index.md) add a value to an array/object
- [Modifying values](https://json.nlohmann.me/features/modifying_values/index.md) - the article on modifying values
## Version history
- Since version 2.0.8.
- Returns reference since 3.7.0.
+66
View File
@@ -0,0 +1,66 @@
# <small>nlohmann::basic_json::</small>empty
```cpp
bool empty() const noexcept;
```
Checks if a JSON value has no elements (i.e., whether its [`size()`](size.md) is `0`).
## Return value
The return value depends on the different types and is defined as follows:
| Value type | return value |
|------------|----------------------------------------|
| null | `#!cpp true` |
| boolean | `#!cpp false` |
| string | `#!cpp false` |
| number | `#!cpp false` |
| binary | `#!cpp false` |
| object | result of function `object_t::empty()` |
| array | result of function `array_t::empty()` |
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Constant, as long as [`array_t`](array_t.md) and [`object_t`](object_t.md) satisfy the
[Container](https://en.cppreference.com/w/cpp/named_req/Container) concept; that is, their `empty()` functions have
constant complexity.
## Possible implementation
```cpp
bool empty() const noexcept
{
return size() == 0;
}
```
## Notes
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 `#!cpp false` in the case of a string.
## Examples
??? example
The following code uses `empty()` to check if a JSON object contains any elements.
```cpp
--8<-- "examples/empty.cpp"
```
Output:
```json
--8<-- "examples/empty.output"
```
## Version history
- Added in version 1.0.0.
- Extended to return `#!cpp false` for binary types in version 3.8.0.
File diff suppressed because one or more lines are too long
+100
View File
@@ -0,0 +1,100 @@
# nlohmann::basic_json::empty
```
bool empty() const noexcept;
```
Checks if a JSON value has no elements (i.e., whether its [`size()`](https://json.nlohmann.me/api/basic_json/size/index.md) is `0`).
## Return value
The return value depends on the different types and is defined as follows:
| Value type | return value |
| ---------- | -------------------------------------- |
| null | `true` |
| boolean | `false` |
| string | `false` |
| number | `false` |
| binary | `false` |
| object | result of function `object_t::empty()` |
| array | result of function `array_t::empty()` |
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Constant, as long as [`array_t`](https://json.nlohmann.me/api/basic_json/array_t/index.md) and [`object_t`](https://json.nlohmann.me/api/basic_json/object_t/index.md) satisfy the [Container](https://en.cppreference.com/w/cpp/named_req/Container) concept; that is, their `empty()` functions have constant complexity.
## Possible implementation
```
bool empty() const noexcept
{
return size() == 0;
}
```
## Notes
This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is `false` in the case of a string.
## Examples
Example
The following code uses `empty()` to check if a JSON object contains any elements.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_null;
json j_boolean = true;
json j_number_integer = 17;
json j_number_float = 23.42;
json j_object = {{"one", 1}, {"two", 2}};
json j_object_empty(json::value_t::object);
json j_array = {1, 2, 4, 8, 16};
json j_array_empty(json::value_t::array);
json j_string = "Hello, world";
// call empty()
std::cout << std::boolalpha;
std::cout << j_null.empty() << '\n';
std::cout << j_boolean.empty() << '\n';
std::cout << j_number_integer.empty() << '\n';
std::cout << j_number_float.empty() << '\n';
std::cout << j_object.empty() << '\n';
std::cout << j_object_empty.empty() << '\n';
std::cout << j_array.empty() << '\n';
std::cout << j_array_empty.empty() << '\n';
std::cout << j_string.empty() << '\n';
}
```
Output:
```
true
false
false
false
false
true
false
true
false
```
## Version history
- Added in version 1.0.0.
- Extended to return `false` for binary types in version 3.8.0.
+42
View File
@@ -0,0 +1,42 @@
# <small>nlohmann::basic_json::</small>end
```cpp
iterator end() noexcept;
const_iterator end() const noexcept;
```
Returns an iterator to one past the last element.
![Illustration from cppreference.com](../../images/range-begin-end.svg)
## Return value
iterator one past the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
??? example
The following code shows an example for `end()`.
```cpp
--8<-- "examples/end.cpp"
```
Output:
```json
--8<-- "examples/end.output"
```
## Version history
- Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+58
View File
@@ -0,0 +1,58 @@
# nlohmann::basic_json::end
```
iterator end() noexcept;
const_iterator end() const noexcept;
```
Returns an iterator to one past the last element.
## Return value
iterator one past the last element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Examples
Example
The following code shows an example for `end()`.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create an array value
json array = {1, 2, 3, 4, 5};
// get an iterator to one past the last element
json::iterator it = array.end();
// decrement the iterator to point to the last element
--it;
// serialize the element that the iterator points to
std::cout << *it << '\n';
}
```
Output:
```
5
```
## Version history
- Added in version 1.0.0.
+68
View File
@@ -0,0 +1,68 @@
# <small>nlohmann::basic_json::</small>end_pos
```cpp
#if JSON_DIAGNOSTIC_POSITIONS
constexpr std::size_t end_pos() const noexcept;
#endif
```
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` |
## Return value
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`](parse.md) function, or `std::string::npos` if the value was constructed otherwise
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Notes
!!! note "Note"
The function is only available if macro [`JSON_DIAGNOSTIC_POSITIONS`](../macros/json_diagnostic_positions.md) has
been defined to `#!cpp 1` before including the library header.
!!! warning "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.
## Examples
??? example "Example"
```cpp
--8<-- "examples/diagnostic_positions.cpp"
```
Output:
```
--8<-- "examples/diagnostic_positions.output"
```
The output shows the start/end positions of all the objects and fields in the JSON string.
## See also
- [start_pos](start_pos.md) to access the start position
- [JSON_DIAGNOSTIC_POSITIONS](../macros/json_diagnostic_positions.md) for an overview of the diagnostic positions
## Version history
- Added in version 3.12.0.
File diff suppressed because one or more lines are too long
+163
View File
@@ -0,0 +1,163 @@
# nlohmann::basic_json::end_pos
```
#if JSON_DIAGNOSTIC_POSITIONS
constexpr std::size_t end_pos() const noexcept;
#endif
```
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` |
## Return value
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`](https://json.nlohmann.me/api/basic_json/parse/index.md) function, or `std::string::npos` if the value was constructed otherwise
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Notes
Note
The function is only available if macro [`JSON_DIAGNOSTIC_POSITIONS`](https://json.nlohmann.me/api/macros/json_diagnostic_positions/index.md) 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.
## Examples
Example
```
#include <iostream>
#define JSON_DIAGNOSTIC_POSITIONS 1
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::string json_string = R"(
{
"address": {
"street": "Fake Street",
"housenumber": 1
}
}
)";
json j = json::parse(json_string);
std::cout << "Root diagnostic positions: \n";
std::cout << "\tstart_pos: " << j.start_pos() << '\n';
std::cout << "\tend_pos:" << j.end_pos() << "\n";
std::cout << "Original string: \n";
std::cout << "{\n \"address\": {\n \"street\": \"Fake Street\",\n \"housenumber\": 1\n }\n }" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j.start_pos(), j.end_pos() - j.start_pos()) << "\n\n";
std::cout << "address diagnostic positions: \n";
std::cout << "\tstart_pos:" << j["address"].start_pos() << '\n';
std::cout << "\tend_pos:" << j["address"].end_pos() << "\n\n";
std::cout << "Original string: \n";
std::cout << "{ \"street\": \"Fake Street\",\n \"housenumber\": 1\n }" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j["address"].start_pos(), j["address"].end_pos() - j["address"].start_pos()) << "\n\n";
std::cout << "street diagnostic positions: \n";
std::cout << "\tstart_pos:" << j["address"]["street"].start_pos() << '\n';
std::cout << "\tend_pos:" << j["address"]["street"].end_pos() << "\n\n";
std::cout << "Original string: \n";
std::cout << "\"Fake Street\"" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j["address"]["street"].start_pos(), j["address"]["street"].end_pos() - j["address"]["street"].start_pos()) << "\n\n";
std::cout << "housenumber diagnostic positions: \n";
std::cout << "\tstart_pos:" << j["address"]["housenumber"].start_pos() << '\n';
std::cout << "\tend_pos:" << j["address"]["housenumber"].end_pos() << "\n\n";
std::cout << "Original string: \n";
std::cout << "1" << "\n";
std::cout << "Parsed string: \n";
std::cout << json_string.substr(j["address"]["housenumber"].start_pos(), j["address"]["housenumber"].end_pos() - j["address"]["housenumber"].start_pos()) << "\n\n";
}
```
Output:
```
Root diagnostic positions:
start_pos: 5
end_pos:109
Original string:
{
"address": {
"street": "Fake Street",
"housenumber": 1
}
}
Parsed string:
{
"address": {
"street": "Fake Street",
"housenumber": 1
}
}
address diagnostic positions:
start_pos:26
end_pos:103
Original string:
{ "street": "Fake Street",
"housenumber": 1
}
Parsed string:
{
"street": "Fake Street",
"housenumber": 1
}
street diagnostic positions:
start_pos:50
end_pos:63
Original string:
"Fake Street"
Parsed string:
"Fake Street"
housenumber diagnostic positions:
start_pos:92
end_pos:93
Original string:
1
Parsed string:
1
```
The output shows the start/end positions of all the objects and fields in the JSON string.
## See also
- [start_pos](https://json.nlohmann.me/api/basic_json/start_pos/index.md) to access the start position
- [JSON_DIAGNOSTIC_POSITIONS](https://json.nlohmann.me/api/macros/json_diagnostic_positions/index.md) for an overview of the diagnostic positions
## Version history
- Added in version 3.12.0.
+217
View File
@@ -0,0 +1,217 @@
# <small>nlohmann::basic_json::</small>erase
```cpp
// (1)
iterator erase(iterator pos);
const_iterator erase(const_iterator pos);
// (2)
iterator erase(iterator first, iterator last);
const_iterator erase(const_iterator first, const_iterator last);
// (3)
size_type erase(const typename object_t::key_type& key);
// (4)
template<typename KeyType>
size_type erase(KeyType&& key);
// (5)
void erase(const size_type idx);
```
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 `#!json null`, the resulting JSON value will be `#!json 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 `#!json null`, the resulting JSON value will be `#!json null`.
3. Removes an element from a JSON object by key.
4. See 3. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
5. Removes an element from a JSON array by index.
## Template parameters
`KeyType`
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
This can also be a string view (C++17).
## Parameters
`pos` (in)
: iterator to the element to remove
`first` (in)
: iterator to the beginning of the range to remove
`last` (in)
: iterator past the end of the range to remove
`key` (in)
: object key of the elements to remove
`idx` (in)
: array index of the element to remove
## Return value
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)
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.307`](../../home/exceptions.md#jsonexceptiontype_error307) if called on a `null` value;
example: `"cannot use erase() with null"`
- Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) 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`](../../home/exceptions.md#jsonexceptioninvalid_iterator205) 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`](../../home/exceptions.md#jsonexceptiontype_error307) if called on a `null` value;
example: `"cannot use erase() with null"`
- Throws [`invalid_iterator.203`](../../home/exceptions.md#jsonexceptioninvalid_iterator203) if called on iterators
which does not belong to the current JSON value; example: `"iterators do not fit current value"`
- Throws [`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) 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`](../../home/exceptions.md#jsonexceptiontype_error307) 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`](../../home/exceptions.md#jsonexceptiontype_error307) when called on a type other than
JSON array; example: `"cannot use erase() with null"`
- Throws [`out_of_range.401`](../../home/exceptions.md#jsonexceptionout_of_range401) when `idx >= size()`; example:
`"array index 17 is out of range"`
## Complexity
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.
## Notes
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)
## Examples
??? example "Example: (1) remove element given an iterator"
The example shows the effect of `erase()` for different JSON types using an iterator.
```cpp
--8<-- "examples/erase__IteratorType.cpp"
```
Output:
```json
--8<-- "examples/erase__IteratorType.output"
```
??? example "Example: (2) remove elements given an iterator range"
The example shows the effect of `erase()` for different JSON types using an iterator range.
```cpp
--8<-- "examples/erase__IteratorType_IteratorType.cpp"
```
Output:
```json
--8<-- "examples/erase__IteratorType_IteratorType.output"
```
??? example "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.
```cpp
--8<-- "examples/erase__object_t_key_type.cpp"
```
Output:
```json
--8<-- "examples/erase__object_t_key_type.output"
```
??? example "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.
```cpp
--8<-- "examples/erase__keytype.c++17.cpp"
```
Output:
```json
--8<-- "examples/erase__keytype.c++17.output"
```
??? example "Example: (5) remove element from a JSON array given an index"
The example shows the effect of `erase()` using an array index.
```cpp
--8<-- "examples/erase__size_type.cpp"
```
Output:
```json
--8<-- "examples/erase__size_type.output"
```
## See also
- [clear](clear.md) clears the contents
- [insert](insert.md) add values to an array/object
- [Modifying values](../../features/modifying_values.md) - the article on modifying values
## Version history
1. Added in version 1.0.0. Added support for binary types in version 3.8.0.
2. Added in version 1.0.0. Added support for binary types in version 3.8.0.
3. Added in version 1.0.0.
4. Added in version 3.11.0.
5. Added in version 1.0.0.
File diff suppressed because one or more lines are too long
+313
View File
@@ -0,0 +1,313 @@
# nlohmann::basic_json::erase
```
// (1)
iterator erase(iterator pos);
const_iterator erase(const_iterator pos);
// (2)
iterator erase(iterator first, iterator last);
const_iterator erase(const_iterator first, const_iterator last);
// (3)
size_type erase(const typename object_t::key_type& key);
// (4)
template<typename KeyType>
size_type erase(KeyType&& key);
// (5)
void erase(const size_type idx);
```
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`.
1. 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`.
1. Removes an element from a JSON object by key.
1. 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.
1. Removes an element from a JSON array by index.
## Template parameters
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
## Parameters
`pos` (in) : iterator to the element to remove
`first` (in) : iterator to the beginning of the range to remove
`last` (in) : iterator past the end of the range to remove
`key` (in) : object key of the elements to remove
`idx` (in) : array index of the element to remove
## Return value
1. Iterator following the last removed element. If the iterator `pos` refers to the last element, the `end()` iterator is returned.
1. Iterator following the last removed element. If the iterator `last` refers to the last element, the `end()` iterator is returned.
1. 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).
1. See 3.
1. (none)
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.307`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error307) if called on a `null` value; example: `"cannot use erase() with null"`
- Throws [`invalid_iterator.202`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator202) 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`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator205) if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"`
1. The function can throw the following exceptions:
- Throws [`type_error.307`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error307) if called on a `null` value; example: `"cannot use erase() with null"`
- Throws [`invalid_iterator.203`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator203) if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"`
- Throws [`invalid_iterator.204`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator204) if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"`
1. The function can throw the following exceptions:
- Throws [`type_error.307`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error307) when called on a type other than JSON object; example: `"cannot use erase() with null"`
1. See 3.
1. The function can throw the following exceptions:
- Throws [`type_error.307`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error307) when called on a type other than JSON array; example: `"cannot use erase() with null"`
- Throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) when `idx >= size()`; example: `"array index 17 is out of range"`
## Complexity
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
1. 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
1. `log(size()) + count(key)`
1. `log(size()) + count(key)`
1. Linear in distance between `idx` and the end of the container.
## Notes
1. Invalidates iterators and references at or after the point of the `erase`, including the `end()` iterator.
1. (none)
1. References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
1. See 3.
1. (none)
## Examples
Example: (1) remove element given an iterator
The example shows the effect of `erase()` for different JSON types using an iterator.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_boolean = true;
json j_number_integer = 17;
json j_number_float = 23.42;
json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world";
// call erase()
j_boolean.erase(j_boolean.begin());
j_number_integer.erase(j_number_integer.begin());
j_number_float.erase(j_number_float.begin());
j_object.erase(j_object.find("two"));
j_array.erase(j_array.begin() + 2);
j_string.erase(j_string.begin());
// print values
std::cout << j_boolean << '\n';
std::cout << j_number_integer << '\n';
std::cout << j_number_float << '\n';
std::cout << j_object << '\n';
std::cout << j_array << '\n';
std::cout << j_string << '\n';
}
```
Output:
```
null
null
null
{"one":1}
[1,2,8,16]
null
```
Example: (2) remove elements given an iterator range
The example shows the effect of `erase()` for different JSON types using an iterator range.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_boolean = true;
json j_number_integer = 17;
json j_number_float = 23.42;
json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world";
// call erase()
j_boolean.erase(j_boolean.begin(), j_boolean.end());
j_number_integer.erase(j_number_integer.begin(), j_number_integer.end());
j_number_float.erase(j_number_float.begin(), j_number_float.end());
j_object.erase(j_object.find("two"), j_object.end());
j_array.erase(j_array.begin() + 1, j_array.begin() + 3);
j_string.erase(j_string.begin(), j_string.end());
// print values
std::cout << j_boolean << '\n';
std::cout << j_number_integer << '\n';
std::cout << j_number_float << '\n';
std::cout << j_object << '\n';
std::cout << j_array << '\n';
std::cout << j_string << '\n';
}
```
Output:
```
null
null
null
{"one":1}
[1,8,16]
null
```
Example: (3) remove element from a JSON object given a key
The example shows the effect of `erase()` for different JSON types using an object key.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON object
json j_object = {{"one", 1}, {"two", 2}};
// call erase()
auto count_one = j_object.erase("one");
auto count_three = j_object.erase("three");
// print values
std::cout << j_object << '\n';
std::cout << count_one << " " << count_three << '\n';
}
```
Output:
```
{"two":2}
1 0
```
Example: (4) remove element from a JSON object given a key using string_view
The example shows the effect of `erase()` for different JSON types using an object key.
```
#include <iostream>
#include <string_view>
#include <nlohmann/json.hpp>
using namespace std::string_view_literals;
using json = nlohmann::json;
int main()
{
// create a JSON object
json j_object = {{"one", 1}, {"two", 2}};
// call erase()
auto count_one = j_object.erase("one"sv);
auto count_three = j_object.erase("three"sv);
// print values
std::cout << j_object << '\n';
std::cout << count_one << " " << count_three << '\n';
}
```
Output:
```
{"two":2}
1 0
```
Example: (5) remove element from a JSON array given an index
The example shows the effect of `erase()` using an array index.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON array
json j_array = {0, 1, 2, 3, 4, 5};
// call erase()
j_array.erase(2);
// print values
std::cout << j_array << '\n';
}
```
Output:
```
[0,1,3,4,5]
```
## See also
- [clear](https://json.nlohmann.me/api/basic_json/clear/index.md) clears the contents
- [insert](https://json.nlohmann.me/api/basic_json/insert/index.md) add values to an array/object
- [Modifying values](https://json.nlohmann.me/features/modifying_values/index.md) - the article on modifying values
## Version history
1. Added in version 1.0.0. Added support for binary types in version 3.8.0.
1. Added in version 1.0.0. Added support for binary types in version 3.8.0.
1. Added in version 1.0.0.
1. Added in version 3.11.0.
1. Added in version 1.0.0.
+42
View File
@@ -0,0 +1,42 @@
# <small>nlohmann::basic_json::</small>error_handler_t
```cpp
enum class error_handler_t {
strict,
replace,
ignore
};
```
This enumeration is used in the [`dump`](dump.md) function to choose how to treat decoding errors while serializing a
`basic_json` value. Three values are differentiated:
strict
: throw a `type_error` exception in case of invalid UTF-8
replace
: replace invalid UTF-8 sequences with U+FFFD ( REPLACEMENT CHARACTER)
ignore
: ignore invalid UTF-8 sequences; all valid bytes are copied to the output unchanged, and invalid bytes are dropped
## Examples
??? example
The example below shows how the different values of the `error_handler_t` influence the behavior of
[`dump`](dump.md) when reading serializing an invalid UTF-8 sequence.
```cpp
--8<-- "examples/error_handler_t.cpp"
```
Output:
```json
--8<-- "examples/error_handler_t.output"
```
## Version history
- Added in version 3.4.0.
File diff suppressed because one or more lines are too long
+62
View File
@@ -0,0 +1,62 @@
# nlohmann::basic_json::error_handler_t
```
enum class error_handler_t {
strict,
replace,
ignore
};
```
This enumeration is used in the [`dump`](https://json.nlohmann.me/api/basic_json/dump/index.md) function to choose how to treat decoding errors while serializing a `basic_json` value. Three values are differentiated:
strict : throw a `type_error` exception in case of invalid UTF-8
replace : replace invalid UTF-8 sequences with U+FFFD ( REPLACEMENT CHARACTER)
ignore : ignore invalid UTF-8 sequences; all valid bytes are copied to the output unchanged, and invalid bytes are dropped
## Examples
Example
The example below shows how the different values of the `error_handler_t` influence the behavior of [`dump`](https://json.nlohmann.me/api/basic_json/dump/index.md) when reading serializing an invalid UTF-8 sequence.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON value with invalid UTF-8 byte sequence
json j_invalid = "ä\xA9ü";
try
{
std::cout << j_invalid.dump() << std::endl;
}
catch (const json::type_error& e)
{
std::cout << e.what() << std::endl;
}
std::cout << "string with replaced invalid characters: "
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
<< "\nstring with ignored invalid characters: "
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
<< '\n';
}
```
Output:
```
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
string with replaced invalid characters: "äü"
string with ignored invalid characters: "äü"
```
## Version history
- Added in version 3.4.0.
+87
View File
@@ -0,0 +1,87 @@
# <small>nlohmann::basic_json::</small>exception
```cpp
class exception : public std::exception;
```
This class is an extension of [`std::exception`](https://en.cppreference.com/w/cpp/error/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.
```mermaid
classDiagram
direction LR
class std_exception ["std::exception"] {
<<interface>>
}
class json_exception ["basic_json::exception"] {
+const int id
+const char* what() const
}
class json_parse_error ["basic_json::parse_error"] {
+const std::size_t byte
}
class json_invalid_iterator ["basic_json::invalid_iterator"]
class json_type_error ["basic_json::type_error"]
class json_out_of_range ["basic_json::out_of_range"]
class json_other_error ["basic_json::other_error"]
std_exception <|-- json_exception
json_exception <|-- json_parse_error
json_exception <|-- json_invalid_iterator
json_exception <|-- json_type_error
json_exception <|-- json_out_of_range
json_exception <|-- json_other_error
style json_exception fill:#CCCCFF
```
Subclasses:
- [`parse_error`](parse_error.md) for exceptions indicating a parse error
- [`invalid_iterator`](invalid_iterator.md) for exceptions indicating errors with iterators
- [`type_error`](type_error.md) for exceptions indicating executing a member function with a wrong type
- [`out_of_range`](out_of_range.md) for exceptions indicating access out of the defined range
- [`other_error`](other_error.md) for exceptions indicating other library errors
## Member functions
- **what** - returns explanatory string
## Member variables
- **id** - the id of the exception
## Notes
To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with
arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual
constructor.
## Examples
??? example
The following code shows how arbitrary library exceptions can be caught.
```cpp
--8<-- "examples/exception.cpp"
```
Output:
```json
--8<-- "examples/exception.output"
```
## See also
[List of exceptions](../../home/exceptions.md)
## Version history
- Since version 3.0.0.
File diff suppressed because one or more lines are too long
+103
View File
@@ -0,0 +1,103 @@
# nlohmann::basic_json::exception
```
class exception : public std::exception;
```
This class is an extension of [`std::exception`](https://en.cppreference.com/w/cpp/error/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
direction LR
class std_exception ["std::exception"] {
<<interface>>
}
class json_exception ["basic_json::exception"] {
+const int id
+const char* what() const
}
class json_parse_error ["basic_json::parse_error"] {
+const std::size_t byte
}
class json_invalid_iterator ["basic_json::invalid_iterator"]
class json_type_error ["basic_json::type_error"]
class json_out_of_range ["basic_json::out_of_range"]
class json_other_error ["basic_json::other_error"]
std_exception <|-- json_exception
json_exception <|-- json_parse_error
json_exception <|-- json_invalid_iterator
json_exception <|-- json_type_error
json_exception <|-- json_out_of_range
json_exception <|-- json_other_error
style json_exception fill:#CCCCFF
```
Subclasses:
- [`parse_error`](https://json.nlohmann.me/api/basic_json/parse_error/index.md) for exceptions indicating a parse error
- [`invalid_iterator`](https://json.nlohmann.me/api/basic_json/invalid_iterator/index.md) for exceptions indicating errors with iterators
- [`type_error`](https://json.nlohmann.me/api/basic_json/type_error/index.md) for exceptions indicating executing a member function with a wrong type
- [`out_of_range`](https://json.nlohmann.me/api/basic_json/out_of_range/index.md) for exceptions indicating access out of the defined range
- [`other_error`](https://json.nlohmann.me/api/basic_json/other_error/index.md) for exceptions indicating other library errors
## Member functions
- **what** - returns explanatory string
## Member variables
- **id** - the id of the exception
## Notes
To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.
## Examples
Example
The following code shows how arbitrary library exceptions can be caught.
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling at() for a non-existing key
json j = {{"foo", "bar"}};
json k = j.at("non-existing");
}
catch (const json::exception& e)
{
// output exception information
std::cout << "message: " << e.what() << '\n'
<< "exception id: " << e.id << std::endl;
}
}
```
Output:
```
message: [json.exception.out_of_range.403] key 'non-existing' not found
exception id: 403
```
## See also
[List of exceptions](https://json.nlohmann.me/home/exceptions/index.md)
## Version history
- Since version 3.0.0.
+87
View File
@@ -0,0 +1,87 @@
# <small>nlohmann::basic_json::</small>find
```cpp
// (1)
iterator find(const typename object_t::key_type& key);
const_iterator find(const typename object_t::key_type& key) const;
// (2)
template<typename KeyType>
iterator find(KeyType&& key);
template<typename KeyType>
const_iterator find(KeyType&& key) const;
```
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 `#!cpp typename object_t::key_type` and
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
## Template parameters
`KeyType`
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
This can also be a string view (C++17).
## Parameters
`key` (in)
: key value of the element to search for.
## Return value
Iterator to an element with a key equivalent to `key`. If no such element is found or the JSON value is not an object,
a past-the-end iterator (see `end()`) is returned.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
Logarithmic in the size of the JSON object.
## Notes
This method always returns `end()` when executed on a JSON type that is not an object.
## Examples
??? example "Example: (1) find object element by key"
The example shows how `find()` is used.
```cpp
--8<-- "examples/find__object_t_key_type.cpp"
```
Output:
```json
--8<-- "examples/find__object_t_key_type.output"
```
??? example "Example: (2) find object element by key using string_view"
The example shows how `find()` is used.
```cpp
--8<-- "examples/find__keytype.c++17.cpp"
```
Output:
```json
--8<-- "examples/find__keytype.c++17.output"
```
## See also
- [count](count.md) returns the number of occurrences of a key
- [contains](contains.md) checks whether a key exists
## Version history
1. Added in version 3.11.0.
2. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More