📝 add more API documentation

This commit is contained in:
Niels Lohmann 2020-08-12 13:41:59 +02:00
parent b888afe5f4
commit fe89049aee
No known key found for this signature in database
GPG Key ID: 7F3CEA63AE251B69
78 changed files with 5092 additions and 177 deletions

View File

@ -9,7 +9,7 @@ prepare_files: clean
# create subfolders
mkdir docs/images docs/examples
# copy images
cp -vr ../json.gif ../images/range-begin-end.svg ../images/range-rbegin-rend.svg docs/images
cp -vr ../json.gif ../images/range-begin-end.svg ../images/range-rbegin-rend.svg ../images/callback_events.png docs/images
# copy examples
cp -vr ../examples/*.cpp ../examples/*.output docs/examples

View File

@ -0,0 +1,88 @@
# basic_json::accept
```cpp
// (1)
template<typename InputType>
static bool accept(InputType&& i,
const bool ignore_comments = false);
// (2)
static bool accept(iterator first, iterator last,
const bool ignore_comments = false);
static bool accept(const_iterator first, const_iterator last,
const bool ignore_comments = 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 a integral type with size of 1, 2 or 4 bytes, which will be interpreted
respectively as UTF-8, UTF-16 and UTF-32.
Unlike the [`parse`](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 `FILE` pointer
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators.
## 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)
`first` (in)
: iterator to start of character range
`last` (in)
: iterator to end of 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.
## Complexity
Linear in the length of the input. The parser is a predictive LL(1) parser.
## Notes
(1) 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"
```
## Version history
- Added in version 3.0.0.
- Ignoring comments via `ignore_comments` added in version 3.9.0.

View File

@ -0,0 +1,55 @@
# basic_json::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"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,52 @@
# basic_json::array_t
```cpp
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
```
The type used to store JSON arrays.
[RFC 7159](http://rfc7159.net/rfc7159) 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 7159](http://rfc7159.net/rfc7159) 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.
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,171 @@
# basic_json::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)
reference at(const json_pointer& ptr);
const_reference at(const json_pointer& ptr) const;
```
1. Returns a reference to the element at specified location `idx`, with bounds checking.
2. Returns a reference to the element at with specified key `key`, with bounds checking.
3. Returns a reference to the element at with specified JSON pointer `ptr`, with bounds checking.
## Parameters
`idx` (in)
: index of the element to access
`key` (in)
: object key of the elements to remove
`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 pointed to by `ptr`
## 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 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 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 example below.
- Throws [`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if the key `key` is is not
stored in the object; that is, `find(key) == end()`. See example below.
3. 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 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 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 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 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 example below.
- Throws [`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) if the JSON pointer `ptr` can
not be resolved. See example below.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
1. Constant
2. Logarithmic in the size of the container.
3. Constant
## Example
??? example
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
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
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
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
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
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"
```
## Version history
1. Added in version 1.0.0.
2. Added in version 1.0.0.
3. Added in version 2.0.0.

View File

@ -0,0 +1,61 @@
# basic_json::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 case of a structured type (array or object), a reference to the last element is returned. In case of number, string,
boolean, or binary values, a reference to the value is returned.
## Exceptions
If the JSON value is `#!json null`, exception
[`invalid_iterator.214`](../../home/exceptions.md#jsonexceptioninvalid_iterator214) is thrown.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Constant.
## Note
!!! danger
Calling `back` on an empty array or object is undefined behavior and is **guarded by an assertion**!
## Example
??? example
The following code shows an example for `back()`.
```cpp
--8<-- "examples/back.cpp"
```
Output:
```json
--8<-- "examples/back.output"
```
## Version history
- Added in version 1.0.0.
- Adjusted code to return reference to binary values in version 3.8.0.

View File

@ -0,0 +1,394 @@
# basic_json::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
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 JSON object type, so interpreting it as JSON
array type is safe.
With the rules described above, the following JSON values cannot be expressed by an initializer list:
- the empty array (`#!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
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 depends 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`.
## 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)
: begin of the range to copy from (included)
`last` (in)
: end of the range to copy from (excluded)
`other` (in)
: the JSON value to copy/move
## Exceptions
1. /
2. The function does not throw exceptions.
3. /
4. /
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. /
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 any more. In this case, the range `[first, last)` is undefined. See 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. /
9. The function does not throw exceptions.
## 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), 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), 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.
## 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
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 an assertion (see
warning).** If assertions are switched off, a violation of this precondition yields undefined behavior.
- 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.
!!! warning
A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this
precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See
<https://en.cppreference.com/w/cpp/error/assert> for more information.
- 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
## Example
??? example
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
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
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"
```
??? example
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
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
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
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
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.

View File

@ -0,0 +1,42 @@
# basic_json::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.
## Example
??? 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.

View File

@ -0,0 +1,50 @@
# basic_json::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 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.
## Version history
- Added in version 3.8.0.

View File

@ -0,0 +1,26 @@
# basic_json::boolean_t
```cpp
using boolean_t = BooleanType;
```
The type used to store JSON booleans.
[RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a type which differentiates the two literals
`#!json true` and `#!json false`.
To store objects 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.
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,41 @@
# basic_json::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.
## Example
??? 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.

View File

@ -0,0 +1,41 @@
# basic_json::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.
## Example
??? 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.

View File

@ -0,0 +1,58 @@
# basic_json::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.
## Example
??? 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.

View File

@ -0,0 +1,56 @@
# basic_json::contains
```cpp
template<typename KeyT>
bool contains(KeyT && key) const;
```
Check whether an element exists in a JSON object with key equivalent to `key`. If the element is not found or the JSON
value is not an object, `#!cpp false` is returned.
## Template parameters
`KeyT`
: A type for an object key other than `basic_json::json_pointer`.
## Parameters
`key` (in)
: key value to check its existence.
## Return value
`#!cpp true` if an element with specified `key` exists. If no such element with such key is found or the JSON value is
not an object, `#!cpp false` 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 `#!cpp false` when executed on a JSON type that is not an object.
## Example
??? example
The example shows how `contains()` is used.
```cpp
--8<-- "examples/contains.cpp"
```
Output:
```json
--8<-- "examples/contains.output"
```
## Version history
- Added in version 3.6.0.

View File

@ -0,0 +1,55 @@
# basic_json::count
```cpp
template<typename KeyT>
size_type count(KeyT&& key) const;
```
Returns the number of elements with key `key`. If `ObjectType` is the default `std::map` type, the return value will
always be `0` (`key` was not found) or `1` (`key` was found).
## Template parameters
`KeyT`
: A type for an object key.
## 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.
## Example
??? example
The example shows how `count()` is used.
```cpp
--8<-- "examples/count.cpp"
```
Output:
```json
--8<-- "examples/count.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,41 @@
# basic_json::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 first element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? 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.

View File

@ -0,0 +1,42 @@
# basic_json::rend
```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.
## Example
??? example
The following code shows an example for `eend()`.
```cpp
--8<-- "examples/crend.cpp"
```
Output:
```json
--8<-- "examples/crend.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,58 @@
# basic_json::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`.
## Note
Currently, only `remove`, `add`, and `replace` operations are generated.
## Example
??? 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"
```
## Version history
- Added in version 2.0.0.

View File

@ -4,36 +4,30 @@
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
const error_handler_t error_handler = error_handler_t::strict) const;
```
Serialization function for JSON values. The function tries to mimic
Python's `json.dumps()` function, and currently supports its `indent`
and `ensure_ascii` parameters.
Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently
supports its `indent` and `ensure_ascii` parameters.
## Parameters
`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.
: 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).
: 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.
: 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: `strict` (throws and exception in case a decoding error
occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
and `ignore` (ignore invalid UTF-8 sequences during serialization; all
bytes are copied to the output unchanged).
: how to react on decoding errors; there are three possible values (see [`error_handler_t`](error_handler_t.md):
`strict` (throws and exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences
with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output
unchanged).
## Return value
@ -41,8 +35,7 @@ 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.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
## Complexity
@ -59,9 +52,8 @@ Binary values are serialized as object containing two keys:
??? example
The following example shows the effect of different `indent`,
`indent_char`, and `ensure_ascii` parameters to the result of the
serialization.
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"

View File

@ -0,0 +1,56 @@
# basic_json::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
## 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.
## 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"
```
## Version history
- Since version 2.0.8.

View File

@ -0,0 +1,54 @@
# basic_json::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
## 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"
```
## Version history
- Since version 2.0.8.
- Returns reference since 3.7.0.

View File

@ -0,0 +1,66 @@
# basic_json::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.
## Example
??? 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.

View File

@ -0,0 +1,42 @@
# basic_json::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.
## Example
??? 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.

View File

@ -0,0 +1,177 @@
# basic_json::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)
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. Removes an element from a JSON array by index.
## 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. /
## 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 thw 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 thw 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. The function can throw thw 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"`
- Throws [`out_of_range.401`](../../home/exceptions.md#jsonexceptionout_of_range401) when `idx >= size()`; example:
`"array index 17 is out of range"`
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## 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. 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. /
3. References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
4. /
## Example
??? example
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
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
The example shows the effect of `erase()` for different JSON types using an object key.
```cpp
--8<-- "examples/erase__key_type.cpp"
```
Output:
```json
--8<-- "examples/erase__key_type.output"
```
??? example
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"
```
## Version history
- Added in version 1.0.0.
- Added support for binary types in version 3.8.0.

View File

@ -0,0 +1,25 @@
# basic_json::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 (<28> REPLACEMENT CHARACTER)
ignore
: ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged
## Version history
- Added in version 3.4.0.

View File

@ -0,0 +1,59 @@
# basic_json::find
```cpp
template<typename KeyT>
iterator find(KeyT&& key);
template<typename KeyT>
const_iterator find(KeyT&& key) const
```
Finds an element in a JSON object with key equivalent to `key`. If the element is not found or the JSON value is not an
object, `end()` is returned.
## Template parameters
`KeyT`
: A type for an object key.
## Parameters
`key` (in)
: key value of the element to search for.
## Return value
Iterator to an element with key equivalent to `key`. If no such element is found or the JSON value is not an object,
past-the-end (see `end()`) iterator 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.
## Example
??? example
The example shows how `find()` is used.
```cpp
--8<-- "examples/find__key_type.cpp"
```
Output:
```json
--8<-- "examples/find__key_type.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,46 @@
# basic_json::flatten
```cpp
basic_json flatten() const;
```
The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901))
and whose values are all primitive (see [`is_primitive()`](is_primitive.md) for more information). The original JSON
value can be restored using the [`unflatten()`](unflatten.md) function.
## Return value
an object that maps JSON pointers to primitive values
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
Linear in the size the JSON value.
## Notes
Empty objects and arrays are flattened to `#!json null` and will not be reconstructed correctly by the
[`unflatten()`](unflatten.md) function.
## Example
??? example
The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.
```cpp
--8<-- "examples/flatten.cpp"
```
Output:
```json
--8<-- "examples/flatten.output"
```
## Version history
- Added in version 2.0.0.

View File

@ -0,0 +1,54 @@
# basic_json::front
```cpp
reference front();
const_reference front() const;
```
Returns a reference to the first element in the container. For a JSON container `#!cpp c`, the expression
`#!cpp c.front()` is equivalent to `#!cpp *c.begin()`.
## Return value
In case of a structured type (array or object), a reference to the first element is returned. In case of number, string,
boolean, or binary values, a reference to the value is returned.
## Exceptions
If the JSON value is `#!json null`, exception
[`invalid_iterator.214`](../../home/exceptions.md#jsonexceptioninvalid_iterator214) is thrown.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Constant.
## Note
!!! danger
Calling `front` on an empty array or object is undefined behavior and is **guarded by an assertion**!
## Example
??? example
The following code shows an example for `front()`.
```cpp
--8<-- "examples/front.cpp"
```
Output:
```json
--8<-- "examples/front.output"
```
## Version history
- Added in version 1.0.0.
- Adjusted code to return reference to binary values in version 3.8.0.

View File

@ -7,14 +7,19 @@
Defined in header `<json.hpp>`
```cpp
template<template<typename, typename, typename...> class ObjectType,
template<typename, typename...> class ArrayType,
class StringType, class BooleanType, class NumberIntegerType,
class NumberUnsignedType, class NumberFloatType,
template<typename> class AllocatorType,
template<typename, typename = void> class JSONSerializer,
class BinaryType>
class basic_json
template<
template<typename U, typename V, typename... Args> class ObjectType = std::map,
template<typename U, typename... Args> class ArrayType = std::vector,
class StringType = std::string,
class BooleanType = bool,
class NumberIntegerType = std::int64_t,
class NumberUnsignedType = std::uint64_t,
class NumberFloatType = double,
template<typename U> class AllocatorType = std::allocator,
template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,
class BinaryType = std::vector<std::uint8_t>
>
class basic_json;
```
## Specializations
@ -24,25 +29,29 @@ class basic_json
## Template parameters
- ObjectType
- ArrayType
- StringType
- BooleanType
- NumberIntegerType
- NumberUnsignedType
- NumberFloatType
- AllocatorType
- JSONSerializer
- BinaryType
| 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` |
| `BooleanType` | type for JSON booleans | `boolean_t` |
| `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()` | |
| `BinaryType` | type for binary arrays | `binary_t` |
## Iterator invalidation
Todo
## Member types
- value_t
- [**value_t**](value_t.md) - the JSON type enumeration
- json_pointer
- json_serializer
- error_handler_t
- [**error_handler_t**](error_handler_t.md) - type to choose behavior on decoding errors
- cbor_tag_handler_t
- initializer_list_t
- input_format_t
@ -59,64 +68,68 @@ class basic_json
### Container types
- value_type
- reference
- const_reference
- difference_type
- size_type
- allocator_type
- pointer
- const_pointer
- iterator
- const_iterator
- reverse_iterator
- const_reverse_iterator
| 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 | |
| const_reverse_iterator | |
| iteration_proxy | |
### JSON value data types
- object_comparator_t
- object_t
- array_t
- string_t
- boolean_t
- number_integer_t
- number_unsigned_t
- number_float_t
- [**object_t**](object_t.md) - type for objects
- [**array_t**](array_t.md) - type for arrays
- [**string_t**](string_t.md) - type for strings
- [**boolean_t**](boolean_t.md) - type for booleans
- [**number_integer_t**](number_integer_t.md) - type for numbers (integer)
- [**number_unsigned_t**](number_unsigned_t.md) - type for numbers (unsigned)
- [**number_float_t**](number_float_t.md) - type for numbers (floating-point)
- binary_t
### Parser callback
- parse_event_t
- parser_callback_t
- [**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)
- (destructor)
- binary (static) - explicitly create a binary array
- array (static) - explicitly create an array
- object (static) - explicitly create an object
- operator= - copy assignment
- [(constructor)](basic_json.md)
- [(destructor)](~basic_json.md)
- [**operator=**](operator=.md) - copy assignment
- [**array**](array_t.md) (static) - explicitly create an array
- [**binary**](binary.md) (static) - explicitly create a binary array
- [**object**](object_t.md) (static) - explicitly create an object
### Object inspection
Functions to inspect the type of a JSON value.
- type - return the type of the JSON value
- is_primitive - return whether type is primitive
- is_structured - return whether type is structured
- is_null - return whether value is null
- is_boolean - return whether value is a boolean
- is_number - return whether value is a number
- is_number_integer - return whether value is an integer number
- is_number_unsigned - return whether value is an unsigned integer number
- is_number_float - return whether value is a floating-point number
- is_object - return whether value is an object
- is_array - return whether value is an array
- is_string - return whether value is a string
- is_binary - return whether value is a binary array
- is_discarded - return whether value is discarded
- operator value_t - return the type of the 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 type is primitive
- [**is_structured**](is_structured.md) - return whether type is structured
- [**is_null**](is_null.md) - return whether value is null
- [**is_boolean**](is_boolean.md) - return whether value is a boolean
- [**is_number**](is_number.md) - return whether value is a number
- [**is_number_integer**](is_number_integer.md) - return whether value is an integer number
- [**is_number_unsigned**](is_number_unsigned.md) - return whether value is an unsigned integer number
- [**is_number_float**](is_number_float.md) - return whether value is a floating-point number
- [**is_object**](is_object.md) - return whether value is an object
- [**is_array**](is_array.md) - return whether value is an array
- [**is_string**](is_string.md) - return whether value is a string
- [**is_binary**](is_binary.md) - return whether value is a binary array
- [**is_discarded**](is_discarded.md) - return whether value is discarded
### Value access
@ -133,56 +146,52 @@ Direct access to the stored value of a JSON value.
Access to the JSON value
- at - access specified array element with bounds checking
- at - access specified object element with bounds checking
- operator[] - access specified array element
- operator[] - access specified object element
- value - access specified object element with default value
- front - access the first element
- back - access the last element
- erase - remove elements
- [**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 an element in a JSON object
- count - returns the number of occurrences of a key in a JSON object
- contains - check the existence of an element in a JSON object
- [**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 - returns an iterator to the first element
- cbegin - returns a const iterator to the first element
- end - returns an iterator to one past the last element
- cend - returns a const iterator to one past the last element
- rbegin - returns an iterator to the reverse-beginning
- rend - returns an iterator to the reverse-end
- crbegin - returns a const iterator to the reverse-beginning
- crend - returns a const iterator to the reverse-end
- items - wrapper to access iterator member functions in range-based for
- [**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 - checks whether the container is empty
- size - returns the number of elements
- max_size - returns the maximum possible number of elements
- [**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 - clears the contents
- push_back - add an object to an array
- operator+= - add an object to an array
- push_back - add an object to an object
- operator+= - add an object to an object
- emplace_back - add an object to an array
- emplace - add an object to an object if key does not exist
- insert - inserts element
- update - updates a JSON object from another object, overwriting existing keys
- [**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 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 - exchanges the values
### Lexicographical comparison operators
- operator== - comparison: equal
- operator!= - comparison: not equal
- [**operator==**](operator==.md) - comparison: equal
- [**operator!=**](operator!=.md) - comparison: not equal
- operator< - comparison: less than
- operator<= - comparison: less than or equal
- operator> - comparison: greater than
@ -196,29 +205,22 @@ Access to the JSON value
### Deserialization
- [**parse**](parse.md) - deserialize from a compatible input
- accept - check if the input is valid JSON
- sax_parse - generate SAX events
### Convenience functions
- type_name - return the type as string
- [**accept**](accept.md) - check if the input is valid JSON
- [**sax_parse**](sax_parse.md) - generate SAX events
### JSON Pointer functions
- at - access specified object element with bounds checking via JSON Pointer
- operator[] - access specified element via JSON Pointer
- value - access specified object element with default value via JSON Pointer
- flatten - return flattened JSON value
- unflatten - unflatten a previously flattened JSON value
- [**flatten**](flatten.md) - return flattened JSON value
- [**unflatten**](unflatten.md) - unflatten a previously flattened JSON value
### JSON Patch functions
- patch - applies a JSON patch
- diff (static) - creates a diff as a JSON patch
- [**patch**](patch.md) - applies a JSON patch
- [**diff**](diff.md) (static) - creates a diff as a JSON patch
### JSON Merge Patch functions
- merge_patch - applies a JSON Merge Patch
- [**merge_patch**](merge_patch.md) - applies a JSON Merge Patch
## Static functions

View File

@ -0,0 +1,179 @@
# basic_json::insert
```cpp
// (1)
iterator insert(const_iterator pos, const basic_json& val);
iterator insert(const_iterator pos, basic_json&& val);
// (2)
iterator insert(const_iterator pos, size_type cnt, const basic_json& val);
// (3)
iterator insert(const_iterator pos, const_iterator first, const_iterator last);
// (4)
iterator insert(const_iterator pos, initializer_list_t ilist);
// (5)
void insert(const_iterator first, const_iterator last);
```
1. Inserts element `val` to array before iterator `pos`.
2. Inserts `cnt` copies of `val` to array before iterator `pos`.
3. Inserts elements from range `[first, last)` to array before iterator `pos`.
4. Inserts elements from initializer list `ilist` to array before iterator `pos`.
5. Inserts elements from range `[first, last)` to object.
## Parameters
`pos` (in)
: iterator before which the content will be inserted; may be the `end()` iterator
`val` (in)
: value to insert
`cnt` (in)
: number of copies of `val` to insert
`first` (in)
: begin of the range of elements to insert
`last` (in)
: end of the range of elements to insert
`ilist` (in)
: initializer list to insert the values from
## Return value
1. iterator pointing to the inserted `val`.
2. iterator pointing to the first element inserted, or `pos` if `#!cpp cnt==0`
3. iterator pointing to the first element inserted, or `pos` if `#!cpp first==last`
4. iterator pointing to the first element inserted, or `pos` if `ilist` is empty
5. /
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
arrays; example: `"cannot use insert() with string"`
- 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"`
2. The function can throw thw following exceptions:
- Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
arrays; example: `"cannot use insert() with string"`
- 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"`
3. The function can throw thw following exceptions:
- Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
arrays; example: `"cannot use insert() with string"`
- 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.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last`
do not belong to the same JSON value; example: `"iterators do not fit"`
- Throws [`invalid_iterator.211`](../../home/exceptions.md#jsonexceptioninvalid_iterator211) if `first` or `last`
are iterators into container for which insert is called; example: `"passed iterators may not belong to container"`
4. The function can throw thw following exceptions:
- Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
arrays; example: `"cannot use insert() with string"`
- 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"`
5. The function can throw thw following exceptions:
- Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than
objects; example: `"cannot use insert() with string"`
- 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.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last`
do not belong to the same JSON value; example: `"iterators do not fit"`
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
1. Constant plus linear in the distance between `pos` and end of the container.
2. Linear in `cnt` plus linear in the distance between `pos` and end of the container.
3. Linear in `#!cpp std::distance(first, last)` plus linear in the distance between `pos` and end of the container.
4. Linear in `ilist.size()` plus linear in the distance between `pos` and end of the container.
5. Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert.
## Example
??? example
The example shows how `insert()` is used.
```cpp
--8<-- "examples/insert.cpp"
```
Output:
```json
--8<-- "examples/insert.output"
```
??? example
The example shows how `insert()` is used.
```cpp
--8<-- "examples/insert__count.cpp"
```
Output:
```json
--8<-- "examples/insert__count.output"
```
??? example
The example shows how `insert()` is used.
```cpp
--8<-- "examples/insert__range.cpp"
```
Output:
```json
--8<-- "examples/insert__range.output"
```
??? example
The example shows how `insert()` is used.
```cpp
--8<-- "examples/insert__ilist.cpp"
```
Output:
```json
--8<-- "examples/insert__ilist.output"
```
??? example
The example shows how `insert()` is used.
```cpp
--8<-- "examples/insert__range_object.cpp"
```
Output:
```json
--8<-- "examples/insert__range_object.output"
```
## Version history
1. Added in version 1.0.0.
2. Added in version 1.0.0.
3. Added in version 1.0.0.
4. Added in version 1.0.0.
5. Added in version 3.0.0.

View File

@ -0,0 +1,39 @@
# basic_json::is_array
```cpp
constexpr bool is_array() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is an array.
## Return value
`#!cpp true` if type is an array, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_array()` for all JSON types.
```cpp
--8<-- "examples/is_array.cpp"
```
Output:
```json
--8<-- "examples/is_array.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,39 @@
# basic_json::is_binary
```cpp
constexpr bool is_binary() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is binary array.
## Return value
`#!cpp true` if type is binary, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_binary()` for all JSON types.
```cpp
--8<-- "examples/is_binary.cpp"
```
Output:
```json
--8<-- "examples/is_binary.output"
```
## Version history
- Added in version 3.8.0.

View File

@ -0,0 +1,39 @@
# basic_json::is_boolean
```cpp
constexpr bool is_boolean() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is `#!json true` or `#!json false`.
## Return value
`#!cpp true` if type is boolean, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_boolean()` for all JSON types.
```cpp
--8<-- "examples/is_boolean.cpp"
```
Output:
```json
--8<-- "examples/is_boolean.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,45 @@
# basic_json::is_discarded
```cpp
constexpr bool is_discarded() const noexcept;
```
This function returns true if and only if the JSON value was discarded during parsing with a callback function (see
[`parser_callback_t`](parser_callback_t.md)).
## Return value
`#!cpp true` if type is discarded, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Notes
This function will always be `#!cpp false` for JSON values after parsing. That is, discarded values can only occur
during parsing, but will be removed when inside a structured value or replaced by null in other cases.
## Example
??? example
The following code exemplifies `is_discarded()` for all JSON types.
```cpp
--8<-- "examples/is_discarded.cpp"
```
Output:
```json
--8<-- "examples/is_discarded.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,39 @@
# basic_json::is_null
```cpp
constexpr bool is_null() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is `#!json null`.
## Return value
`#!cpp true` if type is `#!json null`, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_null()` for all JSON types.
```cpp
--8<-- "examples/is_null.cpp"
```
Output:
```json
--8<-- "examples/is_null.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,50 @@
# basic_json::is_number
```cpp
constexpr bool is_number() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is a number. This includes both integer (signed and
unsigned) and floating-point values.
## Return value
`#!cpp true` if type is number (regardless whether integer, unsigned integer or floating-type), `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Possible implementation
```cpp
constexpr bool is_number() const noexcept
{
return is_number_integer() || is_number_float();
}
```
## Example
??? example
The following code exemplifies `is_number()` for all JSON types.
```cpp
--8<-- "examples/is_number.cpp"
```
Output:
```json
--8<-- "examples/is_number.output"
```
## Version history
- Added in version 1.0.0.
- Extended to also return `#!cpp true` for unsigned integers in 2.0.0.

View File

@ -0,0 +1,40 @@
# basic_json::is_number_float
```cpp
constexpr bool is_number_float() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is a floating-point number. This excludes signed and
unsigned integer values.
## Return value
`#!cpp true` if type is a floating-point number, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_number_float()` for all JSON types.
```cpp
--8<-- "examples/is_number_float.cpp"
```
Output:
```json
--8<-- "examples/is_number_float.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,41 @@
# basic_json::is_number_integer
```cpp
constexpr bool is_number_integer() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is a signed or unsigned integer number. This excludes
floating-point values.
## Return value
`#!cpp true` if type is an integer or unsigned integer number, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_number_integer()` for all JSON types.
```cpp
--8<-- "examples/is_number_integer.cpp"
```
Output:
```json
--8<-- "examples/is_number_integer.output"
```
## Version history
- Added in version 1.0.0.
- Extended to also return `#!cpp true` for unsigned integers in 2.0.0.

View File

@ -0,0 +1,40 @@
# basic_json::is_number_unsigned
```cpp
constexpr bool is_number_unsigned() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is an unsigned integer number. This excludes
floating-point and signed integer values.
## Return value
`#!cpp true` if type is an unsigned integer number, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_number_unsigned()` for all JSON types.
```cpp
--8<-- "examples/is_number_unsigned.cpp"
```
Output:
```json
--8<-- "examples/is_number_unsigned.output"
```
## Version history
- Added in version 2.0.0.

View File

@ -0,0 +1,39 @@
# basic_json::is_object
```cpp
constexpr bool is_object() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is an object.
## Return value
`#!cpp true` if type is an object, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_object()` for all JSON types.
```cpp
--8<-- "examples/is_object.cpp"
```
Output:
```json
--8<-- "examples/is_object.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,60 @@
# basic_json::is_primitive
```cpp
constexpr bool is_primitive() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON type is primitive (string, number, boolean, `#!json null`,
binary).
## Return value
`#!cpp true` if type is primitive (string, number, boolean, `#!json null`, or binary), `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Possible implementation
```cpp
constexpr bool is_primitive() const noexcept
{
return is_null() || is_string() || is_boolean() || is_number() || is_binary();
}
```
## Notes
The term *primitive* stems from [RFC 8259](https://tools.ietf.org/html/rfc8259):
> JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and
> arrays).
This library extends primitive types to binary types, because binary types are roughly comparable to strings. Hence,
`is_primitive()` returns `#!cpp true` for binary values.
## Example
??? example
The following code exemplifies `is_primitive()` for all JSON types.
```cpp
--8<-- "examples/is_primitive.cpp"
```
Output:
```json
--8<-- "examples/is_primitive.output"
```
## Version history
- Added in version 1.0.0.
- Extended to return `#!cpp true` for binary types in version 3.8.0.

View File

@ -0,0 +1,39 @@
# basic_json::is_string
```cpp
constexpr bool is_string() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON value is a string.
## Return value
`#!cpp true` if type is a string, `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `is_string()` for all JSON types.
```cpp
--8<-- "examples/is_string.cpp"
```
Output:
```json
--8<-- "examples/is_string.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,48 @@
# basic_json::is_structured
```cpp
constexpr bool is_structured() const noexcept;
```
This function returns `#!cpp true` if and only if the JSON type is structured (array or object).
## Return value
`#!cpp true` if type is structured (array or object), `#!cpp false` otherwise.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Notes
The term *structured* stems from [RFC 8259](https://tools.ietf.org/html/rfc8259):
> JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and
> arrays).
Note that though strings are containers in C++, they are treated as primitive values in JSON.
## Example
??? example
The following code exemplifies `is_structured()` for all JSON types.
```cpp
--8<-- "examples/is_structured.cpp"
```
Output:
```json
--8<-- "examples/is_structured.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,96 @@
# basic_json::items
```cpp
iteration_proxy<iterator> items() noexcept;
iteration_proxy<const_iterator> items() const noexcept;
```
This function allows to access `iterator::key()` and `iterator::value()` during range-based for loops. In these loops, a
reference to the JSON values is returned, so there is no access to the underlying iterator.
For loop without `items()` function:
```cpp
for (auto it = j_object.begin(); it != j_object.end(); ++it)
{
std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
}
```
Range-based for loop without `items()` function:
```cpp
for (auto it : j_object)
{
// "it" is of type json::reference and has no key() member
std::cout << "value: " << it << '\n';
}
```
Range-based for loop with `items()` function:
```cpp
for (auto& el : j_object.items())
{
std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
}
```
The `items()` function also allows to use
[structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17):
```cpp
for (auto& [key, val] : j_object.items())
{
std::cout << "key: " << key << ", value:" << val << '\n';
}
```
## Return value
iteration proxy object wrapping the current value with an interface to use in range-based for loops
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Constant.
## Notes
When iterating over an array, `key()` will return the index of the element as string (see example). For primitive types
(e.g., numbers), `key()` returns an empty string.
!!! warning
Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exeeds the iteration. See
<https://github.com/nlohmann/json/issues/2040> for more information.
## Example
??? example
The following code shows an example for `items()`.
```cpp
--8<-- "examples/items.cpp"
```
Output:
```json
--8<-- "examples/items.output"
```
## Version history
- Added in version 3.0.0.
- Added structured binding support in version 3.5.0.
!!! note
This function replaces the static function `iterator_wrapper` which was introduced in version 1.0.0, but has been
deprecated in version 3.1.0. Function `iterator_wrapper` will be removed in version 4.0.0. Please replace all
occurrences of `#!cpp iterator_wrapper(j)` with `#!cpp j.items()`.

View File

@ -0,0 +1,58 @@
# basic_json::max_size
```cpp
size_type max_size() const noexcept;
```
Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations,
i.e. `std::distance(begin(), end())` for the JSON value.
## Return value
The return value depends on the different types and is defined as follows:
Value type | return value
----------- | -------------
null | `0` (same as [`size()`](size.md))
boolean | `1` (same as [`size()`](size.md))
string | `1` (same as [`size()`](size.md))
number | `1` (same as [`size()`](size.md))
binary | `1` (same as [`size()`](size.md))
object | result of function `object_t::max_size()`
array | result of function `array_t::max_size()`
## 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 `max_size()` functions have
constant complexity.
## Notes
This function does not return the maximal length of a string stored as JSON value -- it returns the maximal number of
string elements the JSON value can store which is `1`.
## Example
??? example
The following code calls `max_size()` on the different value types. Note the output is implementation specific.
```cpp
--8<-- "examples/max_size.cpp"
```
Output:
```json
--8<-- "examples/max_size.output"
```
## Version history
- Added in version 1.0.0.
- Extended to return `1` for binary types in version 3.8.0.

View File

@ -0,0 +1,58 @@
# basic_json::merge_patch
```cpp
void merge_patch(const basic_json& apply_patch);
```
The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of
modifications to a target resource's content. This function applies a merge patch to the current JSON value.
The function implements the following algorithm from Section 2 of
[RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
```python
define MergePatch(Target, Patch):
if Patch is an Object:
if Target is not an Object:
Target = {} // Ignore the contents and set it to an empty Object
for each Name/Value pair in Patch:
if Value is null:
if Name exists in Target:
remove the Name/Value pair from Target
else:
Target[Name] = MergePatch(Target[Name], Value)
return Target
else:
return Patch
```
Thereby, `Target` is the current object; that is, the patch is applied to the current value.
## Parameters
`apply_patch` (in)
: the patch to apply
## Complexity
Linear in the lengths of `apply_patch`.
## Example
??? example
The following code shows how a JSON Merge Patch is applied to a JSON document.
```cpp
--8<-- "examples/merge_patch.cpp"
```
Output:
```json
--8<-- "examples/merge_patch.output"
```
## Version history
- Added in version 3.0.0.

View File

@ -4,8 +4,8 @@
static basic_json meta();
```
This function returns a JSON object with information about the library,
including the version number and information on the platform and compiler.
This function returns a JSON object with information about the library, including the version number and information on
the platform and compiler.
## Return value
@ -22,8 +22,7 @@ key | description
## Exception safety
Strong guarantee: if an exception is thrown, there are no
changes to any JSON value.
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
## Complexity
@ -43,3 +42,7 @@ Output:
```json
--8<-- "examples/meta.output"
```
## Version history
- Added in version 2.1.0.

View File

@ -0,0 +1,54 @@
# basic_json::number_float_t
```cpp
using number_float_t = NumberFloatType;
```
The type used to store JSON numbers (floating-point).
[RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
> The representation of numbers is similar to that used in most programming languages. A number is represented in base
> 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may
> be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that
> cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.
This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is
known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different
types, [`number_integer_t`](number_integer_t.md), [`number_unsigned_t`](number_unsigned_t.md) and `number_float_t` are
used.
To store floating-point numbers in C++, a type is defined by the template parameter `NumberFloatType` which chooses the
type to use.
## Notes
#### Default type
With the default values for `NumberFloatType` (`double`), the default value for `number_float_t` is `#!cpp double`.
#### Default behavior
- The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be
ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2`
will be serialized to `1.2`. During deserialization, leading zeros yield an error.
- Not-a-number (NaN) values will be serialized to `null`.
#### Limits
[RFC 7159](http://rfc7159.net/rfc7159) states:
> This specification allows implementations to set limits on the range and precision of numbers accepted. Since software
> that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good
> interoperability can be achieved by implementations that expect no more precision or range than these provide, in the
> sense that implementations will approximate JSON numbers within the expected precision.
This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values
smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally
and be serialized to `null`.
#### Storage
Floating-point number values are stored directly inside a `basic_json` type.
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,74 @@
# basic_json::number_integer_t
```cpp
using number_integer_t = NumberIntegerType;
```
The type used to store JSON numbers (integers).
[RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
> The representation of numbers is similar to that used in most
> programming languages. A number is represented in base 10 using decimal
> digits. It contains an integer component that may be prefixed with an
> optional minus sign, which may be followed by a fraction part and/or an
> exponent part. Leading zeros are not allowed. (...) Numeric values that
> cannot be represented in the grammar below (such as Infinity and NaN)
> are not permitted.
This description includes both integer and floating-point numbers.
However, C++ allows more precise storage if it is known whether the number
is a signed integer, an unsigned integer or a floating-point number.
Therefore, three different types, `number_integer_t`,
[`number_unsigned_t`](number_unsigned_t.md) and [`number_float_t`](number_float_t.md) are used.
To store integer numbers in C++, a type is defined by the template
parameter `NumberIntegerType` which chooses the type to use.
## Notes
#### Default type
With the default values for `NumberIntegerType` (`std::int64_t`), the default
value for `number_integer_t` is:
```cpp
std::int64_t
```
#### Default behavior
- The restrictions about leading zeros is not enforced in C++. Instead,
leading zeros in integer literals lead to an interpretation as octal
number. Internally, the value will be stored as decimal number. For
instance, the C++ integer literal `010` will be serialized to `8`.
During deserialization, leading zeros yield an error.
- Not-a-number (NaN) values will be serialized to `null`.
#### Limits
[RFC 7159](http://rfc7159.net/rfc7159) specifies:
> An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be
stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
that are out of range will yield over/underflow when used in a
constructor. During deserialization, too large or small integer numbers
will be automatically be stored as [`number_unsigned_t`](number_unsigned_t.md)
or [`number_float_t`](number_float_t.md).
[RFC 7159](http://rfc7159.net/rfc7159) further states:
> Note that when such software is used, numbers that are integers and are
> in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
> that implementations will agree exactly on their numeric values.
As this range is a subrange of the exactly supported range [INT64_MIN,
INT64_MAX], this class's integer type is interoperable.
#### Storage
Integer number values are stored directly inside a `basic_json` type.
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,75 @@
# basic_json::number_unsigned_t
```cpp
using number_unsigned_t = NumberUnsignedType;
```
The type used to store JSON numbers (unsigned).
[RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
> The representation of numbers is similar to that used in most
> programming languages. A number is represented in base 10 using decimal
> digits. It contains an integer component that may be prefixed with an
> optional minus sign, which may be followed by a fraction part and/or an
> exponent part. Leading zeros are not allowed. (...) Numeric values that
> cannot be represented in the grammar below (such as Infinity and NaN)
> are not permitted.
This description includes both integer and floating-point numbers.
However, C++ allows more precise storage if it is known whether the number
is a signed integer, an unsigned integer or a floating-point number.
Therefore, three different types, [`number_integer_t`](number_integer_t.md),
`number_unsigned_t` and [`number_float_t`](number_float_t.md) are used.
To store unsigned integer numbers in C++, a type is defined by the
template parameter `NumberUnsignedType` which chooses the type to use.
## Notes
#### Default type
With the default values for `NumberUnsignedType` (`std::uint64_t`), the
default value for `number_unsigned_t` is:
```cpp
std::uint64_t
```
#### Default behavior
- The restrictions about leading zeros is not enforced in C++. Instead,
leading zeros in integer literals lead to an interpretation as octal
number. Internally, the value will be stored as decimal number. For
instance, the C++ integer literal `010` will be serialized to `8`.
During deserialization, leading zeros yield an error.
- Not-a-number (NaN) values will be serialized to `null`.
#### Limits
[RFC 7159](http://rfc7159.net/rfc7159) specifies:
> An implementation may set limits on the range and precision of numbers.
When the default type is used, the maximal integer number that can be
stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
number that can be stored is `0`. Integer numbers that are out of range
will yield over/underflow when used in a constructor. During
deserialization, too large or small integer numbers will be automatically
be stored as [`number_integer_t`](number_integer_t.md) or
[`number_float_t`](number_float_t.md).
[RFC 7159](http://rfc7159.net/rfc7159) further states:
> Note that when such software is used, numbers that are integers and are
> in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
> that implementations will agree exactly on their numeric values.
As this range is a subrange (when considered in conjunction with the
number_integer_t type) of the exactly supported range [0, UINT64_MAX],
this class's integer type is interoperable.
#### Storage
Integer number values are stored directly inside a `basic_json` type.
## Version history
- Added in version 2.0.0.

View File

@ -0,0 +1,65 @@
# basic_json::object
```cpp
static basic_json object(initializer_list_t init = {});
```
Creates a JSON object value from a given initializer list. The initializer
lists elements must be pairs, and their first elements must be strings. If
the initializer list is empty, the empty object `#!json {}` is created.
## Parameters
`init` (in)
: initializer list with JSON values to create an object from (optional)
## Return value
JSON object value
## Exceptions
Throws [`type_error.301`](../../home/exceptions.md#jsonexceptiontype_error301)
if `init` is not a list of pairs whose first
elements are strings. In this case, no object can be created. When such a
value is passed to `basic_json(initializer_list_t, bool, value_t)`,
an array would have been created from the passed initializer list `init`.
See example below.
## 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 added for symmetry reasons. In contrast to the
related function `array(initializer_list_t)`, there are
no cases which can only be expressed by this function. That is, any
initializer list `init` can also be passed to the initializer list
constructor `basic_json(initializer_list_t, bool, value_t)`.
## Examples
??? example
The following code shows an example for the `object`
function.
```cpp
--8<-- "examples/object.cpp"
```
Output:
```json
--8<-- "examples/object.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,99 @@
# basic_json::object_t
```cpp
using object_t = ObjectType<StringType,
basic_json,
object_comparator_t,
AllocatorType<std::pair<const StringType, basic_json>>>;
```
The type used to store JSON objects.
[RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
> An object is an unordered collection of zero or more name/value pairs,
> where a name is a string and a value is a string, number, boolean, null,
> object, or array.
To store objects in C++, a type is defined by the template parameters
described below.
## Template parameters
`ObjectType`
: the container to store objects (e.g., `std::map` or `std::unordered_map`)
`StringType`
: the type of the keys or names (e.g., `std::string`).
The comparison function `std::less<StringType>` is used to order elements
inside the container.
`AllocatorType`
: the allocator to use for objects (e.g., `std::allocator`)
## Notes
#### Default type
With the default values for `ObjectType` (`std::map`), `StringType`
(`std::string`), and `AllocatorType` (`std::allocator`), the default
value for `object_t` is:
```cpp
std::map<
std::string, // key_type
basic_json, // value_type
std::less<std::string>, // key_compare
std::allocator<std::pair<const std::string, basic_json>> // allocator_type
>
```
#### Behavior
The choice of `object_t` influences the behavior of the JSON class. With
the default type, objects have the following behavior:
- When all names are unique, objects will be interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings.
- When the names within an object are not unique, it is unspecified which
one of the values for a given key will be chosen. For instance,
`#!json {"key": 2, "key": 1}` could be equal to either `#!json {"key": 1}` or
`#!json {"key": 2}`.
- Internally, name/value pairs are stored in lexicographical order of the
names. Objects will also be serialized (see [`dump`](dump.md)) in this order.
For instance, `#!json {"b": 1, "a": 2}` and `#!json {"a": 2, "b": 1}` will be stored
and serialized as `#!json {"a": 2, "b": 1}`.
- When comparing objects, the order of the name/value pairs is irrelevant.
This makes objects interoperable in the sense that they will not be
affected by these differences. For instance, `#!json {"b": 1, "a": 2}` and
`#!json {"a": 2, "b": 1}` will be treated as equal.
#### Limits
[RFC 7159](http://rfc7159.net/rfc7159) specifies:
> An implementation may set limits on the maximum depth of nesting.
In this class, the object's limit of nesting is not explicitly constrained.
However, a maximum depth of nesting may be introduced by the compiler or
runtime environment. A theoretical limit can be queried by calling the
[`max_size`](max_size.md) function of a JSON object.
#### Storage
Objects are stored as pointers in a `basic_json` type. That is, for any
access to object values, a pointer of type `object_t*` must be
dereferenced.
#### Object key order
The order name/value pairs are added to the object is *not*
preserved by the library. Therefore, iterating an object may return
name/value pairs in a different order than they were originally stored. In
fact, keys will be traversed in alphabetical order as `std::map` with
`std::less` is used by default. Please note this behavior conforms to [RFC
7159](http://rfc7159.net/rfc7159), because any order implements the
specified "unordered" nature of JSON objects.
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,57 @@
# basic_json::operator!=
```cpp
bool operator!=(const_reference lhs, const_reference rhs) noexcept;
template<typename ScalarType>
bool operator!=(const_reference lhs, const ScalarType rhs) noexcept;
template<typename ScalarType>
bool operator!=(ScalarType lhs, const const_reference rhs) noexcept;
```
Compares two JSON values for inequality by calculating `#!cpp !(lhs == rhs)`.
## Template parameters
`ScalarType`
: a scalar type according to `std::is_scalar<ScalarType>::value`
## Parameters
`lhs` (in)
: first value to consider
`rhs` (in)
: second value to consider
## Return value
whether the values `lhs` and `rhs` are not equal
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Linear.
## Example
The example demonstrates comparing several JSON
types.
```cpp
--8<-- "examples/operator__notequal.cpp"
```
Output:
```json
--8<-- "examples/operator__notequal.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,120 @@
# basic_json::operator+=
```cpp
// (1)
reference operator+=(basic_json&& val);
reference operator+=(const basic_json& val);
// (2)
reference operator+=(const typename object_t::value_type& val);
// (3)
reference operator+=(initializer_list_t init);
```
1. Appends the given element `val` to the end of the JSON array. If the
function is called on a JSON null value, an empty array is created before
appending `val`.
2. Inserts the given element `val` to the JSON object. If the function is
called on a JSON null value, an empty object is created before inserting
`val`.
3. This function allows to use `operator+=` with an initializer list. In case
1. the current value is an object,
2. the initializer list `init` contains only two elements, and
3. the first element of `init` is a string,
`init` is converted into an object element and added using
`operator+=(const typename object_t::value_type&)`. Otherwise, `init`
is converted to a JSON value and added using `operator+=(basic_json&&)`.
## Parameters
`val` (in)
: the value to add to the JSON array/object
`init` (in)
: an initializer list
## Return value
`#!cpp *this`
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than JSON array or
null; example: `"cannot use operator+=() with number"`
2. The function can throw the following exceptions:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than JSON object or
null; example: `"cannot use operator+=() with number"`
## Complexity
1. Amortized constant.
2. Logarithmic in the size of the container, O(log(`size()`)).
3. Linear in the size of the initializer list `init`.
## Notes
(3) This function is required to resolve an ambiguous overload error,
because pairs like `{"key", "value"}` can be both interpreted as
`object_t::value_type` or `std::initializer_list<basic_json>`, see
[#235](https://github.com/nlohmann/json/issues/235) for more information.
## Examples
??? example
The example shows how `push_back()` and `+=` can be used to
add elements to a JSON array. Note how the `null` value was silently
converted to a JSON array.
```cpp
--8<-- "examples/push_back.cpp"
```
Output:
```json
--8<-- "examples/push_back.output"
```
??? example
The example shows how `push_back()` and `+=` can be used to
add elements to a JSON object. Note how the `null` value was silently
converted to a JSON object.
```cpp
--8<-- "examples/push_back__object_t__value.cpp"
```
Output:
```json
--8<-- "examples/push_back__object_t__value.output"
```
??? example
The example shows how initializer lists are treated as
objects when possible.
```cpp
--8<-- "examples/push_back__initializer_list.cpp"
```
Output:
```json
--8<-- "examples/push_back__initializer_list.output"
```
## Version history
1. Since version 1.0.0.
2. Since version 1.0.0.
2. Since version 2.0.0.

View File

@ -0,0 +1,46 @@
# basic_json::operator=
```cpp
basic_json& operator=(basic_json other) noexcept (
std::is_nothrow_move_constructible<value_t>::value &&
std::is_nothrow_move_assignable<value_t>::value &&
std::is_nothrow_move_constructible<json_value>::value &&
std::is_nothrow_move_assignable<json_value>::value
);
```
Copy assignment operator. Copies a JSON value via the "copy and swap"
strategy: It is expressed in terms of the copy constructor, destructor,
and the `swap()` member function.
## Parameters
`other` (in)
: value to copy from
## Complexity
Linear.
## Example
??? example
The code below shows and example for the copy assignment. It
creates a copy of value `a` which is then swapped with `b`. Finally\, the
copy of `a` (which is the null value after the swap) is
destroyed.
```cpp
--8<-- "examples/basic_json__copyassignment.cpp"
```
Output:
```json
--8<-- "examples/basic_json__copyassignment.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,102 @@
# basic_json::operator==
```cpp
bool operator==(const_reference lhs, const_reference rhs) noexcept;
template<typename ScalarType>
bool operator==(const_reference lhs, const ScalarType rhs) noexcept;
template<typename ScalarType>
bool operator==(ScalarType lhs, const const_reference rhs) noexcept;
```
Compares two JSON values for equality according to the following rules:
- Two JSON values are equal if (1) they are from the same type and (2)
their stored values are the same according to their respective
`operator==`.
- Integer and floating-point numbers are automatically converted before
comparison. Note that two NaN values are always treated as unequal.
- Two JSON null values are equal.
## Template parameters
`ScalarType`
: a scalar type according to `std::is_scalar<ScalarType>::value`
## Parameters
`lhs` (in)
: first value to consider
`rhs` (in)
: second value to consider
## Return value
whether the values `lhs` and `rhs` are equal
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Linear.
## Notes
- Floating-point inside JSON values numbers are compared with
`json::number_float_t::operator==` which is `double::operator==` by
default. To compare floating-point while respecting an epsilon, an alternative
[comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
could be used, for instance
```cpp
template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
{
return std::abs(a - b) <= epsilon;
}
```
Or you can self-defined operator equal function like this:
```cpp
bool my_equal(const_reference lhs, const_reference rhs)
{
const auto lhs_type lhs.type();
const auto rhs_type rhs.type();
if (lhs_type == rhs_type)
{
switch(lhs_type)
// self_defined case
case value_t::number_float:
return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
// other cases remain the same with the original
...
}
...
}
```
- NaN values never compare equal to themselves or to other NaN values.
## Example
The example demonstrates comparing several JSON
types.
```cpp
--8<-- "examples/operator__equal.cpp"
```
Output:
```json
--8<-- "examples/operator__equal.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,201 @@
# basic_json::operator[]
```cpp
// (1)
reference operator[](size_type idx);
const_reference operator[](size_type idx) const;
// (2)
reference operator[](const typename object_t::key_type& key);
const_reference operator[](const typename object_t::key_type& key) const;
template<typename T>
reference operator[](T* key);
template<typename T>
const_reference operator[](T* key) const;
// (3)
reference operator[](const json_pointer& ptr);
const_reference operator[](const json_pointer& ptr) const;
```
1. Returns a reference to the element at specified location `idx`.
2. Returns a reference to the element at with specified key `key`.
3. Returns a reference to the element at with specified JSON pointer `ptr`.
## Template parameters
`T`
: string literal convertible to `object_t::key_type`
## Parameters
`idx` (in)
: index of the element to access
`key` (in)
: object key of the elements to remove
`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 pointed to by `ptr`
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.305`](../../home/exceptions.md#jsonexceptiontype_error305) if the JSON value is not an array or null; in that
cases, using the `[]` operator with an index makes no sense.
2. The function can throw the following exceptions:
- Throws [`type_error.305`](../../home/exceptions.md#jsonexceptiontype_error305) if the JSON value is not an array or null; in that
cases, using the `[]` operator with an index makes no sense.
3. 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'.
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) if an array index in the passed JSON pointer `ptr`
is not a number.
- Throws [`out_of_range.402`](../../home/exceptions.md#jsonexceptionout_of_range402) if the array index '-' is used in the passed JSON
pointer `ptr` for the const version.
- Throws [`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) if the JSON pointer `ptr` can not be resolved.
## Notes
!!! danger
1. If the element with key `idx` does not exist, the behavior is
undefined.
2. If the element with key `key` does not exist, the behavior is
undefined and is **guarded by an assertion**!
1. The non-const version may add values: If `idx` is beyond the range of the array (i.e., `idx >= size()`),
then the array is silently filled up with `#!json null` values to make `idx` a
valid reference to the last stored element.
In case the value was `#!json null` before, it is converted to an array.
2. If `key` is not found in the object, then it is silently added to
the object and filled with a `#!json null` value to make `key` a valid reference.
In case the value was `#!json null` before, it is converted to an object.
3. `null` values are created in arrays and objects if necessary.
In particular:
- If the JSON pointer points to an object key that does not exist, it
is created an filled with a `null` value before a reference to it
is returned.
- If the JSON pointer points to an array index that does not exist, it
is created an filled with a `null` value before a reference to it
is returned. All indices between the current maximum and the given
index are also filled with `null`.
- The special value `-` is treated as a synonym for the index past the
end.
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
1. Constant if `idx` is in the range of the array. Otherwise linear in `idx - size()`.
2. Logarithmic in the size of the container.
3. Constant
## Example
??? example
The example below shows how array elements can be read and
written using `[]` operator. Note the addition of `null`
values.
```cpp
--8<-- "examples/operatorarray__size_type.cpp"
```
Output:
```json
--8<-- "examples/operatorarray__size_type.output"
```
??? example
The example below shows how array elements can be read using
the `[]` operator.
```cpp
--8<-- "examples/operatorarray__size_type_const.cpp"
```
Output:
```json
--8<-- "examples/operatorarray__size_type_const.output"
```
??? example
The example below shows how object elements can be read and
written using the `[]` operator.
```cpp
--8<-- "examples/operatorarray__key_type.cpp"
```
Output:
```json
--8<-- "examples/operatorarray__key_type.output"
```
??? example
The example below shows how object elements can be read using
the `[]` operator.
```cpp
--8<-- "examples/operatorarray__key_type_const.cpp"
```
Output:
```json
--8<-- "examples/operatorarray__key_type_const.output"
```
??? example
The example below shows how values can be read and written using JSON Pointers.
```cpp
--8<-- "examples/operatorjson_pointer.cpp"
```
Output:
```json
--8<-- "examples/operatorjson_pointer.output"
```
??? example
The example below shows how values can be read using JSON Pointers.
```cpp
--8<-- "examples/operatorjson_pointer_const.cpp"
```
Output:
```json
--8<-- "examples/operatorjson_pointer_const.output"
```
## Version history
1. Added in version 1.0.0.
2. Added in version 1.0.0. Overloads for `T* key` added in version 1.1.0.
3. Added in version 2.0.0.

View File

@ -0,0 +1,56 @@
# basic_json::operator value_t
```cpp
constexpr operator value_t() const noexcept;
```
Return the type of the JSON value as a value from the [`value_t`](value_t.md)
enumeration.
## Return value
the type of the JSON value
Value type | return value
------------------------- | -------------------------
`#!json null` | `value_t::null`
boolean | `value_t::boolean`
string | `value_t::string`
number (integer) | `value_t::number_integer`
number (unsigned integer) | `value_t::number_unsigned`
number (floating-point) | `value_t::number_float`
object | `value_t::object`
array | `value_t::array`
binary | `value_t::binary`
discarded | `value_t::discarded`
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `operator value_t()` for all JSON
types.
```cpp
--8<-- "examples/operator__value_t.cpp"
```
Output:
```json
--8<-- "examples/operator__value_t.output"
```
## Version history
- Added in version 1.0.0.
- Added unsigned integer type in version 2.0.0.
- Added binary type in version 3.8.0.

View File

@ -6,22 +6,24 @@ template<typename InputType>
static basic_json parse(InputType&& i,
const parser_callback_t cb = nullptr,
const bool allow_exceptions = true,
const bool ignore_comments = false)
const bool ignore_comments = false);
// (2)
template<typename IteratorType>
static basic_json parse(IteratorType first,
IteratorType last,
static basic_json parse(iterator first, iterator last,
const parser_callback_t cb = nullptr,
const bool allow_exceptions = true,
const bool ignore_comments = false)
const bool ignore_comments = false);
static basic_json parse(const_iterator first, const_iterator last,
const parser_callback_t cb = nullptr,
const bool allow_exceptions = true,
const bool ignore_comments = false);
```
1. Deserialize from a compatible input.
2. Deserialize from a pair of character iterators
The value_type of the iterator must be a integral type with size of 1, 2 or
4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
The value_type of the iterator must be a integral type with size of 1, 2 or 4 bytes, which will be interpreted
respectively as UTF-8, UTF-16 and UTF-32.
## Template parameters
@ -32,11 +34,7 @@ static basic_json parse(IteratorType first,
- a `FILE` pointer
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of
iterators.
`IteratorType`
: Description
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators.
## Parameters
@ -44,17 +42,15 @@ static basic_json parse(IteratorType first,
: Input to parse from.
`cb` (in)
: a parser callback function of type `parser_callback_t`
which is used to control the deserialization by filtering unwanted values
(optional)
: a parser callback function of type [`parser_callback_t`](parser_callback_t.md) which is used to control the
deserialization by filtering unwanted values (optional)
`allow_exceptions` (in)
: whether to throw exceptions in case of a parse error (optional, `#!cpp true` by default)
`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)
: whether comments 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 start of character range
@ -64,16 +60,18 @@ static basic_json parse(IteratorType first,
## Return value
Deserialized JSON value; in case of a parse error and `allow_exceptions`
set to `#!cpp false`, the return value will be `value_t::discarded`.
Deserialized JSON value; in case of a parse error and `allow_exceptions` set to `#!cpp false`, the return value will be
`value_t::discarded`.
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the length of the input. The parser is a predictive
LL(1) parser. The complexity can be higher if the parser callback function
`cb` or reading from (1) the input `i` or (2) the iterator range [`first`, `last`] has a super-linear complexity.
Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser
callback function `cb` or reading from (1) the input `i` or (2) the iterator range [`first`, `last`] has a
super-linear complexity.
## Notes
@ -83,8 +81,7 @@ LL(1) parser. The complexity can be higher if the parser callback function
??? example
The example below demonstrates the `parse()` function reading
from an array.
The example below demonstrates the `parse()` function reading from an array.
```cpp
--8<-- "examples/parse__array__parser_callback_t.cpp"
@ -98,8 +95,7 @@ LL(1) parser. The complexity can be higher if the parser callback function
??? example
The example below demonstrates the `parse()` function with
and without callback function.
The example below demonstrates the `parse()` function with and without callback function.
```cpp
--8<-- "examples/parse__string__parser_callback_t.cpp"
@ -113,8 +109,7 @@ LL(1) parser. The complexity can be higher if the parser callback function
??? example
The example below demonstrates the `parse()` function with
and without callback function.
The example below demonstrates the `parse()` function with and without callback function.
```cpp
--8<-- "examples/parse__istream__parser_callback_t.cpp"
@ -128,8 +123,7 @@ LL(1) parser. The complexity can be higher if the parser callback function
??? example
The example below demonstrates the `parse()` function reading
from a contiguous container.
The example below demonstrates the `parse()` function reading from a contiguous container.
```cpp
--8<-- "examples/parse__contiguouscontainer__parser_callback_t.cpp"
@ -141,6 +135,8 @@ LL(1) parser. The complexity can be higher if the parser callback function
--8<-- "examples/parse__contiguouscontainer__parser_callback_t.output"
```
## History
## Version history
(1) version 2.0.3 (contiguous containers); version 3.9.0 allowed to ignore comments.
- Added in version 1.0.0.
- Overload for contiguous containers (1) added in version 2.0.3.
- Ignoring comments via `ignore_comments` added in version 3.9.0.

View File

@ -0,0 +1,29 @@
# basic_json::parse_event_t
```cpp
enum class parse_event_t : std::uint8_t {
object_start,
object_end,
array_start,
array_end,
key,
value
};
```
The parser callback distinguishes the following events:
- `object_start`: the parser read `{` and started to process a JSON object
- `key`: the parser read a key of a value in an object
- `object_end`: the parser read `}` and finished processing a JSON object
- `array_start`: the parser read `[` and started to process a JSON array
- `array_end`: the parser read `]` and finished processing a JSON array
- `value`: the parser finished reading a JSON value
## Example
![Example when certain parse events are triggered](../../images/callback_events.png)
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,77 @@
# basic_json::parser_callback_t
```cpp
template<typename BasicJsonType>
using parser_callback_t =
std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
```
With a parser callback function, the result of parsing a JSON text can be
influenced. When passed to [`parse`](parse.md), it is called on certain events
(passed as [`parse_event_t`](parse_event_t.md) via parameter `event`) with a set recursion
depth `depth` and context JSON value `parsed`. The return value of the
callback function is a boolean indicating whether the element that emitted
the callback shall be kept or not.
We distinguish six scenarios (determined by the event type) in which the
callback function can be called. The following table describes the values
of the parameters `depth`, `event`, and `parsed`.
parameter `event` | description | parameter `depth` | parameter `parsed`
------------------ | ----------- | ------------------ | -------------------
`parse_event_t::object_start` | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
`parse_event_t::key` | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
`parse_event_t::object_end` | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
`parse_event_t::array_start` | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
`parse_event_t::array_end` | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
`parse_event_t::value` | the parser finished reading a JSON value | depth of the value | the parsed JSON value
![Example when certain parse events are triggered](../../images/callback_events.png)
Discarding a value (i.e., returning `#!cpp false`) has different effects
depending on the context in which function was called:
- Discarded values in structured types are skipped. That is, the parser
will behave as if the discarded value was never read.
- In case a value outside a structured type is skipped, it is replaced
with `null`. This case happens if the top-level element is skipped.
## Parameters
`depth` (in)
: the depth of the recursion during parsing
`event` (in)
: an event of type [`parse_event_t`](parse_event_t.md) indicating the context in
the callback function has been called
`parsed` (in, out)
: the current intermediate parse result; note that
writing to this value has no effect for `parse_event_t::key` events
## Return value
Whether the JSON value which called the function during parsing
should be kept (`#!cpp true`) or not (`#!cpp false`). In the latter case, it is either
skipped completely or replaced by an empty discarded object.
# Example
??? example
The example below demonstrates the `parse()` function with
and without callback function.
```cpp
--8<-- "examples/parse__string__parser_callback_t.cpp"
```
Output:
```json
--8<-- "examples/parse__string__parser_callback_t.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,70 @@
# basic_json::patch
```cpp
basic_json patch(const basic_json& json_patch) const;
```
[JSON Patch](http://jsonpatch.com) defines a JSON document structure for
expressing a sequence of operations to apply to a JSON) document. With
this function, a JSON Patch is applied to the current JSON value by
executing all operations from the patch.
## Parameters
`json_patch` (in)
: JSON patch document
## Return value
patched document
## Exceptions
- Throws [`parse_error.104`](../../home/exceptions.md#jsonexceptionparse_error104) if the JSON patch does not consist of an array of
objects.
- Throws [`parse_error.105`](../../home/exceptions.md#jsonexceptionparse_error105) if the JSON patch is malformed (e.g., mandatory
attributes are missing); example: `"operation add must have member path"`.
- Throws [`out_of_range.401`](../../home/exceptions.md#jsonexceptionout_of_range401) if an array index is out of range.
- Throws [`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if a JSON pointer inside the patch could not be
resolved successfully in the current JSON value; example: `"key baz not found"`.
- Throws [`out_of_range.405`](../../home/exceptions.md#jsonexceptionout_of_range405) if JSON pointer has no parent ("add", "remove", "move")
- Throws [`out_of_range.501`](../../home/exceptions.md#jsonexceptionother_error501) if "test" operation was unsuccessful.
## Exception safety
Strong guarantee: if an exception is thrown, there are no
changes in the JSON value.
## Complexity
Linear in the size of the JSON value and the length of the
JSON patch. As usually only a fraction of the JSON value is affected by
the patch, the complexity can usually be neglected.
## Note
The application of a patch is atomic: Either all operations succeed
and the patched document is returned or an exception is thrown. In
any case, the original value is not changed: the patch is applied
to a copy of the value.
## Example
??? example
The following code shows how a JSON patch is applied to a
value.
```cpp
--8<-- "examples/patch.cpp"
```
Output:
```json
--8<-- "examples/patch.output"
```
## Version history
- Added in version 2.0.0.

View File

@ -0,0 +1,116 @@
# basic_json::push_back
```cpp
// (1)
void push_back(basic_json&& val);
void push_back(const basic_json& val);
// (2)
void push_back(const typename object_t::value_type& val);
// (3)
void push_back(initializer_list_t init);
```
1. Appends the given element `val` to the end of the JSON array. If the
function is called on a JSON null value, an empty array is created before
appending `val`.
2. Inserts the given element `val` to the JSON object. If the function is
called on a JSON null value, an empty object is created before inserting
`val`.
3. This function allows to use `push_back` with an initializer list. In case
1. the current value is an object,
2. the initializer list `init` contains only two elements, and
3. the first element of `init` is a string,
`init` is converted into an object element and added using
`push_back(const typename object_t::value_type&)`. Otherwise, `init`
is converted to a JSON value and added using `push_back(basic_json&&)`.
## Parameters
`val` (in)
: the value to add to the JSON array/object
`init` (in)
: an initializer list
## Exceptions
1. The function can throw the following exceptions:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than JSON array or
null; example: `"cannot use push_back() with number"`
2. The function can throw the following exceptions:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than JSON object or
null; example: `"cannot use push_back() with number"`
## Complexity
1. Amortized constant.
2. Logarithmic in the size of the container, O(log(`size()`)).
3. Linear in the size of the initializer list `init`.
## Notes
(3) This function is required to resolve an ambiguous overload error,
because pairs like `{"key", "value"}` can be both interpreted as
`object_t::value_type` or `std::initializer_list<basic_json>`, see
[#235](https://github.com/nlohmann/json/issues/235) for more information.
## Examples
??? example
The example shows how `push_back()` and `+=` can be used to
add elements to a JSON array. Note how the `null` value was silently
converted to a JSON array.
```cpp
--8<-- "examples/push_back.cpp"
```
Output:
```json
--8<-- "examples/push_back.output"
```
??? example
The example shows how `push_back()` and `+=` can be used to
add elements to a JSON object. Note how the `null` value was silently
converted to a JSON object.
```cpp
--8<-- "examples/push_back__object_t__value.cpp"
```
Output:
```json
--8<-- "examples/push_back__object_t__value.output"
```
??? example
The example shows how initializer lists are treated as
objects when possible.
```cpp
--8<-- "examples/push_back__initializer_list.cpp"
```
Output:
```json
--8<-- "examples/push_back__initializer_list.output"
```
## Version history
1. Since version 1.0.0.
2. Since version 1.0.0.
2. Since version 2.0.0.

View File

@ -0,0 +1,42 @@
# basic_json::rbegin
```cpp
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() 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 first element
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code shows an example for `rbegin()`.
```cpp
--8<-- "examples/rbegin.cpp"
```
Output:
```json
--8<-- "examples/rbegin.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,43 @@
# basic_json::rend
```cpp
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
```
Returns an iterator to the reverse-end; that is, one before the first
element. This element acts as a placeholder, attempting to access it results in undefined behavior.
![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.
## Example
??? example
The following code shows an example for `eend()`.
```cpp
--8<-- "examples/rend.cpp"
```
Output:
```json
--8<-- "examples/rend.output"
```
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,111 @@
# basic_json::sax_parse
```cpp
// (1)
template <typename InputType, typename SAX>
static bool sax_parse(InputType&& i,
SAX* sax,
input_format_t format = input_format_t::json,
const bool strict = true,
const bool ignore_comments = false);
// (2)
template<class IteratorType, class SAX>
static bool sax_parse(IteratorType first, IteratorType last,
SAX* sax,
input_format_t format = input_format_t::json,
const bool strict = true,
const bool ignore_comments = false);
```
Read from input and generate SAX events
1. Read from a compatible input.
2. Read from a pair of character iterators
The value_type of the iterator must be a integral type with size of 1, 2 or
4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
The SAX event lister must follow the interface of `json_sax`.
## Template parameters
`InputType`
: A compatible input, for instance:
- an `std::istream` object
- a `FILE` pointer
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of
iterators.
`IteratorType`
: Description
`SAX`
: Description
## Parameters
`i` (in)
: Input to parse from.
`sax` (in)
: SAX event listener
`format` (in)
: the format to parse (JSON, CBOR, MessagePack, or UBJSON) (optional, `input_format_t::json` by default)
`strict` (in)
: whether the input has to be consumed completely (optional, `#!cpp true` by default)
`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)
`first` (in)
: iterator to start of character range
`last` (in)
: iterator to end of character range
## Return value
return value of the last processed SAX event
## Exception safety
## Complexity
Linear in the length of the input. The parser is a predictive
LL(1) parser. The complexity can be higher if the SAX consumer `sax` has
a super-linear complexity.
## Notes
A UTF-8 byte order mark is silently ignored.
## Examples
??? example
The example below demonstrates the `sax_parse()` function
reading from string and processing the events with a user-defined SAX
event consumer.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history
- Added in version 3.2.0.
- Ignoring comments via `ignore_comments` added in version 3.9.0.

View File

@ -0,0 +1,60 @@
# basic_json::size
```cpp
size_type size() const noexcept;
```
Returns the number of elements in a JSON value.
## Return value
The return value depends on the different types and is
defined as follows:
Value type | return value
----------- | -------------
null | `0`
boolean | `1`
string | `1`
number | `1`
binary | `1`
object | result of function object_t::size()
array | result of function array_t::size()
## Exception safety
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 concept; that is, their `size()` functions have constant
complexity.
## Notes
This function does not return the length of a string stored as JSON
value - it returns the number of elements in the JSON value which is `1` in
the case of a string.
## Example
??? example
The following code calls `size()` on the different value
types.
```cpp
--8<-- "examples/size.cpp"
```
Output:
```json
--8<-- "examples/size.output"
```
## Version history
- Added in version 1.0.0.
- Extended to return `1` for binary types in version 3.8.0.

View File

@ -0,0 +1,62 @@
# basic_json::string_t
```cpp
using string_t = StringType;
```
The type used to store JSON strings.
[RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
> A string is a sequence of zero or more Unicode characters.
To store objects in C++, a type is defined by the template parameter
described below. Unicode values are split by the JSON class into
byte-sized characters during deserialization.
## Template parameters
`StringType`
: the container to store strings (e.g., `std::string`).
Note this container is used for keys/names in objects, see [object_t](object_t.md).
## Notes
#### Default type
With the default values for `StringType` (`std::string`), the default
value for `string_t` is:
```cpp
std::string
```
#### Encoding
Strings are stored in UTF-8 encoding. Therefore, functions like
`std::string::size()` or `std::string::length()` return the number of
bytes in the string rather than the number of characters or glyphs.
#### String comparison
[RFC 7159](http://rfc7159.net/rfc7159) states:
> Software implementations are typically required to test names of object
> members for equality. Implementations that transform the textual
> representation into sequences of Unicode code units and then perform the
> comparison numerically, code unit by code unit, are interoperable in the
> sense that implementations will agree in all cases on equality or
> inequality of two strings. For example, implementations that compare
> strings with escaped characters unconverted may incorrectly find that
> `"a\\b"` and `"a\u005Cb"` are not equal.
This implementation is interoperable as it does compare strings code unit
by code unit.
#### Storage
String values are stored as pointers in a `basic_json` type. That is,
for any access to string values, a pointer of type `string_t*` must be
dereferenced.
## Version history
- Added in version 1.0.0.

View File

@ -0,0 +1,56 @@
# basic_json::type
```cpp
constexpr value_t type() const noexcept;
```
Return the type of the JSON value as a value from the [`value_t`](value_t.md)
enumeration.
## Return value
the type of the JSON value
Value type | return value
------------------------- | -------------------------
`#!json null` | `value_t::null`
boolean | `value_t::boolean`
string | `value_t::string`
number (integer) | `value_t::number_integer`
number (unsigned integer) | `value_t::number_unsigned`
number (floating-point) | `value_t::number_float`
object | `value_t::object`
array | `value_t::array`
binary | `value_t::binary`
discarded | `value_t::discarded`
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `type()` for all JSON
types.
```cpp
--8<-- "examples/type.cpp"
```
Output:
```json
--8<-- "examples/type.output"
```
## Version history
- Added in version 1.0.0.
- Added unsigned integer type in version 2.0.0.
- Added binary type in version 3.8.0.

View File

@ -0,0 +1,55 @@
# basic_json::type_name
```cpp
const char* type_name() const noexcept;
```
Returns the type name as string to be used in error messages - usually to
indicate that a function was called on a wrong JSON type.
## Return value
a string representation of a the type ([`value_t`](value_t.md)):
Value type | return value
-------------------------------------------------- | -------------------------
`#!json null` | `"null"`
boolean | `"boolean"`
string | `"string"`
number (integer, unsigned integer, floating-point) | `"number"`
object | `"object`
array | `"array`
binary | `"binary`
discarded | `"discarded`
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Constant.
## Example
??? example
The following code exemplifies `type_name()` for all JSON
types.
```cpp
--8<-- "examples/type_name.cpp"
```
Output:
```json
--8<-- "examples/type_name.output"
```
## Version history
- Added in version 1.0.0.
- Part of the public API version since 2.1.0.
- Changed return value to `const char*` and added `noexcept` in version 3.0.0.
- Added support for binary type in version 3.8.0.

View File

@ -0,0 +1,61 @@
# basic_json::unflatten
```cpp
basic_json unflatten() const;
```
The function restores the arbitrary nesting of a JSON value that has been
flattened before using the [`flatten()`](flatten.md) function. The JSON value must
meet certain constraints:
1. The value must be an object.
2. The keys must be JSON pointers (see
[RFC 6901](https://tools.ietf.org/html/rfc6901))
3. The mapped values must be primitive JSON types.
## Return value
the original JSON from a flattened version
## Exceptions
The function can throw the following exceptions:
- Throws [`type_error.314`](../../home/exceptions.md#jsonexceptiontype_error314) if value is not an object
- Throws [`type_error.315`](../../home/exceptions.md#jsonexceptiontype_error315) if object values are not primitive
## Exception safety
Strong exception safety: if an exception occurs, the original value stays intact.
## Complexity
Linear in the size the JSON value.
## Notes
Empty objects and arrays are flattened by [`flatten()`](flatten.md) to `#!json null`
values and can not unflattened to their original type. Apart from
this example, for a JSON value `j`, the following is always true:
`#!cpp j == j.flatten().unflatten()`.
## Example
??? example
The following code shows how a flattened JSON object is
unflattened into the original nested JSON object.
```cpp
--8<-- "examples/unflatten.cpp"
```
Output:
```json
--8<-- "examples/unflatten.output"
```
## Version history
- Added in version 2.0.0.

View File

@ -0,0 +1,78 @@
# basic_json::update
```cpp
// (1)
void update(const_reference j);
// (2)
void update(const_iterator first, const_iterator last);
```
1. Inserts all values from JSON object `j` and overwrites existing keys.
2. Inserts all values from from range `[first, last)` and overwrites existing keys.
The function is motivated by Python's [dict.update](https://docs.python.org/3.6/library/stdtypes.html#dict.update) function.
## Parameters
`j` (in)
: JSON object to read values from
`first` (in)
: begin of the range of elements to insert
`last` (in)
: end of the range of elements to insert
## Exceptions
1. The function can throw thw following exceptions:
- Throws [`type_error.312`](../../home/exceptions.md#jsonexceptiontype_error312) if called on JSON values other than objects;
example: `"cannot use update() with string"`
2. The function can throw thw following exceptions:
- Throws [`type_error.312`](../../home/exceptions.md#jsonexceptiontype_error312) if called on JSON values other than objects;
example: `"cannot use update() with string"`
- 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.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last` do not belong to the
same JSON value; example: `"iterators do not fit"`
## Complexity
1. O(N*log(size() + N)), where N is the number of elements to insert.
2. O(N*log(size() + N)), where N is the number of elements to insert.
## Example
??? example
The example shows how `update()` is used.
```cpp
--8<-- "examples/update.cpp"
```
Output:
```json
--8<-- "examples/update.output"
```
??? example
The example shows how `update()` is used.
```cpp
--8<-- "examples/update__range.cpp"
```
Output:
```json
--8<-- "examples/update__range.output"
```
## Version history
- Added in version 3.0.0.

View File

@ -0,0 +1,125 @@
# basic_json::value
```cpp
// (1)
template<class ValueType>
ValueType value(const typename object_t::key_type& key,
const ValueType& default_value) const;
// (2)
template<class ValueType>
ValueType value(const json_pointer& ptr,
const ValueType& default_value) const;
```
1. Returns either a copy of an object's element at the specified key `key`
or a given default value if no element with key `key` exists.
The function is basically equivalent to executing
```cpp
try {
return at(key);
} catch(out_of_range) {
return default_value;
}
```
2. Returns either a copy of an object's element at the specified JSON pointer `ptr`
or a given default value if no value at `ptr` exists.
The function is basically equivalent to executing
```cpp
try {
return at(ptr);
} catch(out_of_range) {
return default_value;
}
```
Unlike [`operator[]`](operator[].md), this
function does not implicitly add an element to the position defined by `key`/`ptr`
key. This function is furthermore also applicable to const objects.
## Template parameters
`ValueType`
: type compatible to JSON values, for instance `#!cpp int` for
JSON integer numbers, `#!cpp bool` for JSON booleans, or `#!cpp std::vector` types for
JSON arrays. Note the type of the expected value at `key`/`ptr` and the default
value `default_value` must be compatible.
## Parameters
`key` (in)
: key of the element to access
`default_value` (in)
: the value to return if key/ptr found no value
`ptr` (in)
: a JSON pointer to the element to access
## Return value
1. copy of the element at key `key` or `default_value` if `key` is not found
1. copy of the element at JSON Pointer `ptr` or `default_value` if no value for `ptr` is found
## Exception safety
Strong guarantee: if an exception is thrown, there are no
changes to any JSON value.
## Exceptions
1. The function can throw thw following exceptions:
- Throws [`type_error.302`](../../home/exceptions.md#jsonexceptiontype_error302) if `default_value` does not match the type of the
value at `key`
- Throws [`type_error.306`](../../home/exceptions.md#jsonexceptiontype_error306) if the JSON value is not an object; in that case,
using `value()` with a key makes no sense.
2. The function can throw thw following exceptions:
- Throws [`type_error.302`](../../home/exceptions.md#jsonexceptiontype_error302) if `default_value` does not match the type of the
value at `ptr`
- Throws [`type_error.306`](../../home/exceptions.md#jsonexceptiontype_error306) if the JSON value is not an object; in that case,
using `value()` with a key makes no sense.
## Complexity
1. Logarithmic in the size of the container.
2. Logarithmic in the size of the container.
## Example
??? example
The example below shows how object elements can be queried
with a default value.
```cpp
--8<-- "examples/basic_json__value.cpp"
```
Output:
```json
--8<-- "examples/basic_json__value.output"
```
??? example
The example below shows how object elements can be queried
with a default value.
```cpp
--8<-- "examples/basic_json__value_ptr.cpp"
```
Output:
```json
--8<-- "examples/basic_json__value_ptr.output"
```
## Version history
1. Added in version 1.0.0.
2. Added in version 2.0.2.

View File

@ -0,0 +1,40 @@
# basic_json::value_t
```cpp
enum class value_t : std::uint8_t {
null,
object,
array,
string,
boolean,
number_integer,
number_unsigned,
number_float,
binary,
discarded
};
```
This enumeration collects the different JSON types. It is internally used to
distinguish the stored values, and the functions [`is_null`](is_null.md),
[`is_object`](is_object.md), [`is_array`](is_array.md),
[`is_string`](is_string.md), [`is_boolean`](is_boolean.md),
[`is_number`](is_number.md) (with [`is_number_integer`](is_number_integer.md),
[`is_number_unsigned`](is_number_unsigned.md), and [`is_number_float`](is_number_float.md)),
[`is_discarded`](is_discarded.md), [`is_binary`](is_binary.md), [`is_primitive`](is_primitive.md), and
[`is_structured`](is_structured.md) rely on it.
## Note
There are three enumeration entries (number_integer, number_unsigned, and
number_float), because the library distinguishes these three types for numbers:
[`number_unsigned_t`](number_unsigned_t.md) is used for unsigned integers,
[`number_integer_t`](number_integer_t.md) is used for signed integers, and
[`number_float_t`](number_float_t.md) is used for floating-point numbers or to
approximate integers which do not fit in the limits of their respective type.
## Version history
- Added in version 1.0.0.
- Added unsigned integer type in version 2.0.0.
- Added binary type in version 3.8.0.

View File

@ -0,0 +1,19 @@
# basic_json::~basic_json
```cpp
~basic_json() noexcept
```
Destroys the JSON value and frees all allocated memory.
## Exception safety
No-throw guarantee: this member function never throws exceptions.
## Complexity
Linear.
## Version history
- Added in version 1.0.0.

View File

@ -322,7 +322,7 @@ The iterators passed to constructor `basic_json(InputIT first, InputIT last)` ar
### json.exception.invalid_iterator.202
In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
In an [erase](../api/basic_json/erase.md) or insert function, the passed iterator `pos` does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
!!! failure "Example message"
@ -335,7 +335,7 @@ In an erase or insert function, the passed iterator @a pos does not belong to th
### json.exception.invalid_iterator.203
Either iterator passed to function `erase(IteratorType` first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
Either iterator passed to function [`erase(IteratorType first, IteratorType last`)](../api/basic_json/erase.md) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
!!! failure "Example message"
@ -345,7 +345,7 @@ Either iterator passed to function `erase(IteratorType` first, IteratorType last
### json.exception.invalid_iterator.204
When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (`begin(),` `end()),` because this is the only way the single stored value is expressed. All other ranges are invalid.
When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an [erase](../api/basic_json/erase.md) function, this range has to be exactly (`begin(),` `end()),` because this is the only way the single stored value is expressed. All other ranges are invalid.
!!! failure "Example message"
@ -355,7 +355,7 @@ When an iterator range for a primitive type (number, boolean, or string) is pass
### json.exception.invalid_iterator.205
When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the `begin()` iterator, because it is the only way to address the stored value. All other iterators are invalid.
When an iterator for a primitive type (number, boolean, or string) is passed to an [erase](../api/basic_json/erase.md) function, the iterator has to be the `begin()` iterator, because it is the only way to address the stored value. All other iterators are invalid.
!!! failure "Example message"
@ -549,7 +549,7 @@ The `value()` member functions can only be executed for certain JSON types.
### json.exception.type_error.307
The `erase()` member functions can only be executed for certain JSON types.
The [`erase()`](../api/basic_json/erase.md) member functions can only be executed for certain JSON types.
!!! failure "Example message"

View File

@ -2,6 +2,6 @@
!!! note
This page is under construction. You probably want to see the [Doxygen documentation](doxygen).
This page is under construction.
![](images/json.gif)

View File

@ -72,9 +72,79 @@ nav:
- API:
- basic_json:
- api/basic_json/index.md
- api/basic_json/accept.md
- api/basic_json/array.md
- api/basic_json/array_t.md
- api/basic_json/at.md
- api/basic_json/back.md
- api/basic_json/basic_json.md
- api/basic_json/~basic_json.md
- api/basic_json/begin.md
- api/basic_json/binary.md
- api/basic_json/boolean_t.md
- api/basic_json/cbegin.md
- api/basic_json/cend.md
- api/basic_json/clear.md
- api/basic_json/contains.md
- api/basic_json/count.md
- api/basic_json/crbegin.md
- api/basic_json/crend.md
- api/basic_json/diff.md
- api/basic_json/dump.md
- api/basic_json/emplace.md
- api/basic_json/emplace_back.md
- api/basic_json/empty.md
- api/basic_json/end.md
- api/basic_json/erase.md
- api/basic_json/error_handler_t.md
- api/basic_json/find.md
- api/basic_json/flatten.md
- api/basic_json/front.md
- api/basic_json/insert.md
- api/basic_json/is_array.md
- api/basic_json/is_binary.md
- api/basic_json/is_boolean.md
- api/basic_json/is_discarded.md
- api/basic_json/is_null.md
- api/basic_json/is_number.md
- api/basic_json/is_number_float.md
- api/basic_json/is_number_integer.md
- api/basic_json/is_number_unsigned.md
- api/basic_json/is_object.md
- api/basic_json/is_primitive.md
- api/basic_json/is_string.md
- api/basic_json/is_structured.md
- api/basic_json/items.md
- api/basic_json/max_size.md
- api/basic_json/meta.md
- api/basic_json/merge_patch.md
- api/basic_json/number_float_t.md
- api/basic_json/number_integer_t.md
- api/basic_json/number_unsigned_t.md
- api/basic_json/object.md
- api/basic_json/object_t.md
- api/basic_json/operator_value_t.md
- api/basic_json/operator[].md
- api/basic_json/operator=.md
- api/basic_json/operator==.md
- api/basic_json/operator!=.md
- api/basic_json/operator+=.md
- api/basic_json/parse.md
- api/basic_json/parse_event_t.md
- api/basic_json/parser_callback_t.md
- api/basic_json/patch.md
- api/basic_json/push_back.md
- api/basic_json/rbegin.md
- api/basic_json/rend.md
- api/basic_json/sax_parse.md
- api/basic_json/size.md
- api/basic_json/string_t.md
- api/basic_json/type.md
- api/basic_json/type_name.md
- api/basic_json/unflatten.md
- api/basic_json/update.md
- api/basic_json/value.md
- api/basic_json/value_t.md
# Extras
extra: