* 📡 Fix documentation gaps found in a full GitHub Discussions review Reviewed all 1008 GitHub Discussions (2020-2026) for recurring questions that better or more visible documentation would have avoided. Adds/expands documentation for ~26 distinct gaps, including: - New "Debugging" page collecting natvis, GDB pretty printer, LLDB status, and JSON_DIAGNOSTICS pointers (previously scattered/undiscoverable) - Thread-safety and schema-validation FAQ entries - StringType's char-based requirement (no wstring/u16string/u32string) - Brace-initialization-yields-arrays warning directly on the constructor reference page (previously only in the FAQ, missed by users reading the constructor docs) - std::any exclusion from get<T>(), with a manual-dispatch example - Non-string-keyed std::map serializing as an array of pairs - ordered_json compatibility with NLOHMANN_DEFINE_TYPE_* macros (already worked, was undocumented) - std::array truncation on size-mismatched conversion (no exception) - static_cast vs. get<std::optional<T>>() divergence - Recipe for omitting a std::optional field instead of emitting null - No built-in nesting-depth limit during parsing + a callback-based workaround recipe - Recipe for streaming a large homogeneous array via parser callbacks - operator>> stream-position semantics for concatenated JSON values - JSON Pointer array-vs-object creation rule for non-existing paths - CMake target name (nlohmann_json_modules) needed to link C++20 modules - ESP-IDF/PlatformIO: no official package, link to a community fork - get(key, default) as the Python dict.get() equivalent - reserve() recipe for pre-allocating array capacity - JSONC as an alias for the existing ignore_comments/ignore_trailing_commas combination (distinct from the unsupported JSON5) - items() dereferenced-element type: decltype() idiom + detail-namespace stability caveat - Various macro/type-conversion limitations (MSGPACK_DEFINE_ARRAY equivalent, char-array round-tripping, ADL serializer macro gap) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * 🚶 fix format Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
6.7 KiB
nlohmann::basic_json::value
// (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).
-
Returns either a copy of an object's element at the specified key
keyor a given default value if no element with keykeyexists.The function is basically equivalent to executing
try { return at(key); } catch(out_of_range) { return default_value; } -
See 1. This overload is only available if
KeyTypeis comparable with#!cpp typename object_t::key_typeand#!cpp typename object_comparator_t::is_transparentdenotes a type. -
Returns either a copy of an object's element at the specified JSON pointer
ptror a given default value if no value atptrexists.The function is basically equivalent to executing
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.
Template parameters
KeyType- A type for an object key other than
json_pointerthat is comparable withstring_tusingobject_comparator_t. This can also be a string view (C++17).ValueType - type compatible to JSON values, for instance
#!cpp intfor JSON integer numbers,#!cpp boolfor JSON booleans, or#!cpp std::vectortypes for JSON arrays. Note the type of the expected value atkey/ptrand the default valuedefault_valuemust be compatible.
Parameters
key(in)- key of the element to access
default_value(in)- the value to return if
key/ptrfound no value ptr(in)- a JSON pointer to the element to access
Return value
- copy of the element at key
keyordefault_valueifkeyis not found - copy of the element at key
keyordefault_valueifkeyis not found - copy of the element at JSON Pointer
ptrordefault_valueif no value forptris found
Exception safety
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
Exceptions
- The function can throw the following exceptions:
- Throws
type_error.302ifdefault_valuedoes not match the type of the value atkey - Throws
type_error.306if the JSON value is not an object; in that case, usingvalue()with a key makes no sense.
- Throws
- See 1.
- The function can throw the following exceptions:
- Throws
type_error.302ifdefault_valuedoes not match the type of the value atptr - Throws
type_error.306if the JSON value is not an array or object; in that case, usingvalue()with a JSON pointer makes no sense. - Throws
parse_error.106if an array index in the passed JSON pointerptrbegins with '0'. - Throws
parse_error.109if an array index in the passed JSON pointerptris not a number.
- Throws
Complexity
- Logarithmic in the size of the container.
- Logarithmic in the size of the container.
- Logarithmic in the size of the container.
Notes
!!! 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"
```
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"
```
See also
- see
atfor access by reference with range checking - see
operator[]for unchecked access by reference
Version history
- Added in version 1.0.0. Changed parameter
default_valuetype fromconst ValueType&toValueType&&in version 3.11.0. - Added in version 3.11.0. Made
ValueTypethe first template parameter in version 3.11.2. - Added in version 2.0.2. Extended to work with arrays in version 3.13.0, including fixing an issue where resolving
ptrthrough an array unexpectedly threwout_of_rangeinstead of returning the resolved element (ordefault_value, as documented).