-
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
is it possible merge two json object #428
Comments
This is an interesting question. Currently, there is no |
(I should definitely have another look at all the overloads of |
I have also needed this type of functionality. For the time being until this is closed, I have been using this code which modifies the json object in place. One thing to consider is the desired behavior when Hopefully this helps for now. void extendJson(json &j1, const json &j2) {
for (const auto &j : json::iterator_wrapper(j2)) {
j1[j.key()] = j.value();
}
} |
Thanks for the hint. I shall have a look at the |
This implementation forwards the iterators to std::map::insert.
Here is a proposal for an insert function that takes an iterator range and can merge an object into another: 97a25de. Feedback very appreciated! |
I would prefer an shortcut that would overload json2 >> json1; That |
@AraHaan What exactly do you propose? We have several overloads for push_back and insert. And Python only interprets JSON objects as dict. Arrays are mapped to lists. |
@AraHaan I fear that overload of |
Thanks,It's good for me! |
Merged with 4b316ec. |
Great this has been added; #252 addresses a similar issue and I have used json merge( const json &a, const json &b )
{
json result = a.flatten();
json tmp = b.flatten();
for ( auto it = tmp.begin(); it != tmp.end(); ++it )
result[it.key()] = it.value();
return result.unflatten();
} I found the scenario below slightly counter-intuitive using the new approach, json j1 = { {"a",1} };
json j2 = { {"a",2} };
j1.insert(j2.begin(), j2.end()); // --> a=1 But perhaps this is also the behaviour of maps? |
|
We use std::map::insert internally to provide the least surprising behavior. I also would have needed to look up the behavior in case of a duplicate. |
That makes sense. I think the solution is simply to pay attention to order when merging, std::map<int, int> goodKeys;
std::map<int, int> betterKeys;
betterKeys.insert(goodKeys.begin(), goodKeys.end()); Thanks! |
some function like this
json1.join(json2) or
json1.merge(json2) or
json1 += json2
The text was updated successfully, but these errors were encountered: