mirror of
https://github.com/nlohmann/json.git
synced 2025-07-06 06:42:33 +03:00
fix for #133
added value() function to get object value at given key or a default value if key does not exist
This commit is contained in:
29
doc/examples/basic_json__value.cpp
Normal file
29
doc/examples/basic_json__value.cpp
Normal file
@ -0,0 +1,29 @@
|
||||
#include <json.hpp>
|
||||
|
||||
using namespace nlohmann;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON object with different entry types
|
||||
json j =
|
||||
{
|
||||
{"integer", 1},
|
||||
{"floating", 42.23},
|
||||
{"string", "hello world"},
|
||||
{"boolean", true},
|
||||
{"object", {{"key1", 1}, {"key2", 2}}},
|
||||
{"array", {1, 2, 3}}
|
||||
};
|
||||
|
||||
// access existing values
|
||||
int v_integer = j.value("integer", 0);
|
||||
double v_floating = j.value("floating", 47.11);
|
||||
|
||||
// access nonexisting values and rely on default value
|
||||
std::string v_string = j.value("nonexisting", "oops");
|
||||
bool v_boolean = j.value("nonexisting", false);
|
||||
|
||||
// output values
|
||||
std::cout << std::boolalpha << v_integer << " " << v_floating
|
||||
<< " " << v_string << " " << v_boolean << "\n";
|
||||
}
|
Reference in New Issue
Block a user