• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <iostream>
2 #include <nlohmann/json.hpp>
3 
4 using json = nlohmann::json;
5 using namespace nlohmann::literals;
6 
main()7 int main()
8 {
9     // create a JSON value
10     json j =
11     {
12         {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
13     };
14 
15     // read-only access
16 
17     // output element with JSON pointer "/number"
18     std::cout << j.at("/number"_json_pointer) << '\n';
19     // output element with JSON pointer "/string"
20     std::cout << j.at("/string"_json_pointer) << '\n';
21     // output element with JSON pointer "/array"
22     std::cout << j.at("/array"_json_pointer) << '\n';
23     // output element with JSON pointer "/array/1"
24     std::cout << j.at("/array/1"_json_pointer) << '\n';
25 
26     // writing access
27 
28     // change the string
29     j.at("/string"_json_pointer) = "bar";
30     // output the changed string
31     std::cout << j["string"] << '\n';
32 
33     // change an array element
34     j.at("/array/1"_json_pointer) = 21;
35     // output the changed array
36     std::cout << j["array"] << '\n';
37 
38 
39     // out_of_range.106
40     try
41     {
42         // try to use an array index with leading '0'
43         json::reference ref = j.at("/array/01"_json_pointer);
44     }
45     catch (json::parse_error& e)
46     {
47         std::cout << e.what() << '\n';
48     }
49 
50     // out_of_range.109
51     try
52     {
53         // try to use an array index that is not a number
54         json::reference ref = j.at("/array/one"_json_pointer);
55     }
56     catch (json::parse_error& e)
57     {
58         std::cout << e.what() << '\n';
59     }
60 
61     // out_of_range.401
62     try
63     {
64         // try to use an invalid array index
65         json::reference ref = j.at("/array/4"_json_pointer);
66     }
67     catch (json::out_of_range& e)
68     {
69         std::cout << e.what() << '\n';
70     }
71 
72     // out_of_range.402
73     try
74     {
75         // try to use the array index '-'
76         json::reference ref = j.at("/array/-"_json_pointer);
77     }
78     catch (json::out_of_range& e)
79     {
80         std::cout << e.what() << '\n';
81     }
82 
83     // out_of_range.403
84     try
85     {
86         // try to use a JSON pointer to a nonexistent object key
87         json::const_reference ref = j.at("/foo"_json_pointer);
88     }
89     catch (json::out_of_range& e)
90     {
91         std::cout << e.what() << '\n';
92     }
93 
94     // out_of_range.404
95     try
96     {
97         // try to use a JSON pointer that cannot be resolved
98         json::reference ref = j.at("/number/foo"_json_pointer);
99     }
100     catch (json::out_of_range& e)
101     {
102         std::cout << e.what() << '\n';
103     }
104 }
105