diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp index 7ea86c38c2..5337e53145 100644 --- a/include/nlohmann/json.hpp +++ b/include/nlohmann/json.hpp @@ -8456,7 +8456,8 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); - basic_json& parent = result[ptr]; + // parent must exist when performing patch add per RFC6902 specs + basic_json& parent = result.at(ptr); switch (parent.m_type) { diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 5800976306..f4407577ba 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -25996,7 +25996,8 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); - basic_json& parent = result[ptr]; + // parent must exist when performing patch add per RFC6902 specs + basic_json& parent = result.at(ptr); switch (parent.m_type) { diff --git a/test/src/unit-json_patch.cpp b/test/src/unit-json_patch.cpp index 95af671986..17299722c0 100644 --- a/test/src/unit-json_patch.cpp +++ b/test/src/unit-json_patch.cpp @@ -83,6 +83,14 @@ TEST_CASE("JSON patch") CHECK_THROWS_AS(doc2.patch(patch), json::out_of_range&); CHECK_THROWS_WITH(doc2.patch(patch), "[json.exception.out_of_range.403] key 'a' not found"); + + json doc3 = R"({ "a": {} })"_json; + json patch3 = R"([{ "op": "add", "path": "/a/b/c", "value": 1 }])"_json; + + // patch3 should cause an error because "b" does not exist in doc3 + CHECK_THROWS_AS(doc3.patch(patch3), json::out_of_range&); + CHECK_THROWS_WITH(doc3.patch(patch3), + "[json.exception.out_of_range.403] key 'b' not found"); } SECTION("4.2 remove")