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 array
|
2017-03-12 13:49:39 +01:00
|
|
|
const json array = {"first", "2nd", "third", "fourth"};
|
2015-06-24 12:15:51 +02:00
|
|
|
|
|
|
|
// output element at index 2 (third element)
|
|
|
|
std::cout << array.at(2) << '\n';
|
|
|
|
|
2017-03-12 13:49:39 +01:00
|
|
|
// exception type_error.304
|
|
|
|
try
|
|
|
|
{
|
|
|
|
// use at() on a non-array type
|
|
|
|
const json str = "I am a string";
|
|
|
|
std::cout << str.at(0) << '\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 beyond the array limit
|
2015-06-24 12:15:51 +02:00
|
|
|
std::cout << array.at(5) << '\n';
|
|
|
|
}
|
2017-03-12 13:49:39 +01:00
|
|
|
catch (json::out_of_range& e)
|
2015-06-24 12:15:51 +02:00
|
|
|
{
|
2017-03-08 23:12:13 +01:00
|
|
|
std::cout << e.what() << '\n';
|
2015-06-24 12:15:51 +02:00
|
|
|
}
|
|
|
|
}
|