2
0

operator_array__json_pointer.cpp 1.3 KB

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