• 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["/number"_json_pointer] << '\n';
19     // output element with JSON pointer "/string"
20     std::cout << j["/string"_json_pointer] << '\n';
21     // output element with JSON pointer "/array"
22     std::cout << j["/array"_json_pointer] << '\n';
23     // output element with JSON pointer "/array/1"
24     std::cout << j["/array/1"_json_pointer] << '\n';
25 
26     // writing access
27 
28     // change the string
29     j["/string"_json_pointer] = "bar";
30     // output the changed string
31     std::cout << j["string"] << '\n';
32 
33     // "change" a nonexisting object entry
34     j["/boolean"_json_pointer] = true;
35     // output the changed object
36     std::cout << j << '\n';
37 
38     // change an array element
39     j["/array/1"_json_pointer] = 21;
40     // "change" an array element with nonexisting index
41     j["/array/4"_json_pointer] = 44;
42     // output the changed array
43     std::cout << j["array"] << '\n';
44 
45     // "change" the array element past the end
46     j["/array/-"_json_pointer] = 55;
47     // output the changed array
48     std::cout << j["array"] << '\n';
49 }
50