Repository navigation
deep copy (or merge?) #3006
stephanecharette
started this conversation in
Ideas
Replies: 3 comments 7 replies
|
The |
2 replies
|
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); |
5 replies
|
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. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
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:
{ "settings": { "mouse" : true, "colour" : "red", stuff : { init : "foo", shutdown : "bar" } } }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:
{ "settings":{ "colour":"blue" } }Then when I call update(), the user's
settingsobject 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?
All reactions