3.4 KiB
3.4 KiB
basic_json::value
// (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;
-
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; } -
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; }
Unlike operator[], 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 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/ptr found 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 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 thw 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
- The function can throw thw 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 object; in that case, usingvalue()with a key makes no sense.
- Throws
Complexity
- Logarithmic in the size of the container.
- 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
- Added in version 1.0.0.
- Added in version 2.0.2.