• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <iostream>
2 #include <nlohmann/json.hpp>
3 
4 using json = nlohmann::json;
5 
main()6 int main()
7 {
8     // create a JSON value
9     json j =
10     {
11         {"number", 1}, {"string", "foo"}, {"array", {1, 2}}
12     };
13 
14     // read-only access
15 
16     // output element with JSON pointer "/number"
17     std::cout << j["/number"_json_pointer] << '\n';
18     // output element with JSON pointer "/string"
19     std::cout << j["/string"_json_pointer] << '\n';
20     // output element with JSON pointer "/array"
21     std::cout << j["/array"_json_pointer] << '\n';
22     // output element with JSON pointer "/array/1"
23     std::cout << j["/array/1"_json_pointer] << '\n';
24 
25     // writing access
26 
27     // change the string
28     j["/string"_json_pointer] = "bar";
29     // output the changed string
30     std::cout << j["string"] << '\n';
31 
32     // "change" a nonexisting object entry
33     j["/boolean"_json_pointer] = true;
34     // output the changed object
35     std::cout << j << '\n';
36 
37     // change an array element
38     j["/array/1"_json_pointer] = 21;
39     // "change" an array element with nonexisting index
40     j["/array/4"_json_pointer] = 44;
41     // output the changed array
42     std::cout << j["array"] << '\n';
43 
44     // "change" the array element past the end
45     j["/array/-"_json_pointer] = 55;
46     // output the changed array
47     std::cout << j["array"] << '\n';
48 }
49