Skip to content

Commit

Permalink
Fix patch::add creating nonexistent parents
Browse files Browse the repository at this point in the history
The previous behavior was not in accordance with RFC6902.
Add unit test.

Fixes nlohmann#3134.
  • Loading branch information
Hudson00 authored and falbrechtskirchinger committed Jul 29, 2022
1 parent e3095f6 commit 6eb5329
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
3 changes: 2 additions & 1 deletion include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4683,7 +4683,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)
{
Expand Down
3 changes: 2 additions & 1 deletion single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -23527,7 +23527,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)
{
Expand Down
10 changes: 10 additions & 0 deletions tests/src/unit-json_patch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ TEST_CASE("JSON patch")

// because "a" does not exist.
CHECK_THROWS_WITH_AS(doc2.patch(patch), "[json.exception.out_of_range.403] key 'a' not found", json::out_of_range&);

json doc3 = R"({ "a": {} })"_json;
json patch2 = R"([{ "op": "add", "path": "/a/b/c", "value": 1 }])"_json;

// should cause an error because "b" does not exist in doc3
#if JSON_DIAGNOSTICS
CHECK_THROWS_WITH_AS(doc3.patch(patch2), "[json.exception.out_of_range.403] (/a) key 'b' not found", json::out_of_range&);
#else
CHECK_THROWS_WITH_AS(doc3.patch(patch2), "[json.exception.out_of_range.403] key 'b' not found", json::out_of_range&);
#endif
}

SECTION("4.2 remove")
Expand Down

0 comments on commit 6eb5329

Please sign in to comment.