Skip to content

Commit 376be93

Browse files
improve algorithm efficiency
Signed-off-by: Luís Murta <luis@murta.dev>
1 parent 8c10cd2 commit 376be93

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

include/nlohmann/json.hpp

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5272,14 +5272,22 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
52725272
auto itf = target.find(it.key());
52735273
if (itf != target.end())
52745274
{
5275-
if (it.value() != itf.value())
5275+
if (!it.value().is_null() && itf.value().is_null())
5276+
{
5277+
JSON_THROW(other_error::create(503, detail::concat("cannot set \"", it.key(), "\" to null"), &source));
5278+
}
5279+
5280+
if (it.value().is_object())
52765281
{
52775282
auto diff = merge_diff(it.value(), itf.value());
5278-
if (diff.is_null())
5283+
if (!diff.empty())
52795284
{
5280-
JSON_THROW(other_error::create(503, detail::concat("cannot set \"", itf.key(), "\" to null"), &target));
5285+
result[it.key()] = std::move(diff);
52815286
}
5282-
result[it.key()] = merge_diff(it.value(), itf.value());
5287+
}
5288+
else if (it.value() != itf.value())
5289+
{
5290+
result[it.key()] = itf.value();
52835291
}
52845292
}
52855293
else

tests/src/unit-merge_diff.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,24 @@ TEST_CASE("JSON Merge Patch")
399399
original.merge_patch(json::merge_diff(original, result));
400400
CHECK(original == result);
401401
}
402+
403+
SECTION("object to primitive")
404+
{
405+
json original = R"({"a":{"b":"c"}})"_json;
406+
json result = R"({"a":1})"_json;
407+
408+
original.merge_patch(json::merge_diff(original, result));
409+
CHECK(original == result);
410+
}
411+
412+
SECTION("primitive to object")
413+
{
414+
json original = R"({"a":1})"_json;
415+
json result = R"({"a":{"b":"c"}})"_json;
416+
417+
original.merge_patch(json::merge_diff(original, result));
418+
CHECK(original == result);
419+
}
402420
}
403421

404422
SECTION("arrays")
@@ -429,5 +447,14 @@ TEST_CASE("JSON Merge Patch")
429447
original.merge_patch(json::merge_diff(original, result));
430448
CHECK(original == result);
431449
}
450+
451+
SECTION("same keys")
452+
{
453+
json original = R"(["a","b"])"_json;
454+
json result = R"({"a":1,"b":2})"_json;
455+
456+
original.merge_patch(json::merge_diff(original, result));
457+
CHECK(original == result);
458+
}
432459
}
433460
}

0 commit comments

Comments
 (0)