at_json_pointer.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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.at("/number"_json_pointer) << '\n';
  14. // output element with JSON pointer "/string"
  15. std::cout << j.at("/string"_json_pointer) << '\n';
  16. // output element with JSON pointer "/array"
  17. std::cout << j.at("/array"_json_pointer) << '\n';
  18. // output element with JSON pointer "/array/1"
  19. std::cout << j.at("/array/1"_json_pointer) << '\n';
  20. // writing access
  21. // change the string
  22. j.at("/string"_json_pointer) = "bar";
  23. // output the changed string
  24. std::cout << j["string"] << '\n';
  25. // change an array element
  26. j.at("/array/1"_json_pointer) = 21;
  27. // output the changed array
  28. std::cout << j["array"] << '\n';
  29. // out_of_range.106
  30. try
  31. {
  32. // try to use an array index with leading '0'
  33. json::reference ref = j.at("/array/01"_json_pointer);
  34. }
  35. catch (json::parse_error& e)
  36. {
  37. std::cout << e.what() << '\n';
  38. }
  39. // out_of_range.109
  40. try
  41. {
  42. // try to use an array index that is not a number
  43. json::reference ref = j.at("/array/one"_json_pointer);
  44. }
  45. catch (json::parse_error& e)
  46. {
  47. std::cout << e.what() << '\n';
  48. }
  49. // out_of_range.401
  50. try
  51. {
  52. // try to use a an invalid array index
  53. json::reference ref = j.at("/array/4"_json_pointer);
  54. }
  55. catch (json::out_of_range& e)
  56. {
  57. std::cout << e.what() << '\n';
  58. }
  59. // out_of_range.402
  60. try
  61. {
  62. // try to use the array index '-'
  63. json::reference ref = j.at("/array/-"_json_pointer);
  64. }
  65. catch (json::out_of_range& e)
  66. {
  67. std::cout << e.what() << '\n';
  68. }
  69. // out_of_range.403
  70. try
  71. {
  72. // try to use a JSON pointer to an nonexistent object key
  73. json::const_reference ref = j.at("/foo"_json_pointer);
  74. }
  75. catch (json::out_of_range& e)
  76. {
  77. std::cout << e.what() << '\n';
  78. }
  79. // out_of_range.404
  80. try
  81. {
  82. // try to use a JSON pointer that cannot be resolved
  83. json::reference ref = j.at("/number/foo"_json_pointer);
  84. }
  85. catch (json::out_of_range& e)
  86. {
  87. std::cout << e.what() << '\n';
  88. }
  89. }