You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3 KiB

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