mirror of
https://github.com/nlohmann/json.git
synced 2026-10-12 10:13:13 +00:00
Give basic_json_view the read-only access functions of basic_json: operator[] and at() with keys and indices, front()/back(), find(), contains(), count(), begin()/end() and cbegin()/cend(), items() with structured bindings from C++17 on, and type_name(). Exceptions have the ids and messages of the const functions of basic_json. Where basic_json has undefined behavior the view answers safely: operator[] with a missing key or an out-of-range index returns a discarded view, and front()/back() of an empty container throw invalid_iterator.214. Objects are iterated in document order, and all members are visited; duplicate-key lookups find the first member (as yyjson and simdjson do), while parse(), materialize(), and the map conversions keep the last value, as parse() does. Keys of up to 16 bytes are compared with two overlapping loads. Add value conversions: get<T>()/get_to() for arithmetic types, bool, nullptr_t, strings (std::basic_string copied, string_view_t without a copy), BasicJsonType, views, std::vector, and maps with string keys; get_string() for the string without a copy; number_token() for the number exactly as written in the source; value() with keys and JSON pointers; and operator[]/at()/ contains() with JSON pointers. Everything else, including types with from_json(), goes through materialize() of that subtree. get<T>() of arithmetic types is inlined down to the conversion, so reading an integer needs no call. detail::json_pointer_access exposes a pointer's reference tokens to code outside basic_json. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
242 lines
9.4 KiB
Markdown
242 lines
9.4 KiB
Markdown
# <small>nlohmann::basic_json::</small>value
|
|
|
|
```cpp
|
|
// (1)
|
|
template<class ValueType>
|
|
ValueType value(const typename object_t::key_type& key,
|
|
ValueType&& default_value) const;
|
|
|
|
// (2)
|
|
template<class ValueType, class KeyType>
|
|
ValueType value(KeyType&& key,
|
|
ValueType&& default_value) const;
|
|
|
|
// (3)
|
|
template<class ValueType>
|
|
ValueType value(const json_pointer& ptr,
|
|
const ValueType& default_value) const;
|
|
```
|
|
|
|
This is equivalent to Python's `dict.get(key, default)`.
|
|
|
|
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. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
|
|
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
|
|
|
|
3. 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;
|
|
}
|
|
```
|
|
|
|
!!! note "Differences to `at` and `operator[]`"
|
|
|
|
- Unlike [`at`](at.md), this function does not throw if the given `key`/`ptr` was not found.
|
|
- 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.
|
|
|
|
!!! note "Integer keys"
|
|
|
|
Calling this function with an integer `key` argument (for example, `#!cpp value(0, 1)`) does not compile in
|
|
C++11, where `object_comparator_t` is not transparent: such an argument would otherwise implicitly convert to a
|
|
null `#!cpp const char*` and, from there, cause undefined behavior when constructing a `#!cpp std::string` for the
|
|
object key. To access an array element with a default value, use [`at`](at.md) together with a `#!cpp try`/`#!cpp
|
|
catch` block, or compare against [`size`](size.md) instead.
|
|
|
|
## Template parameters
|
|
|
|
`KeyType`
|
|
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
|
|
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
|
|
This can also be a string view (C++17).
|
|
`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
|
|
2. copy of the element at key `key` or `default_value` if `key` is not found
|
|
3. 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 the 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. See 1.
|
|
3. The function can throw the 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 array
|
|
or object; in that case, using `value()` with a JSON pointer makes no sense.
|
|
- 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.
|
|
|
|
## Complexity
|
|
|
|
1. Logarithmic in the size of the container.
|
|
2. Logarithmic in the size of the container.
|
|
3. Logarithmic in the size of the container.
|
|
|
|
## Notes
|
|
|
|
!!! warning "`null` members are not missing"
|
|
|
|
The default value is used only if the key (or JSON Pointer) does not exist. A member that exists but is
|
|
`#!json null` is converted like any other value, so `#!cpp j.value("k", 0)` throws a
|
|
[`type_error.302`](../../home/exceptions.md#jsonexceptiontype_error302) if `"k"` is `#!json null`. See
|
|
[Access with default value](../../features/element_access/default_value.md)
|
|
for alternatives.
|
|
|
|
!!! warning "Return type"
|
|
|
|
The value function is a template, and the return type of the function is determined by the type of the provided
|
|
default value unless otherwise specified. This can have unexpected effects. In the example below, we store a 64-bit
|
|
unsigned integer. We get exactly that value when using [`operator[]`](operator[].md). However, when we call `value`
|
|
and provide `#!c 0` as default value, then `#!c -1` is returned. This occurs, because `#!c 0` has type `#!c int`
|
|
which overflows when handling the value `#!c 18446744073709551615`.
|
|
|
|
To address this issue, either provide a correctly typed default value or use the template parameter to specify the
|
|
desired return type. Note that this issue occurs even when a value is stored at the provided key, and the default
|
|
value is not used as the return value.
|
|
|
|
```cpp
|
|
--8<-- "examples/value__return_type.cpp"
|
|
```
|
|
|
|
Output:
|
|
|
|
```json
|
|
--8<-- "examples/value__return_type.output"
|
|
```
|
|
|
|
!!! warning "Deprecation"
|
|
|
|
Overload (3) also accepts a [`json_pointer`](../json_pointer/index.md) whose template argument is a `basic_json`
|
|
specialization (e.g., `nlohmann::json_pointer<nlohmann::json>`) instead of a string type. This is deprecated since
|
|
version 3.11.0 and will be removed in a future major version; use `basic_json::json_pointer` (for `json`,
|
|
`nlohmann::json_pointer<std::string>`) instead.
|
|
|
|
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
|
|
function.
|
|
|
|
See the [migration guide](../../integration/migration_guide.md#json-pointers) for how to update existing code.
|
|
|
|
## Examples
|
|
|
|
??? example "Example: (1) access specified object element with default value"
|
|
|
|
The example below shows how object elements can be queried with a default value.
|
|
|
|
```cpp
|
|
--8<-- "examples/value__object_t_key_type.cpp"
|
|
```
|
|
|
|
Output:
|
|
|
|
```json
|
|
--8<-- "examples/value__object_t_key_type.output"
|
|
```
|
|
|
|
??? example "Example: (2) access specified object element using string_view with default value"
|
|
|
|
The example below shows how object elements can be queried with a default value.
|
|
|
|
```cpp
|
|
--8<-- "examples/value__keytype.c++17.cpp"
|
|
```
|
|
|
|
Output:
|
|
|
|
```json
|
|
--8<-- "examples/value__keytype.c++17.output"
|
|
```
|
|
|
|
??? example "Example: (3) access specified object element via JSON Pointer with default value"
|
|
|
|
The example below shows how object elements can be queried with a default value.
|
|
|
|
```cpp
|
|
--8<-- "examples/value__json_ptr.cpp"
|
|
```
|
|
|
|
Output:
|
|
|
|
```json
|
|
--8<-- "examples/value__json_ptr.output"
|
|
```
|
|
|
|
??? example "Example: (1) type_error.302 and type_error.306 exceptions"
|
|
|
|
The example below shows how `value()` throws `type_error.302` when the default value's type does not match the type
|
|
of the stored value, and `type_error.306` when `value()` is called on a JSON value that is not an object.
|
|
|
|
```cpp
|
|
--8<-- "examples/value__exception.cpp"
|
|
```
|
|
|
|
Output:
|
|
|
|
```json
|
|
--8<-- "examples/value__exception.output"
|
|
```
|
|
|
|
## See also
|
|
|
|
- see [`at`](at.md) for access by reference with range checking
|
|
- see [`operator[]`](operator%5B%5D.md) for unchecked access by reference
|
|
- [basic_json_view::value](../basic_json_view/value.md) - the same access on a zero-copy view
|
|
|
|
## Version history
|
|
|
|
1. Added in version 1.0.0. Changed parameter `default_value` type from `const ValueType&` to `ValueType&&` in version
|
|
3.11.0. Deleted overload for integral key types added in version 3.13.0 to reject such calls at compile time
|
|
instead of causing undefined behavior at runtime.
|
|
2. Added in version 3.11.0. Made `ValueType` the first template parameter in version 3.11.2. Fixed in version 3.13.0
|
|
to consistently accept `std::string_view`-convertible keys, as already supported by
|
|
[`operator[]`](operator[].md), [`at`](at.md), [`find`](find.md), and other lookup functions.
|
|
3. Added in version 2.0.2. Extended to work with arrays in version 3.13.0, including fixing an issue where resolving
|
|
`ptr` through an array unexpectedly threw `out_of_range` instead of returning the resolved element (or
|
|
`default_value`, as documented). Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109)
|
|
instead of returning `default_value` for a one-character array index that is not a digit (e.g., `/x`) in version
|
|
3.13.0, as it already did for longer ones.
|