• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <iostream>
2 #include <unordered_map>
3 #include <nlohmann/json.hpp>
4 
5 using json = nlohmann::json;
6 
main()7 int main()
8 {
9     // create a JSON value with different types
10     json json_types =
11     {
12         {"boolean", true},
13         {
14             "number", {
15                 {"integer", 42},
16                 {"floating-point", 17.23}
17             }
18         },
19         {"string", "Hello, world!"},
20         {"array", {1, 2, 3, 4, 5}},
21         {"null", nullptr}
22     };
23 
24     bool v1;
25     int v2;
26     short v3;
27     float v4;
28     int v5;
29     std::string v6;
30     std::vector<short> v7;
31     std::unordered_map<std::string, json> v8;
32 
33 
34     // use explicit conversions
35     json_types["boolean"].get_to(v1);
36     json_types["number"]["integer"].get_to(v2);
37     json_types["number"]["integer"].get_to(v3);
38     json_types["number"]["floating-point"].get_to(v4);
39     json_types["number"]["floating-point"].get_to(v5);
40     json_types["string"].get_to(v6);
41     json_types["array"].get_to(v7);
42     json_types.get_to(v8);
43 
44     // print the conversion results
45     std::cout << v1 << '\n';
46     std::cout << v2 << ' ' << v3 << '\n';
47     std::cout << v4 << ' ' << v5 << '\n';
48     std::cout << v6 << '\n';
49 
50     for (auto i : v7)
51     {
52         std::cout << i << ' ';
53     }
54     std::cout << "\n\n";
55 
56     for (auto i : v8)
57     {
58         std::cout << i.first << ": " << i.second << '\n';
59     }
60 }
61