operatorjson_pointer.cpp 1.3 KB

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