xref: /third_party/json/docs/examples/object.cpp (revision c5f01b2f)
1#include <iostream>
2#include <nlohmann/json.hpp>
3
4using json = nlohmann::json;
5
6int main()
7{
8    // create JSON objects
9    json j_no_init_list = json::object();
10    json j_empty_init_list = json::object({});
11    json j_list_of_pairs = json::object({ {"one", 1}, {"two", 2} });
12
13    // serialize the JSON objects
14    std::cout << j_no_init_list << '\n';
15    std::cout << j_empty_init_list << '\n';
16    std::cout << j_list_of_pairs << '\n';
17
18    // example for an exception
19    try
20    {
21        // can only create an object from a list of pairs
22        json j_invalid_object = json::object({{ "one", 1, 2 }});
23    }
24    catch (json::type_error& e)
25    {
26        std::cout << e.what() << '\n';
27    }
28}
29