• 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     const 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     // out_of_range.109
27     try
28     {
29         // try to use an array index that is not a number
30         json::const_reference ref = j.at("/array/one"_json_pointer);
31     }
32     catch (json::parse_error& e)
33     {
34         std::cout << e.what() << '\n';
35     }
36 
37     // out_of_range.401
38     try
39     {
40         // try to use an invalid array index
41         json::const_reference ref = j.at("/array/4"_json_pointer);
42     }
43     catch (json::out_of_range& e)
44     {
45         std::cout << e.what() << '\n';
46     }
47 
48     // out_of_range.402
49     try
50     {
51         // try to use the array index '-'
52         json::const_reference ref = j.at("/array/-"_json_pointer);
53     }
54     catch (json::out_of_range& e)
55     {
56         std::cout << e.what() << '\n';
57     }
58 
59     // out_of_range.403
60     try
61     {
62         // try to use a JSON pointer to a nonexistent object key
63         json::const_reference ref = j.at("/foo"_json_pointer);
64     }
65     catch (json::out_of_range& e)
66     {
67         std::cout << e.what() << '\n';
68     }
69 
70     // out_of_range.404
71     try
72     {
73         // try to use a JSON pointer that cannot be resolved
74         json::const_reference ref = j.at("/number/foo"_json_pointer);
75     }
76     catch (json::out_of_range& e)
77     {
78         std::cout << e.what() << '\n';
79     }
80 }
81