at_json_pointer_const.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. using json = nlohmann::json;
  4. int main()
  5. {
  6. // create a JSON value
  7. const 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. // out_of_range.109
  21. try
  22. {
  23. // try to use an array index that is not a number
  24. json::const_reference ref = j.at("/array/one"_json_pointer);
  25. }
  26. catch (json::parse_error& e)
  27. {
  28. std::cout << e.what() << '\n';
  29. }
  30. // out_of_range.401
  31. try
  32. {
  33. // try to use a an invalid array index
  34. json::const_reference ref = j.at("/array/4"_json_pointer);
  35. }
  36. catch (json::out_of_range& e)
  37. {
  38. std::cout << e.what() << '\n';
  39. }
  40. // out_of_range.402
  41. try
  42. {
  43. // try to use the array index '-'
  44. json::const_reference ref = j.at("/array/-"_json_pointer);
  45. }
  46. catch (json::out_of_range& e)
  47. {
  48. std::cout << e.what() << '\n';
  49. }
  50. // out_of_range.403
  51. try
  52. {
  53. // try to use a JSON pointer to an nonexistent object key
  54. json::const_reference ref = j.at("/foo"_json_pointer);
  55. }
  56. catch (json::out_of_range& e)
  57. {
  58. std::cout << e.what() << '\n';
  59. }
  60. // out_of_range.404
  61. try
  62. {
  63. // try to use a JSON pointer that cannot be resolved
  64. json::const_reference ref = j.at("/number/foo"_json_pointer);
  65. }
  66. catch (json::out_of_range& e)
  67. {
  68. std::cout << e.what() << '\n';
  69. }
  70. }