1 #include <iostream> 2 #include <nlohmann/json.hpp> 3 4 using json = nlohmann::json; 5 using namespace nlohmann::literals; 6 main()7int main() 8 { 9 // create a JSON value 10 json j = 11 { 12 {"number", 1}, {"string", "foo"}, {"array", {1, 2}} 13 }; 14 15 // read-only access 16 17 // output element with JSON pointer "/number" 18 std::cout << j.at("/number"_json_pointer) << '\n'; 19 // output element with JSON pointer "/string" 20 std::cout << j.at("/string"_json_pointer) << '\n'; 21 // output element with JSON pointer "/array" 22 std::cout << j.at("/array"_json_pointer) << '\n'; 23 // output element with JSON pointer "/array/1" 24 std::cout << j.at("/array/1"_json_pointer) << '\n'; 25 26 // writing access 27 28 // change the string 29 j.at("/string"_json_pointer) = "bar"; 30 // output the changed string 31 std::cout << j["string"] << '\n'; 32 33 // change an array element 34 j.at("/array/1"_json_pointer) = 21; 35 // output the changed array 36 std::cout << j["array"] << '\n'; 37 38 // out_of_range.106 39 try 40 { 41 // try to use an array index with leading '0' 42 json::reference ref = j.at("/array/01"_json_pointer); 43 } 44 catch (const json::parse_error& e) 45 { 46 std::cout << e.what() << '\n'; 47 } 48 49 // out_of_range.109 50 try 51 { 52 // try to use an array index that is not a number 53 json::reference ref = j.at("/array/one"_json_pointer); 54 } 55 catch (const json::parse_error& e) 56 { 57 std::cout << e.what() << '\n'; 58 } 59 60 // out_of_range.401 61 try 62 { 63 // try to use an invalid array index 64 json::reference ref = j.at("/array/4"_json_pointer); 65 } 66 catch (const json::out_of_range& e) 67 { 68 std::cout << e.what() << '\n'; 69 } 70 71 // out_of_range.402 72 try 73 { 74 // try to use the array index '-' 75 json::reference ref = j.at("/array/-"_json_pointer); 76 } 77 catch (const json::out_of_range& e) 78 { 79 std::cout << e.what() << '\n'; 80 } 81 82 // out_of_range.403 83 try 84 { 85 // try to use a JSON pointer to a nonexistent object key 86 json::const_reference ref = j.at("/foo"_json_pointer); 87 } 88 catch (const json::out_of_range& e) 89 { 90 std::cout << e.what() << '\n'; 91 } 92 93 // out_of_range.404 94 try 95 { 96 // try to use a JSON pointer that cannot be resolved 97 json::reference ref = j.at("/number/foo"_json_pointer); 98 } 99 catch (const json::out_of_range& e) 100 { 101 std::cout << e.what() << '\n'; 102 } 103 } 104