|
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<class ValueType , typename std::enable_if< std::is_convertible< basic_json_t, ValueType >::value, int >::type = 0>
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 try { } catch(std::out_of_range) { return default_value; } - Note
- Unlike at(const json_pointer&), this function does not throw if the given key key was not found.
- Parameters
-
[in] | ptr | a JSON pointer to the element to access |
[in] | default_value | the value to return if ptr found no value |
- Template Parameters
-
ValueType | type compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key and the default value default_value must be compatible. |
- Returns
- copy of the element at key key or default_value if key is not found
- Exceptions
-
std::domain_error | if JSON is not an object; example: "cannot use
value() with null" |
- Complexity
- Logarithmic in the size of the container.
- Example
- The example below shows how object elements can be queried with a default value.
12 { "string", "hello world"}, 14 { "object", {{ "key1", 1}, { "key2", 2}}}, 19 int v_integer = j.value( "/integer"_json_pointer, 0); 20 double v_floating = j.value( "/floating"_json_pointer, 47.11); 23 std::string v_string = j.value( "/nonexisting"_json_pointer, "oops"); 24 bool v_boolean = j.value( "/nonexisting"_json_pointer, false); 27 std::cout << std::boolalpha << v_integer << " " << v_floating 28 << " " << v_string << " " << v_boolean << "\n"; basic_json<> json default JSON class
Output (play with this example online): 1 42.23 oops false
The example code above can be translated withg++ -std=c++11 -Isrc doc/examples/basic_json__value_ptr.cpp -o basic_json__value_ptr
- See also
- operator[](const json_pointer&) for unchecked access by reference
- Since
- version 2.0.2
Definition at line 3769 of file json.hpp.
|