deep copy (or merge?) #3006
Replies: 3 comments 7 replies
-
The |
Beta Was this translation helpful? Give feedback.
-
If anyone comes across this discussion topic in the future, this is how I got it working: nlohmann::json merge(const nlohmann::json & lhs, const nlohmann::json & rhs)
{
// start with the full LHS json, into which we'll copy everything from RHS
nlohmann::json j = lhs;
// if a key exists in both LHS and RHS, then we keep RHS
for (auto it = rhs.cbegin(); it != rhs.cend(); ++it)
{
const auto & key = it.key();
if (it->is_object())
{
if (lhs.contains(key))
{
// object already exists (must merge)
j[key] = merge(lhs[key], rhs[key]);
}
else
{
// object does not exist in LHS, so use the RHS
j[key] = rhs[key];
}
}
else
{
// this is an individual item, use RHS
j[key] = it.value();
}
}
return j;
} Then I call it like this: auto user_settings = nlohmann::json::parse(...);
auto default_settings = get_default_settings(); // obtain defaults as a JSON object from within my app
auto combined_settings = merge(default_settings, user_settings); |
Beta Was this translation helpful? Give feedback.
-
Fixed up code above as you commented just in case someone comes across this issue and wants to re-use the code. Thanks for pointing it out. |
Beta Was this translation helpful? Give feedback.
-
I see the discussion in issue #661 about
update()
. This almost does what I was looking for, but not quite.I have 2 json objects: the user settings, and then the defaults. I would like to merge this together into 1 json. But say the defaults look like this:
If the user settings is empty, then when I call this code everything works fine:
But if the user has even 1 item, such as:
Then when I call update(), the user's
settings
object completely overwrites all the other settings, and I lose the default values. What I was looking for in this example is for "blue" to overwrite "red" without losing everything else that came from the defaults.Does this exist?
Beta Was this translation helpful? Give feedback.
All reactions