2017-07-09 11:51:38 +02:00
|
|
|
#include <iostream>
|
2018-02-01 22:20:26 +01:00
|
|
|
#include <nlohmann/json.hpp>
|
2015-06-24 12:15:51 +02:00
|
|
|
|
2016-01-30 20:23:14 +01:00
|
|
|
using json = nlohmann::json;
|
2015-06-24 12:15:51 +02:00
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
// create JSON object
|
2020-02-26 06:44:08 +01:00
|
|
|
const json object =
|
2015-06-24 12:15:51 +02:00
|
|
|
{
|
|
|
|
{"the good", "il buono"},
|
2017-01-27 18:50:52 +01:00
|
|
|
{"the bad", "il cattivo"},
|
2015-06-24 12:15:51 +02:00
|
|
|
{"the ugly", "il brutto"}
|
|
|
|
};
|
|
|
|
|
|
|
|
// output element with key "the ugly"
|
|
|
|
std::cout << object.at("the ugly") << '\n';
|
|
|
|
|
2017-03-12 13:49:39 +01:00
|
|
|
|
|
|
|
// exception type_error.304
|
|
|
|
try
|
|
|
|
{
|
|
|
|
// use at() on a non-object type
|
|
|
|
const json str = "I am a string";
|
|
|
|
std::cout << str.at("the good") << '\n';
|
|
|
|
}
|
|
|
|
catch (json::type_error& e)
|
|
|
|
{
|
|
|
|
std::cout << e.what() << '\n';
|
|
|
|
}
|
|
|
|
|
|
|
|
// exception out_of_range.401
|
2015-06-24 12:15:51 +02:00
|
|
|
try
|
|
|
|
{
|
2017-03-12 13:49:39 +01:00
|
|
|
// try to read from a nonexisting key
|
2015-06-24 12:15:51 +02:00
|
|
|
std::cout << object.at("the fast") << '\n';
|
|
|
|
}
|
2017-03-08 21:03:19 +01:00
|
|
|
catch (json::out_of_range)
|
2015-06-24 12:15:51 +02:00
|
|
|
{
|
|
|
|
std::cout << "out of range" << '\n';
|
|
|
|
}
|
|
|
|
}
|